Java|java 递归recursion的使用

Java|java 递归recursion的使用

/**
* 测试递归recursion
*/
public class TestRecursion2 {
public static int m = 0;
public static int factorial(int n){
//factorial阶乘
m++;
if (m<n){
return m*factorial(n);
else{
m = 0;
return n;


public static void main(String[
args) {
System.out.println(factorial(10));
System.out.println(10*9*8*7*6*5*4*3*2);


class TestRecursion3{
//计算斐波那契数列 [123581321.....
每一位是前两位的和
public static int abc(int n) {
//计算第n位的值
if (n > 2) {
return abc(n - 1) + abc(n - 2);
else if (n==2) {
return 2;
else return 1;

public static int def(int n){
if (n<2){
return 1;
else if (n<3){
return 2;

int a1 = 1;
int a2 = 2;
int result = a1+a2;
for (int i =4;i<=n;i++){
a1 = a2;
a2 = result;
result = a1+a2;

return result;

public static int ghi(int n){
if (n<2){
return 1;
else if (n<3){
return 2;

int[
arr = new int[n
;
arr[0
= 1;
arr[1
= 2;
for (int i=2;i<n;i++){
arr[i
= arr[i-1
+arr[i-2
;

return arr[n-1
;

public static void main(String[
args) {
int n = new Random().nextInt(20)+1;
System.out.println(n);
System.out.println(abc(n));
System.out.println(def(n));
System.out.println(ghi(n));


【Java|java 递归recursion的使用】