由于对于任意的n,
n! = (n-1)! * n
即令f(n) = n!,存在公式
f(n) = f(n-1) * n
int fac(int n){
if(n == 0 || n == 1) return 1
return fac(n-1)*n
}
public static void main(String[] args){System.out.println("输入n,按回车:")
Scanner s = new Scanner(System.in)
Integer n = Integer.parseInt(s.next())
Integer re = factorial(1, n)
System.out.println(re)
}
public static Integer factorial(Integer a, Integer b){
if(b == 1){
return a * b
}else{
return a * b * factorial(a, b-1)
}
}
这个最后吐槽一句,用循环一下就解决了,非要用递归,闲得蛋疼
求n的阶乘#include <iostream>
using namespace std
int fun(int n)
{
if(n == 0)
{
return 1
}
else
{
return n * fun(n-1)
}
}
int main()
{
int n
cin >>n
cout <<n <<"的阶乘为:" <<fun(n) <<endl
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)