版权声明:MZ21G https://blog.csdn.net/qq_35793285/article/details/84678907
最开始的代码是这样的,没说我超时,直接报错~~
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int num(int A,int B,int n) {
int[] ans = new int[n + 1];
ans[1] = 1;
ans[2] = 1;
for(int i = 3; i <= n; i++) {
ans[i] = (A * ans[i - 1] + B * ans[i - 2]) % 7;
}
return ans[n];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int A = scanner.nextInt();
int B = scanner.nextInt();
int n = scanner.nextInt();
if (A == 0 && B == 0 && n == 0) {
break;
}
int res = num(A,B,n);
System.out.println(res);
}
}
}
后来通过参考别人的代码发现是有规律的,最后是对7取余数,所以,f(n-1),f(n-2)最多各有七种情况(0、1、2、3、4、5、6),所以f(n)最多有7*7=49种情况,所以从一开始到49可能不尽相同,但是从50开始则开始循环,f(50)=f(50%49)=f(1)。这是解决超时和内存不够的办法。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int num(int A,int B,int n) {
int[] ans = new int[n + 1];
ans[1] = 1;
ans[2] = 1;
for(int i = 3; i <= n; i++) {
ans[i] = (A * ans[i - 1] + B * ans[i - 2]) % 7;
}
return ans[n];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int A = scanner.nextInt();
int B = scanner.nextInt();
int n = scanner.nextInt();
if (A == 0 && B == 0 && n == 0) {
break;
}
int res = num(A,B,n);
System.out.println(res);
}
}
}
参考资料: