Problem 25

Statement
The Fibonacci sequence is defined by the recurrence relation:

F(n) = F(n−1) + F(n−2), where F(1) = 1 and F(2) = 1.

Hence the first 12 terms will be:

F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
F(11) = 89
F(12) = 144

The 12th term, F(12), is the first term to contain three digits.

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

Solution
The code, in C.

#include <stdio.h>

#define DIGIT 1000

int fibDigits()
{
  int i,j,tmp,a[DIGIT]={1},b[DIGIT]={1};
  for(i=3;!a[DIGIT-1];i++){
    for(j=0;j<DIGIT;j++){
      tmp=a[j];
      a[j]+=b[j];
      if(j){
	a[j]+=a[j-1]/10;
	a[j-1]%=10;
      }
      b[j]=tmp;
    }
  }
  return i-1;
}

int main(void)
{
  printf("%d\n",fibDigits(DIGIT));
  return 0;
}

Answer
4782

No tags for this post.

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>