又到周五,假期完全没有星期几的概念。。。
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 141837 Accepted Submission(s): 34462
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 1 3 1 2 10 0 0 0
2 5
总结:
起初读题,以为会用递归做(开始方了,因为递归学的不好T_T)但是从n的范围看来,很明显,这题不能直接按公式用递归来求,因为n最大可以达到100,000,000,会栈溢出。所以要找规律:取模就是周期性最好的标志。即当前两个等于1,所以后面如果有两个连着的1出现,那就是出现周期了。表示成代码为: if(f[i]==1&&f[i-1]==1),从而i-2就是这个函数的周期啦~这个题比较简单,但是很有代表性哦~尤其是取模与周期性(可以直接看出周期T)关系。
代码如下:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int a,b,n,f[11000];
f[1]=1;
f[2]=1;
while(scanf("%d%d%d",&a,&b,&n)!=EOF)
{
int i;
if(a==0&&b==0&&n==0)
break;
for(i=3;i<11000;i++)
{
f[i]=(a*f[i-1]+b*f[i-2])%7;
if(f[i]==1&&f[i-1]==1)
break;
}
f[0]=f[i-2];
printf("%d\n",f[n%(i-2)]);
}
return 0;
}