0

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

http://ideone.com/iCPEyz

CODE 2

http://ideone.com/Un5p2S

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
g4ur4v
  • 3,210
  • 5
  • 32
  • 57
  • 2
    I can't help but notice the lack of a question mark. – Mr Lister Feb 03 '13 at 14:59
  • 1
    Your "knowledge" is only correct (in C and C++) for unsigned integral types. For signed integrals this is undefined behavior. – Matthieu M. Feb 03 '13 at 14:59
  • Not a direct answer to your question, but to tackle the *Fimodacci* problem you might want to not wait until the end to do the modulo thing. Many such problems are amenable to this approach. See http://www.mathblog.dk/uva-10229-modular-fibonacci/ – LSerni Feb 03 '13 at 15:16

1 Answers1

0

"Overflow" (you don't really call it that for unsigneds, they wrap around) of unsigned n-bit types will preserve values modulo 2^n only, not modulo an arbitrary modulus (how could they? Try to reproduce the steps with pen and paper). You therefore have to make sure that no operation ever goes over the limits of your type in order to maintain correct results mod 100000007.

us2012
  • 16,083
  • 3
  • 46
  • 62