版权声明:欢迎评论与转载,转载时请注明出处! https://blog.csdn.net/wjl_zyl_1314/article/details/84927750
原题链接:
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
题意:
根据数列递推公式,求出f(n)。
题解:
这道题目重点是在mod7上,这样的话很容易就构成循环,所以只需要计算他的循环周期T,以及T之内的所有结果即可,只不过这道题目好像有多余限制(T<50),题目题目没有明确说明,知道这一点就很简单了。
附上AC代码:
#include <iostream>
#include <cstdio>
using namespace std;
#define LL long long
const int mod=7;
const int N=50;
int a,b,n;
int res[50];
int main()
{
while(scanf("%d %d %d",&a,&b,&n),a||b||n)
{
int i;
res[1]=res[2]=1;
for(i=3;i<50;i++)//寻找循环周期T
{
res[i]=(a*res[i-1]+b*res[i-2])%mod;
if(res[i]==1&&res[i-1]==1)//判断是否开始新的循环
{
break;
}
}
int T=i-2;
if(n%T)
printf("%d\n",res[n%T]);
else
printf("%d\n",res[T]);
}
return 0;
}
欢迎评论!