一道简单的编程题 但是通不过

来源:百度知道 编辑:UC知道 时间:2024/05/31 04:40:55
这是HDU上的第1005题

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) % 7.
Given A, B, and n, you are to calculate the value of f(n).

我用穷举得到f(n)的循环表
但是提交的时候老是wrong answer

C/C++ code
#include <iostream>
using namespace std;
int main()
{
int A,B;
long n;
int a[300] = {0};
a[1] = 1;
a[2] = 1;
while(cin>>A>>B>>n)
{
if(A + B + n == 0)
break;
if(n > 2)
{
int i = 3;
for(;i<300;i++)
{
a[i] = (A*a[i-1] +B*a[i-2])%7;
if(a[i] == 1)
if(a[i-1] == 1)
break;
}
i -= 2;
cout<<a[(n-1)% i + 1]<<endl;
}
else
cout<<"1"<<endl;
}
return 0;
}

请问高手 为什么会这样
还有下面的c代码跟我的算法一模一样 实现细节也一样 它却通过了

C/C++ code
#include<stdio.h>
int main()
{
int a,b,i;
long n,f[201];
while (scanf("%d %d %ld",&a

应该用递归比较好
int func(int A, int B, int n)
{
if(n == 2 || n == 1) return 1;
int temp = func(A, B, n-1);
int temp2 = func(A, B, n-2);
return (A*temp + B*temp2);
}

你的思路,就应该用楼上说的递归
如果不用递归,用数组,下面有段程序,你看一下

#include <iostream>

using namespace std;

int main()
{
int a,b;
long n;
cout<<"输入a,b,n:";
cin>>a>>b>>n;
int *arry = new int[n+1];
if(n<3)
{
cout<<"f(n)="<<1;
}
else if(n>=3)
{
arry[1]=arry[2]=1;
for(int i=3; i<=n; i++)
{
arry[i] = (a*arry[i-1] + b*arry[i-2]) % 7;
}

for(int j=1; j<=n; j++)
{
cout << "f(" << j << ")=" << arry[j] <<endl;
}
}

delete [] arry;

return 0;
}