For calculating arbitrarily large elements of the Fibonacci sequence, you're going to have to use the closed-form solution -- Binet's formula, and use arbitrary-precision math to provide enough precision to calculate the answer.
Just using the recurrence relation, though, should not require 2-3 minutes to calculate the 50th term -- you should be able to calculate terms out into the billions within a few seconds on any modern machine. It sounds like you're using the fully-recursive formula, which does lead to a combinatorial explosion of recursive calculations. The simple iterative formula is much faster.
To wit: the recursive solution is:
int fib(int n) {
if (n < 2)
return 1;
return fib(n-1) + fib(n-2)
}
... and sit back and watch the stack overflow.
The iterative solution is:
int fib(int n) {
if (n < 2)
return 1;
int n_1 = 1, n_2 = 1;
for (int i = 2; i <= n; i += 1) {
int n_new = n_1 + n_2;
n_1 = n_2;
n_2 = n_new;
}
return n_2;
}
Notice how we're essentially calculating the next term n_new from previous terms n_1 and n_2, then "shuffling" all the terms down for the next iteration. With a running time linear on the value of n, it's a matter of a few seconds for n in the billions (well after integer overflow for your intermediate variables) on a modern gigahertz machine.
For calculating the Fibonacci numbers, the recursive algorithm is one of the worst way.
By simply adding the two previous numbers in a for cycle (called iterative method) will not take 2-3 minutes, to calculate the 50th element.
You can use the matrix exponentiation method (linear recurrence method).
You can find detailed explanation and procedure in this or this blog. Run time is O(log n).
I don't think there is a better way of doing this.
Use recurrence identities http://en.wikipedia.org/wiki/Fibonacci_number#Other_identities to find n-th number in log(n) steps. You will have to use arbitrary precision integers for that. Or you can calculate the precise answer modulo some factor by using modular arithmetic at each step.
Noticing that 3n+3 == 3(n+1), we can devise a single-recursive function which calculates two sequential Fibonacci numbers at each step dividing the n by 3 and choosing the appropriate formula according to the remainder value. IOW it calculates a pair @(3n+r,3n+r+1), r=0,1,2 from a pair @(n,n+1) in one step, so there's no double recursion and no memoization is necessary.
I have written a small code to compute Fibonacci for large number which is faster than conversational recursion way.
I am using memorizing technique to get last Fibonacci number instead of recomputing it.
public class FabSeries {
private static Map<BigInteger, BigInteger> memo = new TreeMap<>();
public static BigInteger fabMemorizingTech(BigInteger n) {
BigInteger ret;
if (memo.containsKey(n))
return memo.get(n);
else {
if (n.compareTo(BigInteger.valueOf(2)) <= 0)
ret = BigInteger.valueOf(1);
else
ret = fabMemorizingTech(n.subtract(BigInteger.valueOf(1))).add(
fabMemorizingTech(n.subtract(BigInteger.valueOf(2))));
memo.put(n, ret);
return ret;
}
}
public static BigInteger fabWithoutMemorizingTech(BigInteger n) {
BigInteger ret;
if (n.compareTo(BigInteger.valueOf(2)) <= 0)
ret = BigInteger.valueOf(1);
else
ret = fabWithoutMemorizingTech(n.subtract(BigInteger.valueOf(1))).add(
fabWithoutMemorizingTech(n.subtract(BigInteger.valueOf(2))));
return ret;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number");
BigInteger num = scanner.nextBigInteger();
// Try with memorizing technique
Long preTime = new Date().getTime();
System.out.println("Stats with memorizing technique ");
System.out.println("Fibonacci Value : " + fabMemorizingTech(num) + " ");
System.out.println("Time Taken : " + (new Date().getTime() - preTime));
System.out.println("Memory Map: " + memo);
// Try without memorizing technique.. This is not responsive for large
// value .. can 50 or so..
preTime = new Date().getTime();
System.out.println("Stats with memorizing technique ");
System.out.println("Fibonacci Value : " + fabWithoutMemorizingTech(num) + " ");
System.out.println("Time Taken : " + (new Date().getTime() - preTime));
}
}
If you are using C# have a look at Lync and BigInteger.
I tried this with 1000000 (actually 1000001 as I skip the first 1000000) and was below 2 minutes (00:01:19.5765).
public static IEnumerable<BigInteger> Fibonacci()
{
BigInteger i = 0;
BigInteger j = 1;
while (true)
{
BigInteger fib = i + j;
i = j;
j = fib;
yield return fib;
}
}
public static string BiggerFib()
{
BigInteger fib = Fibonacci().Skip(1000000).First();
return fib.ToString();
}
#include <bits/stdc++.h>
#define MOD 1000000007
using namespace std;
const long long int MAX = 10000000;
// Create an array for memoization
long long int f[MAX] = {0};
// Returns n'th fuibonacci number using table f[]
long long int fib(int n)
{
// Base cases
if (n == 0)
return 0;
if (n == 1 || n == 2)
return (f[n] = 1);
if (f[n])
return f[n];
long long int k = (n & 1)? (n+1)/2 : n/2;
f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) %MOD
: ((2*fib(k-1) + fib(k))*fib(k))%MOD;
return f[n];
}
int main()
{
long long int n = 1000000;
printf("%lld ", fib(n));
return 0;
}
Time complexity: O(Log n) as we divide the problem to half in every recursive call.
I have done a program.
It doesn't take long to calculate the values but the maximum term which can be displayed is the 1477th(because of the max range for double).
Results appear almost instantly.
The series starts from 0.
If there are any improvements needed,please feel free to edit it.
#include<iostream>
using namespace std;
void fibseries(long int n)
{
long double x=0;
double y=1;
for (long int i=1;i<=n;i++)
{
if(i%2==1)
{
if(i==n)
{
cout<<x<<" ";
}
x=x+y;
}
else
{
if(i==n)
{
cout<<x<<" ";
}
y=x+y;
}
}
}
main()
{
long int n=0;
cout<<"The number of terms ";
cin>>n;
fibseries(n);
return 0;
}
I agree with Wayne Rooney's answer that the optimal solution will complete in O(log n) steps, however the overall run-time complexity will depend upon the complexity of the multiplication algorithm used. Using Karatsuba Multiplication, for example, the overall run-time complexity would be O(nlog23) ≈ O(n1.585).1
However, matrix exponentiation isn't necessarily the best way to go about it. As a developer at Project Nayuki has noticed, matrix exponentiation carries with it redundant calculations, which can be removed. From the author's description:
Given Fk and Fk+1, we can calculate these:
Note that this requires only 3 BigInt-to-BigInt multiplications per split, rather than 8 as matrix exponentiation would.
We can still do slightly better than this, though. One of the most elegant Fibonacci identities is related to the Lucas Numbers:
where Ln is the nthLucas Number. This identity can be further generalized as:
There's a few more-or-less equivalent ways to proceed recursively, but the most logical seems to be on Fn and Ln. Further identities used in the implementation below can either be found or derived from the identities listed for Lucas Sequences:
Proceeding in this way requires only two BigInt-to-BigInt multiplications per split, and only one for the final result. This is about 20% faster than the code provided by Project Nayuki (test script). Note: the original source has been modified (improved) slightly to allow a fair comparison.
def fibonacci(n):
def fib_inner(n):
'''Returns F[n] and L[n]'''
if n == 0:
return 0, 2
u, v = fib_inner(n >> 1)
q = (n & 2) - 1
u, v = u * v, v * v + 2*q
if (n & 1):
u1 = (u + v) >> 1
return u1, 2*u + u1
return u, v
u, v = fib_inner(n >> 1)
if (n & 1):
q = (n & 2) - 1
u1 = (u + v) >> 1
return v * u1 + q
return u * v
Update
A greybeard points out, the above result has already been improved upon by Takahashi (2000)2, by noting that BigInt squaring is generally (and specifically for the Schönhage-Strassen algorithm) less computationally expensive than BigInt multiplication. The author suggestions an iteration, splitting on Fn and Ln, using the following identities:
Iterating in this way will require two BigInt squares per split, rather than a BigInt square and a BigInt multiplication as above. As expected, the run-time is measurably faster than the above implementation for very large n, but is somewhat slower for small values (n < 25000).
However, this can be improved upon slightly as well. The author claims that, "It is known that the Product of Lucas Numbers algorithm uses the fewest bit operations to compute the Fibonacci number Fn." The author then elects to adapt the Product of Lucas Numbers algorithm, which at the time was the fastest known, splitting on Fn and Ln. Note, however, that Ln is only ever used in the computation of Fn+1. This seems a somewhat wasteful, if one considers the following identities:
where the first is taken directly from Takahashi, the second is a result of the matrix exponentiation method (also noted by Nayuki), and the third is the result of adding the previous two. This allows an obvious split on Fn and Fn+1. The result requires one less BigInt addition, and, importantly, one less division by 2 for even n; for odd n the benefit is doubled. In practice this is signifcantly faster than the method proposed by Takahashi for small n (10-15% faster), and marginally faster for very large n (test script).
def fibonacci(n):
def fib_inner(n):
'''Returns F[n] and F[n+1]'''
if n == 0:
return 0, 1
u, v = fib_inner(n >> 1)
q = (n & 2) - 1
u *= u
v *= v
if (n & 1):
return u + v, 3*v - 2*(u - q)
return 2*(v + q) - 3*u, u + v
u, v = fib_inner(n >> 1)
# L[m]
l = 2*v - u
if (n & 1):
q = (n & 2) - 1
return v * l + q
return u * l
Update 2
Since originally posting, I've improved upon the previous result slightly as well. Aside from the two BigInt squares, splitting on Fn and Fn+1 also has an overhead of three BigInt additions and two small constant multiplications per split. This overhead can be eliminated almost entirely by splitting on Ln and Ln+1 instead:
Splitting in this way requires two BigInt squares as before, but only a single BigInt addition. These values need to be related back to the corresponding Fibonacci number, though. Fortunately, this can be achieved with a single division by 5:
Because the quotient is known to be integer, an exact division method such as GMP's mpz_divexact_ui can be used. Unrolling the outermost split allows us to then compute the final value with a single multiplication:
As implemented in Python, this is noticably faster than the previous implementation for small n (5-10% faster) and marginally faster for very large n (test script).
def fibonacci(n):
def fib_inner(n):
'''Returns L[n] and L[n+1]'''
if n == 0:
return mpz(2), mpz(1)
m = n >> 1
u, v = fib_inner(m)
q = (2, -2)[m & 1]
u = u * u - q
v = v * v + q
if (n & 1):
return v - u, v
return u, v - u
m = n >> 1
u, v = fib_inner(m)
# F[m]
f = (2*v - u) / 5
if (n & 1):
q = (n & 2) - 1
return v * f - q
return u * f
1 It can be seen that the number of digits (or bits) of Fn ~ O(n) as:
The runtime complexity using Karatsuba Multiplication can then be calculated as:
The test_seq() is not very smart, it didn't reuse the cache between 2 input number.
While actually a single call to fib_gmp() would be enough, if you add a gmp_printf() to fib_gmp_next() and provide the i to fib_gmp_next() in each step.
Anyhow, it's just for demo.
With some knowledge of discrete mathematics, you can find any Fibonacci number in constant time O(1). There is something called Linear Homogeneous Recurrence Relation.
Fibonacci sequence is an famous example.
To find the nth Fibonacci number we need to find that
We know that
where
Then, the Characteristic equation is
After finding the roots of the characteristic equation and substituting in the first equation
Finally, we need to find the value of both alpha 1 & alpha 2
Now, you can use this equation to find any Fibonacci number in O(1).
The following formula seems working fine but depends on the preciseness of the number used-
[((1+√5)/2)ⁿ- ((1-√5)/2)ⁿ]/√5
Note: Don't round-off the figures for more preciseness.
JS sample code:
let n = 74,
const sqrt5 = Math.sqrt(5);
fibNum = Math.round((Math.pow(((1+sqrt5)/2),n)- Math.pow(((1-sqrt5)/2),n))/sqrt5) ;
As per the Number Precision, it'll work fine on chrome console upto n=74
Open for any suggestion!
Another solution
Follows the steps-
make a set of index and value and pervious value of fibonacci series at certain intervals. e.g each 50 or each 100.
Find the nearest lower index of the desired number n from the set of step-1.
Proceed in traditional way by adding the previous value in each subsequent one.
Note: It doesn't seems good, but if you really concern about time complexity, this solution is a hit. The max iterations will be equal to the interval as per step-1.
Conclusion:
Fibonacci numbers are strongly related to the golden ratio: Binet's formula expresses the nth Fibonacci number in terms of n and the golden ratio, and implies that the ratio of two consecutive Fibonacci numbers tends to the golden ratio as n increases.
In pure mathematics Binet's formula will give you the exact result every time. In real world computing there will be errors as the precision needed exceeds the precision used. Every real solution has the same problem with exceeding precision at some point.