天天看点

java n的阶乘 递归_java 递归与非递归求n的阶乘

public class Factorial {//求阶乘类

static int norecursion(int n) {

int sum = 1;

for(int i=1;i<=n;i++) {

sum *= i;

}

return sum;

}//norecursion

static int recursion(int n) {

int result;

if(n ==1)

{

return 1;

}

else

{

result = n*recursion(n-1);

return result;

}

}//recursion

public static void main(String[] args) {

// TODO Auto-generated method stub

int n = 10;

System.out.println("\n    递归求"+n+"阶乘结果为:"+recursion(n));

System.out.println("    非递归求"+n+"阶乘结果为:"+norecursion(n));

}//main

}

运行结果:

java n的阶乘 递归_java 递归与非递归求n的阶乘