public class Test { public static void main(String[] args) { int num1 = 1; int num2 = 1; int n = 2; int num3 = 1; long startTime = System.currentTimeMillis(); for(int i = 3; i<=n;i++) { num3 = num1 + num2; num1=num2; num2=num3; } long endTime = System.currentTimeMillis(); System.out.println(startTime - endTime); System.out.println("使用循环" + num3); startTime = System.currentTimeMillis(); int result = fi(n); endTime = System.currentTimeMillis(); System.out.println(startTime - endTime); System.out.println(result); } public static int fi(int n) { int result = 0; if(n ==1 || n ==2) { result =1; }else { result = fi(n-1)+ fi(n-2); } return result; } }
代码进一步修改完善
public class Test { public static void main(String[] args) { int n = 5; long startTime = System.currentTimeMillis(); System.out.println("使用循环" + f(n)); long endTime = System.currentTimeMillis(); System.out.println(startTime - endTime); startTime = System.currentTimeMillis(); System.out.println(fi(n)); endTime = System.currentTimeMillis(); System.out.println(startTime - endTime); } public static long f(int n) { if(n < 1) { System.out.println("有错误"); return -1; } long num1 = 1L; long num2 = 1L; long num3 = 1L; if(n ==1 || n ==2) { num3 =1; } for(int i = 3; i<=n;i++) { num3 = num1 + num2; num1=num2; num2=num3; } return num3; } public static long fi(int n) { if(n < 1) { System.out.println("有错误"); return -1; } long result = 0; if(n ==1 || n ==2) { result =1; }else { result = fi(n-1)+ fi(n-2); } return result; } }
下面的,我写了,一半
有需要的可以动动脑筋练练手
public class FiBoClass { // 1、 1、 2、 3、5、8、13、21、34 //num1 num2 num3 public static void main(String[] args) { int num1 = 1; int num2 = 1; int n = 9; int num3 = 0; for(int i=3; i<=n; i++) { num3 = num1 + num2; System.out.println("第"+i+"项的数字是:-->"+num3); num1 =num2; num2 = num3; } System.out.println(num3); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)