递归求5!:
public class Test {
public int digui(int n) {
if (n > 1)
return n * (digui(n - 1));
else
return 1;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.digui(5)); //result=120
}
}
当n>1时,a=n(n-1)n(-2)2 当n=1时,结果为a1。
非递归求5!
public class Test {
public int nodigui(int n) {
int s = 1;
while (n > 1) {
s *= n;
n--;
}
return s;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.nodigui(4));
}
}