Hdu 1005, hdu
Problem DescriptionA number sequence is defined as follows:
F (1) = 1, f (2) = 1, f (n) = (A * f (n-1) + B * f (n-2 )) mod 7.
Given A, B, and n, you are to calculate the value of f (n ).
InputThe input consists of multiple test cases. each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000 ). three zeros signal the end of input and this test case is not to be processed.
OutputFor each test case, print the value of f (n) on a single line.
Sample Input1 1 31 2 100 0 0
Sample Output25 cannot be computed using Recursive Formulas because n is relatively large (although I only know it when I see other blogs) for the formula f [n] = A * f [n-1] + B * f [N-2]; the latter is only 7*7 = 49, why so, because the values of f [n-1] or f [N-2] are only 0, 1, 2, 3, 4, 5, 6, and A and B are fixed, so there are only 49 possible values. The relationship between each item and the first two items is known, so when the two consecutive items appear in the previous cycle section, note that the cycle section does not necessarily start. In addition, in a group of test data, f [n] has only 49 possible answers. The worst case is that all the situations are met, then, a circular section is generated in 50 operations. After finding the cycle, you can easily solve the problem. (Posted) the code is as follows (but I submitted N times, as long as I "= 10000", a running error occurs) ......
#include <stdio.h>#include <math.h>int f[10000];int main(){ int a,b,n,i; f[1]=1; f[2]=1; while(scanf("%d%d%d",&a,&b,&n),a|b|n) { for(i=3; i<10000; i++) { f[i]=(a*f[i-1]+b*f[i-2])%7; if(f[i]==1&&f[i-1]==1) { break; } } n=n%(i-2); f[0]=f[i-2]; printf("%d\n",f[n]); } return 0;}