Friday 10 April 2009

PROJECT EULER #16

Link to page

2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^(1000)?



using System;
using System.Collections.Generic;

namespace ProjectEuler
{
class Program
{
static void Main(string[] args)
{
//Problem 16
DateTime start = DateTime.Now;
//This is about doubling 2, 999 times
//This number is too big for the system types in C#
int carry=0, sum=0;
List<int> a = new List<int>(){2};
List<int> b = new List<int>();
for (int i = 2; i <= 1000;i++ )
{
foreach (int j in a)
{
int c = j*2 + carry;

if (c > 9)
{
c = c - 10;
carry = 1;
}
else
{
carry = 0;
}
b.Add(c);
}
if (b.Count == a.Count && carry == 1)
b.Add(1);
carry = 0;
a.Clear();
foreach (int j in b)
{
a.Add(j);
}
b.Clear();
}
foreach(int j in a)
{
sum += j;
}
TimeSpan time = DateTime.Now-start;
Console.WriteLine("{0}\nThis took {1}", sum, time);
Console.ReadKey();
}
}
}

No comments: