Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1005
A 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 ).
1 <= A, B <= 1000, 1 <= n <= 100,000,000
Solution:
F (n) = (A * F (n-1) + B * F (n-2) % 7
= (A * F (n-1) % 7 + B * F (n-2) % 7) % 7
Therefore, for a given a and B, You can first create a table to find out the cyclic part of the series. The Pigeon nest principle knows that the total number of States will not exceed 7*7.
Note that the loop section does not necessarily start with F (3...
# Include <iostream> <br/> using namespace STD; <br/> int A, B, n, x, y, L, H, M [7] [7], Q [300]; <br/> int main () <br/>{< br/> while (scanf ("% d", &, & B, & N )! = EOF & (A | B | N) <br/>{< br/> memset (M, 0, sizeof (m )); <br/> q [1] = Q [2] = 1; <br/> X = y = 1; L = 3; <br/> while (M [x] [Y] = 0) <br/> {// This status has not been experienced yet, then expand <br/> q [l] = (A * x + B * Y) % 7; <br/> M [x] [Y] = L; <br/> Y = x; <br/> X = Q [L ++]; <br/>}< br/> // at this time, Q [1... h-1] is the front non-cyclic part <br/> // Q [h... l-1] is the cyclic section </P> <p> H = m [x] [Y]; // the starting position of the cyclic section <br/> If (n <p) <br/>{< br/> printf ("% d/N", Q [N]); <br/>}< br/> else <br/> {<br/> printf ("% d/N", Q [(n-h) % (L-h) + H]); <br/>}< br/> return 0; <br/>}