Calculating 2^N in C# with long data type where N is 1929439432949324 [closed]

萝らか妹 提交于 2019-12-02 13:19:19

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!