Day16 递归
作者:互联网
1、说到递归就不得不说菲波那契数列,F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*),相当于每次都是自己调用了自己;
2、sumToN() 这个方法是求0-N之和,可以理解成 N 与 sumToN(N-1) 之和,即 sumToN(0) = 0 , sumToN(N) = sumToN(N - 1) + N(n∈N*);
1 public class Recursion { 2 /** 3 * Sum to N. No loop, however a stack is used. 4 * 5 * @param paraN The given value. 6 * @return The sum. 7 */ 8 public static int sumToN(int paraN) { 9 if (paraN <= 0) { 10 // Basis. 11 return 0; 12 } // Of if 13 14 return sumToN(paraN - 1) + paraN; 15 } // Of sumToN 16 17 /** 18 * Fibonacci sequence. 19 * 20 * @param paraN The given value. 21 * @return The sum. 22 */ 23 public static int fibonacci(int paraN) { 24 if (paraN <= 0) { 25 return 0; 26 } if (paraN == 1) { 27 return 1; 28 }// Of if 29 return fibonacci(paraN - 1) + fibonacci(paraN - 2); 30 }// Of fibonacci 31 32 public static void main(String args[]){ 33 int tempValue = 5; 34 System.out.println("0 sum to " + tempValue + sumToN(tempValue)); 35 tempValue = -1; 36 System.out.println("0 sum to " + tempValue + sumToN(tempValue)); 37 38 for (int i = 0; i < 10; i++) { 39 System.out.println("Fibonacci " + i + ": " + fibonacci(i)); 40 } // Of for i 41 } // Of main 42 } // Of class Recursion
标签:递归,No,int,paraN,sumToN,Day16,public 来源: https://www.cnblogs.com/f1uency/p/16219608.html