helios wrote: |
---|
Am I wrong, or did you do the opposite of what the problem asks for? The problem asks for GCD(fib(n), fib(m)) % 10^8, but it looks like you're calculating fib(GCD(n, m)) % 10^8. I don't think those are equivalent. |
No, I'm doing {GCD(fib(n), fib(m)) } % 10^8. The modulo 10
8 is only done to one of the two possible exit points.
The reduction is done by
INT hFib( INT n, INT m )
That is completely independent of M=10
8. It has nothing directly to do with the HCF algorithm (which uses n%m, not n-m; look carefully).
hFib(n,m) is the function hcf( F(n), F(m) ), where F(n) is the nth Fibonacci number (with F(1)=F(2)=1).
There are only two exit points from the recursion in hFib():
m =1 (whence F(1)=1, so that's the highest common factor)
OR
n=m, in which case hcf(F(n),F(n))=F(n), so you are stuck with finding a large Fibonacci number, mod M. That is done by a different function
int FibMod()
.
FWIW:
I see
two main steps:
(1) Proving that hcf( F(n),F(m) ) = hcf( F(n-m),F(m) ), where m<n, without any modulo. This reduces the problem.
(2) Finding the value of a Fibonnaci number for very large n and then writing it modulo M.
Item (1) took me hours to prove myself, but I subsequently discovered it online in a different context.
Item (2) is fairly standard (i.e. I googled it). It turns out that Fibonacci numbers mod M have a period - the Pisano Period. I obtained that with a separate program by brute force. Luckily, here it is (relatively) small - it could have been anything between 3 and M
2, i.e. 10
16. The latter would have crippled the method.
Well, that's my take on it. Somebody will have to get an account on the e-Olympiad site and try it out, I suppose. You'll need to change the output format if you want to put it in a competitive programming site.
The last three cases:
"6 9 \n"
"6 12 \n"
"6 15 \n" |
should allow you (by writing out the first 15 Fibonacci numbers) to check the statement
hcf( F(n), F(m) ) = hcf( F(m), F(n-m) ) |
by hand. Dealing with the modulo is a different (and somewhat easier) problem.
As an example,
hcf(F(6),F(15)) = hcf(F(6),F(9)) = hcf(F(6),F(3)) = hcf(F(3),F(3)) = F(3) = 2 |
Check: F(6) = 8 and F(15) = 610; the highest common factor is 2.
Feel free to come up with a better alternative.