Project Euler 25 Solution

Project Euler Problem 25 & HackerRank Version Solution

N-digit Fibonacci number

by {BetaProjects} | APRIL 10, 2009 | Project Euler & HackerRank

Project Euler Problem 25 Statement

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: {1,1,2,3,5,8,13,21,34,55,89,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?

Solution

Girl at beach swinging water from her hair

Solving this problem simply comes down to knowing Binet’s formula for finding the nth Fibonacci term and using logs to determine its magnitude. This formula takes advantage of Fibonacci terms converging to φFn = Fn+1, where φ (Phi) is the Golden Ratio Formula for the Golden Ratio.

The nth Fibonacci number is the closest integer to Formula for the nth Fibonacci number so we can define an inequality that we will use to solve for n—the first Fibonacci term that contain d>1 digits. In the case of d = 1000 digits it would be 10999 or 1 followed by 999 zeros:

Solving Binet’s formula for n

Now, we want to solve for n to find the first term in the Fibonacci sequence with d digits.

Solving Binet’s formula for n

Let’s use our new equation for d = 3 as shown in the problem statement. We calculated sqrt(5)/2 and log of phi as 0.349845 and 0.208988, respectively. The ceiling function maps a number to the least integer greater than or equal to that integer.

(0.349845 + 3 − 1) = 2.349485, and 2.349485 ÷ 0.208988 = 11.2422, and the ceil (11.2422) = 12✓.

HackerRank version

HackerRank Project Euler 25 requires us to run up to 5,000 test cases and find the first term in the Fibonacci sequence to contains d digits where, 2 ≤ d ≤ 5000.

Python Source Code

  1. from math import log10, ceil, sqrt
  2. phi = (1+sqrt(5))/2 # phi is the golden ratio, 1.61803398875
  3. d = int(input("Digits in Fibonacci number? "))
  4. term = ceil((log10(5)/2 + d-1) / log10(phi))
  5. print ("First Fibonacci term to contain %d digits is F(%d)." % (d, int(term)))

Last Word

Fun Fact: Did you know that you can use the Fibonacci sequence to convert between miles and kilometers? Just find the miles in the sequence and take the next value in the sequence for an approximate measure in kilometers. For example, 89 miles is approximately 144 kilometers.

This works as an approximation because there are 1.609 kilometers in a mile, which is very close to the golden ratio (1.618)—the ratio between two Fibonacci numbers.