Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1000 digit number in C#

Tags:

c#

I am working on Project Euler and ran into an issue.

I am unable to use a 1000 digit number and wanted to know if I am doing something wrong or am just going about this solution in the wrong way and if so what would be best approach be?

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);
                }
            }
        }
    }
}
like image 282
monkeylumps Avatar asked Nov 28 '22 04:11

monkeylumps


1 Answers

I'm guessing the 'issue' you ran into (would be helpful to include error message) is that the compiler doesn't like the integer literal with 1000 digits so you can't initialise it with a very large integer literal. As others have noted, breaking the integer literal into multiple lines isn't valid either.

The number[x] = 1; lines work because the compiler can handle the integer literal 1 and because we're assigning it to a BigInteger it uses BigInteger's implicit operator to convert it to a BigInteger.


One simple method to get around your problem with the big integer literal is to use the BigInteger.Parse method to create your 1000 digit number.

BigInteger check = BigInteger.Parse("10000....", CultureInfo.InvariantCulture);

Another method could be to initialise it with a small int, then use maths to get to the number you want, as in Jon Skeet's answer.

like image 124
George Duckett Avatar answered Dec 15 '22 13:12

George Duckett