I am learning this algorithm to calculate nth number in fibonacci series. This is my code,
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
long long int fib(long long int n)
{
if(n < 2)
return n;
if(n == 2)
return 1;
long long int k = n/2;
long long int a = fib(k+1);
long long int b = fib(k);
if(n%2 == 1)
return (((a*a)%MOD) + ((b*b)%MOD))%MOD;
else
return (b*((2*a - b)%MOD))%MOD;
}
int main()
{
//fibonacci series : 0,1,1,2,3,5,8,13..
long long int n;
scanf("%lld",&n);
printf("%lld\n", fib(n));
return 0;
}
It is working fine for smaller no.s but for larger n
values, its printing -ve no.s as output.
n = 10000000
fib(n) = -509810513
I don't understand where the value is going into -ve no.s as I think I applied %
operator properly for not having any data type overflow. Anyone please help me in finding the mistake.