Cyclic nature of MOD for HDU 1005

Source: Internet
Author: User

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/>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.