Spoiler Alert: As the About page of Project Euler says, "Real learning is an active process and seeing how it is done is a long way from experiencing that epiphany of discovery." If you are currently attempting to solve this problem in the archives, please do not continue to read this post. I personally worked through all the problems I post on this blog and it has brought me immense satisfaction.
Problem:
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 index of the first term in the Fibonacci sequence to contain 1000 digits?
Solution:
Using the BigInteger class, this problem can be solved very simply using C#:
I've avoided putting the answer in the solution, just in case someone solving the problem on Project Euler ignored the Spoiler Alert. But this method will provide the correct answer.
Problem:
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 index of the first term in the Fibonacci sequence to contain 1000 digits?
Solution:
Using the BigInteger class, this problem can be solved very simply using C#:
//Time the process
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//First Fibonacci number
BigInteger n1 = 1;
//Second Fibonacci number
BigInteger n2 = 1;
//Variable to hold next Fibonacci
BigInteger sum;
//i represents which term we are on
int i = 2;
do
{
sum = n2 + n1;
n1 = n2; n2 = sum;
i++;
} while (BigInteger.Log10(sum)<999);
stopwatch.Stop();
Console.WriteLine($"First Fib with 1000 digits: {i}");
Console.WriteLine($"Time to calculate (ms): {stopwatch.Elapsed.TotalMilliseconds}");
Console.ReadKey();
Notice the "while (BigInteger.Log10(sum)<999)" line. When I first solved this problem, my first reaction was to convert each sum to a string and then count the number of characters in the string (while (sum.ToString().Length<1000)) This is a bad idea. While using the log base 10 method only takes about 60 milliseconds on my machine, using the string method takes more than 350. Converting numbers to strings is an expensive operation. At least in this case, it is 6x more expensive to convert to a string and count the characters vs. getting the log base 10.I've avoided putting the answer in the solution, just in case someone solving the problem on Project Euler ignored the Spoiler Alert. But this method will provide the correct answer.
Comments
Post a Comment