Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger division in C#

I am writing a class which needs accurate division of the BigInteger class in C#.

Example:

BigInteger x = BigInteger.Parse("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
BigInteger y = BigInteger.Parse("2000000000000000000000000000000000000000000000000000000000000000000000000000000000000");

x /= y;

Console.WriteLine(x.ToString());

//Output = 0

The problem is that being an Integer, naturally it does not hold decimal values. How can I overcome this to get the real result of 0.5 (given example).

P.S. The solution must be able to accurately divide any BigInteger, not just the example!

like image 635
Matthew Layton Avatar asked Aug 08 '12 06:08

Matthew Layton


People also ask

How do you divide BigInt?

divide(BigInteger val) is used to calculate the division of two BigIntegers. BigInteger class internally uses array of integers for processing, the operation on object of BigIntegers are not as fast as on primitives.

What is BigInteger in C?

The BIGINT data type is a machine-independent method for representing numbers in the range of -2 63-1 to 2 63-1. ESQL/C provides routines that facilitate the conversion from the BIGINT data type to other data types in the C language. The BIGINT data type is internally represented with the ifx_int8_t structure.

How do you divide numbers in a string?

Initialize the large number along with a divisor. Iterate over the given number until we extract the part that is greater than the divisor. Now, iterate from where we left in the previous step until the end of the number. Divide the extracted part with a divisor and add it to the result.


1 Answers

What accuracy you need for the division? One way would be:

  • Multiply the numerator by, say, 1000
  • Divide the numbers
  • Convert the result to double and divide by 1000

The same in code:

BigInteger x = BigInteger.Parse("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
BigInteger y = BigInteger.Parse("2000000000000000000000000000000000000000000000000000000000000000000000000000000000000");

x *= 1000;
x /= y;
double result = (double)x;
result /= 1000;
Console.WriteLine(result);
like image 188
Ilmo Euro Avatar answered Oct 03 '22 22:10

Ilmo Euro