[color=blue]方法一:用递归 递归方法思路清晰,编程简单(不能承担大容量的计算,例如超过几十的阶层,运算速度急速下降),时间复杂度是[/color]
[color=blue]方法二:用for循环 虽然效率也不是很快,但是时间复杂度只有n,单层循环效率肯定比递归快[/color]
public int fun(n){
if(n<0){
throw new MyException("负数不能求阶层");
}else{
if(n<=1){
return 1;
}else{
return n*fun(n-1);
}
}
}
[color=blue]方法二:用for循环 虽然效率也不是很快,但是时间复杂度只有n,单层循环效率肯定比递归快[/color]
public int fun(n){
int sum=1;
for(int i=n;i>=1;n--){
sum=sum*i
}
return sum;
}