Saturday 11 April 2009

PROJECT EULER #25

Link to Project Euler problem 25

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.

Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?


using System;
using System.Collections.Generic;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 25
DateTime start = DateTime.Now;
//again we use base 100000, saving the
//chunks of the big number in a List<int>
int digits = 0,carry=0,fibNo =2;
var a = new List<int>{1};
var b = new List<int>{1};
var c = new List<int>();
while (digits<1000)
{
fibNo+=1;
//add the chunks carrying over to the next chunk
for (int i = 0; i < b.Count; i++)
{
int temp = a[i] + b[i] + carry;
int number;
carry =(Math.DivRem(temp, 100000, out number));
c.Add(number);
}
//if a has more chunks than b....
if(a.Count>b.Count)
{
c.Add(a[a.Count-1] + carry);
carry = 0;
}
//if the sum of a and b makes a new chunk...
if (carry > 0)
{
c.Add(carry);
}
//swap the numbers around
b.Clear();
foreach (int i in a)
{
b.Add(i);
}
a.Clear();
foreach (int i in c)
{
a.Add(i);
}
c.Clear();
//calculate how many digits, check the last chunk (MSB)
//for less than 5 digits
digits = a.Count*5;
char[] ch = a[a.Count-1].ToString().ToCharArray();
digits -= 5-ch.Length;
}
Console.WriteLine(fibNo + " has " + digits + " digits.");
TimeSpan time = DateTime.Now-start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: