4

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.

1
  • 1
    When you directly type in a number it is being treated as an Int32 or Int64 literal. So if the number is to big for the DataType of which the literal is new BigInteger(<number>) can't be used. You will likely have to split this up.
    – Oliver Ulm
    Commented May 30, 2016 at 10:39

3 Answers 3

10

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"));
3
  • 2
    I'd just add that he needs to use BigInteger.Multiply then: BigInteger.Multiply( BigInteger.Parse("1253999939979969998746"), BigInteger.Parse("9999999999"));. Because that is what he has asked, the compiler error fix is just one issue. Commented May 30, 2016 at 10:42
  • Thanks @TimSchmelter Commented May 30, 2016 at 10:45
  • 2
    I've just noticed that the *-operator is overloaded so you can also use BigInteger result = bi1 * bi2;. Commented May 30, 2016 at 10:46
4

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

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.