public class addFrom1ToN_Recursive { static int addFrom1ToN_Recursive(int n){//递归 return n<=0?0:n+addFrom1ToN_Recursive(n-1); } static int addFrom1ToN_Iterative(int n){//循环 int result=0; for(int i=1;i<=n;i++){ result+=i; } return result; } public static void main(String[] args){ System.out.println(addFrom1ToN_Recursive(100)); System.out.println(addFrom1ToN_Iterative(100)); } }
public class fibonacci { static long Fib(long n){ if(n<=0){ return 0; } else if(n==1){ return 1; } else{ return Fib(n-1)+Fib(n-2); } } }
static long Fib2(int n){ int[] result = {0,1}; if(n<2){ return result[n]; } long fibOne=0; long fibTwo=1; long fibN=0; for(int i=2;i<=n;i++){ fibN = fibOne+fibTwo; fibOne = fibTwo; fibTwo = fibN; } return fibN; }
public class RectangularCover { public static int rectangularCover(int n){ if(n<=0){ return 0; } if(n<=2&&n>0){ return n; } else{ return rectangularCover(n-1)+rectangularCover(n-2); } } public static int rectangularCover2(int n){ if(n<3){ return n; } int fib1=1; int fib2=2; int fibN=0; for(int i=3;i<=n;i++){ fibN=fib1+fib2; fib1=fib2; fib2=fibN; } return fibN; } public static void main(String[] args){ System.out.println(rectangularCover(8)); System.out.println(rectangularCover2(8)); } }