Fast Doubling method to find nth Fibonacci number

One among very common questions asked in maths category in competitive programming is Fibonacci Series.

For a question that asks to find nth term of Fibonacci series, a naive approach to solve is an iterative method like

#define MOD 1000000007
long long int fib(long long int n)
{
    if(n < 2)
        return n;
    long long int a = 0,b = 1,ans;
    int i = 1;
    while(i < n)
    {
        ans = (a+b) % MOD;
        a = b;
        b = ans;
        i++;
    }
    return ans;
}

Above function has an O(n) complexity. With all our patience we may use it to calculate for at most n = 10^9 which gives output in around 10-15 seconds.

But as n gets larger, it takes hours,days,months,years,decades and so on for increasing n.

So the question is can we optimise it? Do we have methods to find nth Fibonacci number in less than a second?

Yes. We have few methods to do this. Out of them matrix exponentiation is most commonly used concept. Another well known concept is fast doubling method, which we are going to learn now.

Fast doubling is based on two formulae

F(2n) = F(n)[2*F(n+1) – F(n)]
F(2n + 1) = F(n)2 + F(n+1)2

Let us consider n starts from 0 and F(0) = 0. So our Fibonacci series would be F(0) = 0, F(1) = 1, F(2) = 1, F(3) = 2, F(4) = 3, F(5) = 5, F(6) = 8 …

For calculating terms, F(2n) & F(2n + 1), lets have a record of F(n) & F(n+1). By following this statement and taking care of equations and data type overflow, code would be as follows,

#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007;
long long int a,b,c,d;

void fast_fib(long long int n,long long int ans[])
{
    if(n == 0)
    {
        ans[0] = 0;
        ans[1] = 1;
        return;
    }
    fast_fib((n/2),ans);
    a = ans[0];             /* F(n) */
    b = ans[1];             /* F(n+1) */
    c = 2*b - a;
    if(c < 0)
        c += MOD;
    c = (a * c) % MOD;      /* F(2n) */
    d = (a*a + b*b) % MOD;  /* F(2n + 1) */
    if(n%2 == 0)
    {
        ans[0] = c;
        ans[1] = d;
    }
    else
    {
        ans[0] = d;
        ans[1] = c+d;
    }
}

int main()
{
    long long int n;        /* nth value to be found */
    scanf("%lld",&n);
    long long int ans[2]={0};
    fast_fib(n,ans);
    printf("%lld\n",ans[0]);
    return 0;
}

This code has a complexity of O(log n) which is way too faster than previously discussed function.

Advertisements

Travelling in a Maze

We might have come across problems asking number of possible paths to reach destination from source point. Lets see one such problem that can be solved with simple DP.

Question is, given a maze of dimensions MxN, and few obstructions, find number of paths that are possible starting at (1,1) and ends at (M,N). Also given that we can travel only to right or down from current position. ((1,1) will on top-left and (M,N) will be on bottom-right).

Lets once trace out for a maze with no obstructions. How many different paths are possible? There might be a mathematical formula for this. But let us solve it using DP. We will caluclate possible ways to reach each position starting from (1,1) and moving away from it towards (M,N).

Recursion formula would be,

f(X,Y) = 0 if either X = 0 or Y = 0
1 if X = 1 and Y = 1
f(X-1,Y)+f(X,Y-1) for rest of X,Y

For either X =0 or Y= 0, we never reach to those points, so number of paths leading to those points is 0.
For (X,Y) = (1,1), f(X,Y) = 1 because that is the source node. Only one possible way to reach there.
For rest of X and Y, reaching to that position is possible only from (X-1,Y) or (X,Y-1) as we can move only to right or down.

So tracing for X=4,Y=4, maze will become,

0 0 0 0 0
0 1 1 1 1
0 1 2 3 4
0 1 3 6 10
0 1 4 10 20

So to reach (4,4) from (1,1), there are 20 paths possible.

Now for any given obstructions, mark them 0 in the DP matrix and then apply above recursive formula for rest of the positions.

Code solving above question would be,

#include <iostream>;
#include <cstdio>;

using namespace std;

void travel_in_maze(int a[][100],int m,int n)
{
    int i,j;
    for(i = 0;i <= m;i++)
    {
        for(j = 0;j <= n;j++)
        {
            if(i == 0 || j == 0)
                a[i][j] = 0;
            else if(i == 1 && j == 1)
                a[i][j] = 1;
            else if(a[i][j] != 0)
                a[i][j] = a[i-1][j] + a[i][j-1];
        }
    }
}

int main()
{
    int m,n;
    int maze[100][100];
    int i,j;
    for(i = 0;i < 100;i++)
    {
        for(j = 0;j < 100;j++)
        {
            maze[i][j] = -1;
        }
    }
    scanf("%d %d",&m,&n);
    int obs; /* number of obstructions */
    int x,y;
    scanf("%d",&obs);
    for(i = 0;i < obs; i++)
    {
        scanf("%d %d",&x,&y);
        maze[x][y] = 0;
    }
    travel_in_maze(maze,m,n);
    printf("Number of paths = %d\n",maze[m][n]);
return 0;
}
Tracing for following case,
M = 5, N = 5
obs = 3
obstruction points = (1,3)
(5,1)
(3,2)

0 0 0 0 0 0
0 1 1 0 0 0
0 1 2 2 2 2
0 1 0 2 4 6
0 1 1 3 7 13
0 0 1 4 11 24

Number of paths = 24.

Lazy Caterer’s Sequence

That’s an interesting name! Has an interesting concept too. Lets say you have a large cake. In N cuts, what is the maximum number of pieces you could cut this cake into, given that cuts always follow straight line? Do you have any answer for it? Well if no, maximum number of pieces follows Lazy Caterer’s Sequence.

Starting with N = 0, as N increases sequence is
1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121, 137, …

Now it would be great if you could find any relation in this sequence. Did you? Well let me reveal it to you. Observe that f(n) = (n*(n+1))/2 + 1.

That made the sequence a lot simpler right? But how did this sequence come up? Lets derive it..

For any cut that you could make, you can achieve maximum number of pieces if you pass through all previous cuts. Lets say for nth cut, it should pass through all n-1 previously made cuts and at the same time not along any intersections. Thus the line itself divides into n segments each dividing their respective piece of cake into two parts. Hence for nth cut, you get n new pieces of cake. (If you are passing through an intersection of two cuts, you are loosing a piece of cake for that cut. And later on, a lot more.)

Maximum number of pieces for n cuts thus forms a recurrence relation,
f(n) = n + f(n-1).

Expanding the relation,

f(n) = n + (n-1) + f(n-2)
f(n) = n + (n-1) + (n-2) + f(n-3)
.
..
.
f(n) = n + (n-1) + (n-2) + ... 1 + f(0)

f(0) = 1 as there is one piece of cake when no cuts are made.

Therefore, f(n) = Sum of first n natural numbers + 1

Thus relation is f(n) = (n*(n+1))/2 + 1.

Lazy_Caterer's_Sequence_(Cuts)

Problem related to this concept: Joyfest and Joyful Cake