Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger.Pow(BigInteger, BigInteger)?

Tags:

c#

biginteger

I'm trying to calculate a large number, which requires BigInteger.Pow(), but I need the exponent to also be a BigInteger and not int.

i.e.

BigInteger.Pow(BigInteger)

How can I achieve this?

EDIT: I came up with an answer. User dog helped me to achieve this.

public BigInteger Pow(BigInteger value, BigInteger exponent)
{
    BigInteger originalValue = value;
    while (exponent-- > 1)
        value = BigInteger.Multiply(value, originalValue);
    return value;
}
like image 905
avi12 Avatar asked May 13 '15 20:05

avi12


1 Answers

Just from the aspect of general maths, this doesn't make sense. That's why it's not implemented.

Think of this example: Your BigInteger number is 2 and you need to potentiate it by 1024. This means that the result is a 1 KB number (2^1024). Now imagine you take int.MaxValue: Then, your number will consume 2 GB of memory already. Using a BigInteger as an exponent would yield a number beyond memory capacity!


If your application requires numbers in this scale, where the number itself is too large for your memory, you probably want a solution that stores the number and the exponent separately, but that's something I can only speculate about since it's not part of your question.


If your your issue is that your exponent variable is a BigInteger, you can just cast it to int:

BigInteger.Pow(bigInteger, (int)exponent); // exponent is BigInteger
like image 167
bytecode77 Avatar answered Oct 16 '22 04:10

bytecode77