n! = n * (n-1) * (n-2) * (n-3) * ... * 1
阶乘指从1乘以2乘以3乘以4一直乘到所要求的数。例如所要求的数是4,则阶乘式是1×2×3×4,得到的积是24,24就是4的阶乘。 例如所要求的数是6,则阶乘式是1×2×3×……×6,得到的积是720,720就是6的阶乘。例如所要求的数是n,则阶乘式是1×2×3×……×n,设得到的积是x,x就是n的阶乘。 任何大于1的自然数n阶乘表示方法: n!=1×2×3×……×n 或 n!=n×(n-1)! 5!=5*4*3*2*1=120( n的双阶乘: 当n为奇数时表示不大于n的所有奇数的乘积 如:7!!=1×3×5×7 当n为偶数时表示不大于n的所有偶数的乘积(除0外) 如:8!!=2×4×6×8 小于0的整数-n的阶乘表示(-n)!= 1 / (n+1)!)
Common.java
package com.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Common {
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
return br.readLine();
}
public static int getInt() throws IOException {
String in = getString();
return Integer.parseInt(in);
}
}
FactorialApp.java
package com.ch6.triangle;
import java.io.IOException;
import com.util.Common;
public class FactorialApp {
public static int factorial(int n) {
if (n == 0) {
System.out.println("Returned 1 .") ;
return 1;
} else {
int temp = n * factorial(n -1) ;
System.out.println("Returning : " + temp ) ;
return temp;
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
while (true) {
System.out.println("Enter a number: ");
int n = Common.getInt();
int ret = factorial(n);
System.out.println("factorial("+ n + ") is Returned : " + ret);
System.out.println(" ");
}
}
}
输出结果:
Enter a number:
6
Returned 1 .
Returning : 1
Returning : 2
Returning : 6
Returning : 24
Returning : 120
Returning : 720
factorial(6) is Returned : 720
Enter a number:
7
Returned 1 .
Returning : 1
Returning : 2
Returning : 6
Returning : 24
Returning : 120
Returning : 720
Returning : 5040
factorial(7) is Returned : 5040
Enter a number: