码迷,mamicode.com
首页 > 其他好文 > 详细

Number Sequence(快速幂矩阵)

时间:2015-09-28 08:46:25      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1005

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 131753    Accepted Submission(s): 31988


Problem Description
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).
 

 

Input
The 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.
 

 

Output
For each test case, print the value of f(n) on a single line.
 

 

Sample Input
1 1 3 1 2 10 0 0 0
 

 

Sample Output
2 5
 

 

Author
CHEN, Shunbao
 

 

Source
 
题意:简单的快速幂矩阵,加一个f(n-1) = f(n-1)即可
代码:
 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 using namespace std;
 7 struct Mtr{
 8     int a , b , c , d ;
 9     Mtr operator * (const Mtr m) const
10     {
11         Mtr res ;
12         res.a = (a*m.a%7 + b*m.c%7)%7;
13         res.b = (a*m.b%7+b*m.d%7)%7;
14         res.c = (c*m.a%7+d*m.c%7)%7;
15         res.d = (c*m.b%7+d*m.d%7)%7;
16         return res;
17     }
18 };
19 int cal(Mtr a , int n)
20 {
21     Mtr c;
22     c.a = c.d = 1;
23     c.b = c.c = 0;
24     while(n>0)
25     {
26         if(n&1)
27             c = c*a;
28         a = (a*a);
29         n/=2;
30     }
31     return (c.a+c.b)%7;
32 }
33 int main()
34 {
35     int a , b , n;
36     while(~scanf("%d%d%d",&a,&b,&n)&&(a!=0||b!=0||n!=0))
37     {
38         Mtr tm;
39         tm.a = a;
40         tm.b = b;
41         tm.c = 1;
42         tm.d = 0;
43         int tt = cal(tm,n-2);
44         printf("%d\n",tt);
45     }
46     return 0;
47 }

 

 

Number Sequence(快速幂矩阵)

标签:

原文地址:http://www.cnblogs.com/shanyr/p/4843212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!