杭电1005题ACM求解答
http://acm.hdu.edu.cn/showproblem.php?pid=1005ProblemDescriptionAnumbersequenceisdefi...
http://acm.hdu.edu.cn/showproblem.php?pid=1005
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
答案里都说49一个循环,但是我觉得需要找循环开始点
所以打了一个代码运行测试数据也对但是一直WA
求解=-=
#include<stdio.h>
int main()
{
int a,b,n,i,f[2000],t,j,k,m;
while(scanf("%d%d%d",&a,&b,&n)&&(a!=0||b!=0||n!=0))
{
f[1]=1;f[2]=1;
t=0;
for(i=3;i<=102;i++)
f[i]=(a*f[i-1]%7+b*f[i-2]%7)%7;
for(i=1;i<=102;i++)
{
if(t==1)
{break;}
for(j=i+1;j<=100;j++)
if(f[i]==f[j]&&f[i+1]==f[j+1])
{k=2*(j-i);
m=i-1;
t=1;
break;}
}
if(n<=m)
printf("%d\n",f[n]);
else
{
n=(n-m)%k;
printf("%d\n",f[m+n]);
}
}
return 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
答案里都说49一个循环,但是我觉得需要找循环开始点
所以打了一个代码运行测试数据也对但是一直WA
求解=-=
#include<stdio.h>
int main()
{
int a,b,n,i,f[2000],t,j,k,m;
while(scanf("%d%d%d",&a,&b,&n)&&(a!=0||b!=0||n!=0))
{
f[1]=1;f[2]=1;
t=0;
for(i=3;i<=102;i++)
f[i]=(a*f[i-1]%7+b*f[i-2]%7)%7;
for(i=1;i<=102;i++)
{
if(t==1)
{break;}
for(j=i+1;j<=100;j++)
if(f[i]==f[j]&&f[i+1]==f[j+1])
{k=2*(j-i);
m=i-1;
t=1;
break;}
}
if(n<=m)
printf("%d\n",f[n]);
else
{
n=(n-m)%k;
printf("%d\n",f[m+n]);
}
}
return 0;
} 展开
1个回答
2014-02-21
展开全部
这个是我的,参考一下吧,很久以前写的代码
#include<stdio.h>
int main()
{
int a[50]={0,0,0,0};
int n,A,B,i;
a[1]=1;a[2]=1;
while(scanf("%d%d%d",&A,&B,&n))
{
if(n==0&&A==0&&B==0)break;
n=n%49;
for(i=3;i<49;i++)
a[i]=(A*a[i-1]+B*a[i-2])%7;
a[0]=(A*a[48]+B*a[47])%7;
printf("%d\n",a[n]);
}
return 1;
}
这是很典型的递归,记得当时我们老师讲过这个题呢。
#include<stdio.h>
int main()
{
int a[50]={0,0,0,0};
int n,A,B,i;
a[1]=1;a[2]=1;
while(scanf("%d%d%d",&A,&B,&n))
{
if(n==0&&A==0&&B==0)break;
n=n%49;
for(i=3;i<49;i++)
a[i]=(A*a[i-1]+B*a[i-2])%7;
a[0]=(A*a[48]+B*a[47])%7;
printf("%d\n",a[n]);
}
return 1;
}
这是很典型的递归,记得当时我们老师讲过这个题呢。
追问
谢谢,不过我是想知道为什么一定是从刚开始就循环,没有可能先输出几个数然后再开始循环节吗
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询