c语言问题,求高手指点,
题目是Anumbersequenceisdefinedasfollows:f(1)=1,f(2)=1,f(n)=(A*f(n-1)+B*f(n-2))mod7.Given...
题目是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
输出Output
For each test case, print the value of f(n) on a single line
我的程序:
#include<stdio.h>
int a,b;
int main(){
int f(int n);
int n,x;
scanf("%d%d%d",&a,&b,&n);
while(a!=0||b!=0||n!=0){
x=f(n);
printf("%d\n",x);
scanf("%d%d%d",&a,&b,&n);
}
return 0;
}
int f(int n){
int x;
if(n==1||n==2){
if(n==1)
x=1;
else
x=1;
}
else
x=(a*f(n-1)+b*f(n-2))%7;
return(x);
}
最后检测总出Runtime Error
(STACK_OVERFLOW)
求高人指教 展开
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
输出Output
For each test case, print the value of f(n) on a single line
我的程序:
#include<stdio.h>
int a,b;
int main(){
int f(int n);
int n,x;
scanf("%d%d%d",&a,&b,&n);
while(a!=0||b!=0||n!=0){
x=f(n);
printf("%d\n",x);
scanf("%d%d%d",&a,&b,&n);
}
return 0;
}
int f(int n){
int x;
if(n==1||n==2){
if(n==1)
x=1;
else
x=1;
}
else
x=(a*f(n-1)+b*f(n-2))%7;
return(x);
}
最后检测总出Runtime Error
(STACK_OVERFLOW)
求高人指教 展开
展开全部
程序没有问题,但是数字太大后多次递归造成运行栈溢出,其实你不用递归,用一个数组从f(3)开始依次向f(4), f(5) 递推不就没有问题了,也不会溢出,速度也快得多
追问
麻烦给我一个正解被.... 我被卡这了,谢谢
追答
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
以下是用单变量迭代的方法:
unsigned long int r = 1, s = 1, i, t;
for (i = 3; i <= n; ++ i)
{
t = (A * r + B * s) % 7;
s = r;
r = t;
}
循环完了,r就是结果
用数组来完成不要一个结果单独放一个数组元素,因为n可能到100000000,还是可能会溢出,可以考虑像上面的一样原地来做
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询