Search This Blog

Tuesday, December 14, 2010

Euler Problem 16

http://projecteuler.net/index.php?section=problems&id=16

What is the sum of all the numbers in the answer from 2^1000?

This is tricky because it’s a big number!

C# .NET3.5 does this…1.0715086071862673E+301
…which means I don’t have all the digits to add up…

As an aside.. here’s what python does when you ask it for 2 to the power 1000…

>>> print pow(2,1000)
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

No problem! Just need to add those up……

Anyway back to C#… how to cope? We need to make an array.. and handle it ourselves like this..:

static void Main(string[] args)
       {
           int[] c = new int[999];

           c[0] = 2; //starting condition

           for (int i = 1; i < 1000; i++)   //go to the power of 1000
           {
               //do mult in place
                for (int n=0;n<999;n++)
               {
                   c[n] *= 2;
               }
              
            
               //sort out carries across to right
               for (int n=0;n<999;n++)
               {
                 
                   if (c[n] >= 10)
                   {
                       c[n+1] += 1;
                       c[n] -= 10;
                   }
                   }

           }

           //now add up all the columns
           long sum = 0;

           for (int n = 0; n < 999; n++)
           {
              sum+= c[n];
           }


           Console.WriteLine(sum);

        
       Console.ReadLine();

       }

No comments: