杭电ACM 1005 一直报错
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.
For each test case, print the value of f(n) on a single line.
一开始我用的递归,但是报Memory Limit Exceeded,我就没用递归了。
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a, b;
int n;
while (in.hasNext()) {
a = in.nextInt();
b = in.nextInt();
n = in.nextInt();
// 1 <= A, B <= 1000, 1 <= n <= 100,000,000
if (a < 1 & a > 1000 & b < 1 & b > 1000 & b < 1 & a > 100000000)
System.exit(0);
if (a == 0 & b == 0 & n == 0)
System.exit(0);
BigInteger f[] = new BigInteger[n];
f[0] = BigInteger.valueOf(1);
f[1] = BigInteger.valueOf(1);
for (int i = 2; i < f.length; i++) {
f[i] = (f[i - 1].multiply(BigInteger.valueOf(a)).add(f[i - 2]
.multiply(BigInteger.valueOf(b)))).remainder(BigInteger
.valueOf(7));
//f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
}
System.out.println(f[n - 1]);
}
}
}一直报错,我试了给的例子“1 1 3”和“1 2 10”,结果2和5是对的。是哪里错了呢?
------解决方案--------------------这个是我当年AC的C++版本:
#include<iostream>
using namespace std;
int main()
{
int A,B;
unsigned int n;
cin>>A>>B>>n;
while(A&&B&&n)
{
int *p=new int[50]; //存在循环,在这里判断,来减少运行时间
if(n>50)
n=(n-2)%48+2;
*p=*(p+1)=1;
for(int i=2;i<n;i++)
*(p+i)=(A**(p+i-1)+B**(p+i-2))%7; //公式
cout<<*(p+n-1)<<endl;
cin>>A>>B>>n;
}
return 0;
}
------解决方案--------------------我之前也犯过类似的错误,这个应该不是报错,而是Time Limited Exceed,我的java版本你可以参考下:
import java.util.Scanner;
public class NumberSequence2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a, b;
int n;
while (in.hasNext()) {
a = in.nextInt();
b = in.nextInt();
n = in.nextInt();
// 1 <= A, B <= 1000, 1 <= n <= 100,000,000
if (a < 1 & a > 1000 & b < 1 & b > 1000 & b < 1 & a > 100000000)
System.exit(0);
if (a == 0 & b == 0 & n == 0)
System.exit(0);
int f[] = new int[50];
for (int i = 1; i < 50; i++) {
if (i == 1
------解决方案--------------------
i == 2) {
f[i] = 1;
} else {
f[i] = (a * f[i - 1] + b * f[i - 2]) % 7;
}
}
System.out.println(f[n % 49]);
}
in.close();
}
}
另附本人关于此题的博客一篇,欢饮讨论:
http://blog.csdn.net/jinyongqing/article/details/21537175