Mirjalal
Mirjalal

Reputation: 1352

multiply very big integer in .NET

Assume that you have big integers like 1253999939979969998746 and 9999999999. Is there anyway to multiply these big integers in C#?

Note: I've tried System.Numerics.BigInteger class constructor compiler says that integer is too long.

What's your suggestion?

p.s warn me if this question out of topics.

Upvotes: 4

Views: 3661

Answers (3)

Malik Khalil Ahmad
Malik Khalil Ahmad

Reputation: 6925

The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.

Example :

var num1 = BigInteger.Parse("1253999939979969998746");
var num2 = BigInteger.Parse("9999999999");
var result = BigInteger.Multiply(num1, num2);

NOTE : Namespace : System.Numerics

Upvotes: 4

user1666620
user1666620

Reputation: 4808

You need to use BigInteger.Parse.

BigInteger num = BigInteger.Parse("1253999939979969998746");

If you try to use an integer value like below

BigInteger num = 1253999939979969998746;

the right hand side needs to have a type, which by default will be an Int32 or a long. But since the number is too large to be an Int32 or a long, the conversion fails, hence the error you get.

As Tim Schmelter pointed out in a comment, to then do your multiplication, you can do the following:

BigInteger num = BigInteger.Multiply(BigInteger.Parse("1253999939979969998746"), 
                                     BigInteger.Parse("9999999999"));

Upvotes: 10

Slupka
Slupka

Reputation: 121

System.Numberics.BigInteger does not have upper or lower bounds for values. So the numbers you mentioned can be processed by the BigInteger class.

The compiler is complaining because you are probably trying to initialize the BigInteger from integer. You need to initialize it using byte array or parse from string.

Upvotes: 2

Related Questions