Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 212774 Accepted Submission(s): 53788
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
Sample Output
2
5
错误思路:递归
一开始看这道题,想都没想直接函数递归,VS上跑的不亦乐乎,样本测试用例都通过了,欸心想肯定过,拿到OJ上提交,显示内存溢出,眉头一皱发现事情并不简单,仔细分析,n可能是一个超大的数,当数很大时,函数递归的深度不可想象,把n换成大数果然,VS上也出现了栈溢出,先把错误代码po出来
#include<math.h>
#include<iostream>
#include<string.h>
using namespace std;
long long f(long long n,int A,int B)
{
long long result;
if (n == 1 || n == 2)
return 1;
else
{
result = (A*f(n - 1,A,B) + B * f(n - 2,A,B)) % 7;
return result;
}
}
int main() {
int A, B;
long long n;
while (cin >> A >> B >> n)
{
if (A == 0 && B == 0 && n == 0)
return 0;
if (A >= 1 && A <= 1000 && B >= 1 && B <= 1000 && n >= 1 && n <= 100000000)
{
cout << f(n,A,B)<<endl;
}
}
return 0;
}
正确思路:如题所述,发现数的顺序规律
仔细观察所给函数可以发现,无论f(n)怎么变,最终取模7后的答案,结果一定是[0,6],这个地方理解到很重要;也就是说,f(n-1)和f(n-2)的范围同样是在[0,6],那么当n>2时,两两组合得到的f(n)会有7*7=49种不同的答案,即结果取值会是49种一周期,之后所有的结果都会从者49种结果中产生,那么新代码的思路也就出来了,只需要将前49种结果都算出来,最后匹配n%49传参即可得到正确答案。
#include<math.h>
#include<iostream>
#include<string.h>
using namespace std;
int f(int n,int A,int B)
{
int result;
if (n == 1 || n == 2)
{
return 1;
}
else
{
result= (A*f(n - 1, A, B) + B * f(n - 2, A, B)) % 7;
return result;
}
}
int main() {
int A, B;
long n;
while (cin >> A >> B >> n)
{
if (A == 0 && B == 0 && n == 0)
return 0;
if (A >= 1 && A <= 1000 && B >= 1 && B <= 1000 && n >= 1 && n <= 100000000)
{
cout << f((n%49),A,B)<<endl;
}
}
return 0;
}