JAVA面向程序第二版课后习题4.1

来源:互联网 发布:tensorflow 入门 编辑:程序博客网 时间:2024/06/16 13:30
    本题要求算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);}}}

0 0