一,简单Demo
public class Recursion {
public static void main(String[] args) {
test(100);
}
public static void test(int n) {
if(n == 0) {
return;
}
System.out.println(n);
test2(n - 1);
}
}
二,三角数字
public class Triangle {
public static int getNumber(int n) {
int total= 0;
while(n > 0) {
total = total + n;
n--;
}
return total;
}
public static int getNumberByRecursion(int n) {
if(n == 1) {
return 1;
} else {
return n + getNumberByRecursion(n - 1);
}
}
}
测试:
public class TestTriangle {
public static void main(String[] args) {
System.out.println(Triangle.getNumber(500));
System.out.println(Triangle.getNumberByRecursion(500));
}
}
三,斐波那契数列
public class Fibonacci {
public static int getNumber(int n) {
if(n == 1) {
return 0;
} else if(n == 2){
return 1;
} else {
return getNumber(n - 1) + getNumber(n - 2);
}
}
}
测试:
public class TestFibonacci {
public static void main(String[] args) {
System.out.println(Fibonacci.getNumber(5));
}
}