Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 202453 Accepted Submission(s): 50972
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).
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
Sample Output
2 5
我开始想用递归直接就求出来了(天真),但是提交后才知道Runtime Error(INTEGER_DIVIDE_BY_ZERO);
n太大可能递归次数多就溢出了。每个线程都建立一个默认1M堆栈。这个堆栈是供函数调用时使用,线程内函数里的各种静态变量都是从这个默认堆栈里分配的.
RE代码:
1 #include<iostream> 2 using namespace std; 3 int f(int a,int b,int n) { 4 int m; 5 if(n==1||n==2) 6 return 1; 7 else { 8 m=(a*f(a,b,n-1)+b*f(a,b,n-2))%7; //会溢出 9 return m; 10 } 11 } 12 int main() { 13 while(1) { 14 int A,B,n; 15 cin>>A>>B>>n; 16 if(A==0&&B==0&&n==0||A<1||B<1||n<1) 17 break; 18 else { 19 cout<<f(A,B,n)<<endl; 20 } 21 } 22 return 0; 23 }
还是看了别人的才发现mod7是有规律的,周期是49,所以:
1 #include<iostream> 2 using namespace std; 3 4 int f[105]; 5 int main() 6 { 7 int a,b,n; 8 while(1) 9 { 10 cin>>a>>b>>n; 11 if(a==0&&b==0&&n==0) 12 break; 13 f[1]=1,f[2]=1; 14 for(int i=3;i<=49;i++) 15 { 16 f[i]=(a*f[i-1]+b*f[i-2])%7; 17 } 18 int num=n%49; 19 cout<<f[num]<<endl; 20 } 21 return 0; 22 }