C#中的1000位数字

mon*_*mps 4 c#

我正在研究Project Euler并遇到了一个问题.

我无法使用1000位数字,想知道我是做错了什么,或者只是以错误的方式解决这个问题,如果是这样,最好的办法是什么?

C#

namespace ToThePowerOf
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger n = 1;
            int x = 0;
            BigInteger [] number;
            number = new BigInteger[149194];
            number[x] = 1;
            number[x + 1] = 1;
            x = 3; ;
            BigInteger check = 10000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                0000000000000000000000000000000
                                00000000000000000000000;

            for (int i = 99; i > 0; i--)
            {
                n = (n - 1) + (n - 2);
                number[x] = n;
                x++;
                if (n > check)
                {
                    Console.WriteLine(x);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*ett 14

我猜你遇到的'问题'(包括错误信息会有帮助)是编译器不喜欢1000位数的整数文字,所以你不能用非常大的整数文字初始化它.正如其他人所指出的那样,将整数文字分成多行也是无效的.

这些number[x] = 1;行是有效的,因为编译器可以处理整数文字1,因为我们将它分配给BigInteger它使用BigInteger隐式运算符将它转换为BigInteger.


使用大整数文字解决问题的一种简单方法是使用该BigInteger.Parse方法创建1000位数字.

BigInteger check = BigInteger.Parse("10000....", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

另一种方法可能是用一个小int初始化它,然后用数学来得到你想要的数字,就像Jon Skeet的回答一样.


Jon*_*eet 14

BigInteger在C#中没有文字支持.因此,虽然使用BigInteger不是不正确的,但您需要制定一种不同的实例化方法 - 例如new BigInteger(10).Pow(1000).


Cod*_*aos 5

这么大的文字是不可能的。整数文字最多可以为64位。

要获取较大的biginteger,可以从字符串转换,也可以计算数字而不是对其进行硬编码。在您的情况下,使用计算BigInteger.Pow(10, digits)是最干净的解决方案。