问题及代码:
运行结果:
知识点总结:
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:HDU.cpp
*作 者:单昕昕
*完成日期:2015年1月27日
*版 本 号:v1.0
*问题描述:Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 45 Accepted Submission(s) : 7
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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).
*程序输入: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.
*程序输出: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
*/
#include<iostream>
using namespace std;
int main()
{
int a,b,i;
long long n;
while(cin>>a>>b>>n,a||b||n)
{
int f[49];
f[1]=f[2]=1;
for(i=3; i<=49; ++i)
{
f[i]=(a*f[i-1]+b*f[i-2])%7;
if(f[i]==1&&f[i-1]==1)
break;
}
n=n%(i-2);
f[0]=f[i-2];
cout<<f[n]<<endl;
}
return 0;
}
运行结果:
知识点总结:
因为是对7取模运算,所以在7*7=49中必定有循环,而且f(1) = 1, f(2) = 1,所以当下一次出现两个相邻且同时为1的递推式时,上一个循环结束。
找到循环体,要标记循环节i-2。
学习心得:
循环节标记就用i-2就好,如果用flag的话,没处理好就会出现报错除数为0的情况。