I am trying to calculate number of ways of composition of a number using numbers 1 and 2.
This can be found using fibonacci series where F(1)=1
and F(2)=2
and
F(n)=F(n-1)+F(n-2)
Since F(n) can be very large I just need F(n)%1000000007
.To speed up the process I am using fibonacci exponentiation .I have written two codes for the same problem(both are almost similar).But one of them fails for large numbers.I am not able to figure out which one is correct ?
CODE 1
CODE 2
Though I have a feeling first one should be correct.I am not able to figure what would happen when there is a case like when we are multiplying say a
and b
and value of a
has already exceeded the upper limit of a
and when we multiply this by b
,then how sure can I be that a*b
is correct. As per my knowledge if a
value is above its data type limits then the value starts again from the lowest value like in below example.
#include<iostream>
#include<limits.h>
using namespace std;
int main()
{
cout<<UINT_MAX<<endl;
cout<<UINT_MAX+2;
}
Output
4294967295
1