问题
Currently I need to calculate 2^N
, however N
can be as large as 1929238932899 and I'm stuck using a long data type which can't hold a number that large.
I've currently tried converting to 'BigInt' however I'm still stuck with the long data type restriction from what I've seen as well.
I have a function which calculates the power. However, with the long data type, it just returns 0 when the number gets too big. Note that this is just a generic recursive power function.
For example, with 2^6
its meant to return 64 and with 2^47
to return 140737488355328. However, when it becomes 2^8489289
, it just returns 0.
回答1:
To represent 2^N in binary form, you need N+1 bits (binary digits), that is
(1 929 439 432 949 324 + 1) / 8 = 241 179 929 118 665.6 bytes ~ 219 PiB for a single number, if you really want to work with it.
Or you can just write down 2^N in binary form: 1 followed by N zeroes.
回答2:
Since 2^N is an integer, you can represented it using Integer factorization.
You can put that in a class like this:
class FactorizedInteger {
private Dictionary<long, long> _factors = new Dictionary<long, long>();
public FactorizedInteger(long radix, long exponent) {
_factors[radix] = exponent;
}
public void Add(FactorizedInteger other) {
foreach(var factor in other._factors) {
if (_factors.ContainsKey(factor.Key)) {
_factors[factor.Key] += factor.Value;
} else {
_factors[factor.Key] = factor.Value;
}
}
}
public override string ToString() {
return "(" + String.Join(" + ", _factors.Select(p => $"{p.Key}^{p.Value}")) + ")";
}
}
As you can see, you can even add some mathematical operations without exhausting the memory of the computer. I've included Add as an example.
To use it:
var e1 = new FactorizedInteger(2, 1929238932899);
var e2 = new FactorizedInteger(2, 64);
Console.WriteLine(e1);
e1.Add(e2);
Console.WriteLine(e1);
Output:
(2^1929238932899)
(2^1929238932963)
This example needs to be made much smarter to be really usefull, but it is a possible representation of such large numbers.
来源:https://stackoverflow.com/questions/57721004/calculating-2n-in-c-sharp-with-long-data-type-where-n-is-1929439432949324