给定数列 1, 1, 1, 3, 5, 9, 17, …,从第 4 项开始,每项都是前 3 项的和。求
第 20190324 项的最后 4 位数字。
import java.util.Collections;
import java.util.List;
public class 数列求值 {
public static void main(String[] args) {
int f1 = 1,f2 = 1,f3 = 1;
int f = 0;
for(int i=3;i<20190324;i++) {
f = (f1 + f2 + f3)%10000;
f1 = f2;
f2 = f3;
f3 = f;
}
System.out.println(f);
}
}
下面是我写的另一种方法,但是运行报错,希望有大佬帮忙指正一下
public class 数列求值 {
public static void main(String[] args) {
int n = 20190324;
long res = F(n);
int ans = F(n)%10000;
System.out.println(ans);
}
private static int F(int n) {
if(n==1 || n==2 || n==3) {
return 1;
}
return F(n-1)+F(n-2)+F(n-3);
}
}