馬士兵J2SE-第二章-J2SE基礎語法(周六補充)-遞歸、非遞歸
//求5的階乘
public class test {
public static void main(String[] args) {
System.out.println(method(4));
}
public static int method(int n) {
if (n==1) return 1;
else return n*method(n-1);
}
}
輸出:24
//利用遞歸求Fibonacci數列:1,1,2,3,,5,8……第40個數的值。數列滿足遞推公式:
//F1=1,F2=1,……,Fn=Fn-1 + Fn-2(n>2)
public class test {
public static void main(String[] args) {
System.out.println(method(4));
}
public static int method(int n) {
if (n==1||n==2) return 1;
else return method(n-1)+method(n-2);
}
}
輸出: 3
非遞歸調用
public class Fab {
public static void main(String[] args) {
System.out.println(f(-9));
}
public static long f(int index) {
if(index < 1) {
System.out.println("invalid parameter!");
return -1;
}
if(index == 1 || index == 2) {
return 1;
}
long f1 = 1L;
long f2 = 1L;
long f = 0;
for(int i=0; i<index-2; i++) {
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
}
輸出:
102334155
輸入-9時輸出:
invalid parameter
-1
最後更新:2017-04-02 06:52:05