Monday, November 1, 2010

Problem: Euler Task 25: What is the first term in the Fibonacci sequence to contain 1000 digits ?

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


Well, it should be only a variation of problem number 2. We need to modify the fibonacci function a little bit to stop when the number exceeds a value, for example 1099.


The function becomes: 

1 def fibiter(max: BigInt) : BigInt = {
2   def fibiter(x: BigInt, acc: BigInt, index: Int) : BigInt = {
3       if (x > max)
4           index
5       else fibiter(x + acc,x, index + 1)
6    }
7    fibiter(1, 1, 2)
8 }

The line 3 checks if the last fibonacci number exceeds the maximum number. If it is, then its index is returned. Otherwise, the next fibonacci number is generated (x + acc) and the index is incremented.

The call starts with (1, 1, 2) to tell that the first two fibonacci numbers are already created. The solution to the problem is fibiter( (10: BigInt).pow 99)

No comments: