首页 > 其他 > 详细

HDU 1005 Number Sequence 数学

时间:2016-02-02 18:57:09      阅读:131      评论:0      收藏:0      [点我收藏+]
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

 题目就是给你一条递推式,让你求第n项的大小。

假如直接模拟,会超时,因为它可以给你求很后面的数据,所以不能直接模拟。

所以就考虑有没有循环,看到题目的递推式里对于7取模,只有两个变量共有7*7=49种可能,所以可以对所有的可能进行枚举,然后对求的数对49取模就可以过了。

代码如下:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<cstring>
 5 using namespace std;
 6 int main(){
 7     int a,b,n;
 8     int ans[200];
 9     scanf("%d %d %d",&a,&b,&n);
10     while(n!=0)
11     {
12         ans[1]=1;
13         ans[2]=1;
14         int i=3;
15         for ( ;i<=100;++i)
16         {
17             ans[i]=(ans[i-1]*a+ans[i-2]*b)%7;
18         }
19         n=n%49;
20         printf("%d\n",ans[n]);
21         scanf("%d %d %d",&a,&b,&n);
22     }
23     
24     return 0;
25 }

 

HDU 1005 Number Sequence 数学

原文:http://www.cnblogs.com/fakerv587/p/5178272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!