本題要求算n!,算法很簡單,其實就是一個factorical方程,難點在于當n比較大時,超大資料的處理,這裡利用了BigInteger的方法,在網上也找了很多方法,有數組的比較高端,初學,用了一種比較簡單的方法。代碼如下:
</pre><pre name="code" class="java"></pre><pre name="code" class="java">package com.bingbingzhu.hw4;
/* Author:Bingbing Zhu
* Date:2/11/2015
* Function:assignment 4.1 to compute n!
*/
import javax.swing.JOptionPane;
import java.math.*;
public class Factorial
{
public static void main(String[] args)
{
String testn="";
testn = JOptionPane.showInputDialog("Please input your n, this small function can compute n!");
int n = Integer.parseInt(testn);
BigInteger temp = BigInteger.ONE;
if(n==0)
{
JOptionPane.showMessageDialog(null, "as n=0,n!=1");
}else if(n>0)
{
temp = BigInteger.ONE;
int j=n;
while(j>0)
{
temp = temp.multiply(BigInteger.valueOf(j));
j--;
}
JOptionPane.showMessageDialog(null,"we can get the result is"+n+"!="+temp);
}
}
}