A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 支胜勇 中级黑马   /  2014-6-1 23:17  /  994 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1000!的求法,大家还有更好的方法吗?
package com.itheima;

import java.math.BigInteger;

/**
* 第9题:求1000!的结果中包含多少个0
* 1000! = 1×2×3×4×5×...×999×1000
* @author 支胜勇
*
*/
public class Test9 {
       
       
        /***
         * 计算n的阶乘
         * @param n
         * @return
         */
        public static BigInteger getFactorial(int n){
               
                //当n比较大的时候,n的阶乘会在Long类型中溢出,所以用BigInteger类的对象来存放阶乘结果比较安全
                BigInteger product=new BigInteger("1");
               
                if(n<0){
                       
                        System.err.println("n必须大于等于0!");
                       
                }else if(n<=1){
                       
                        return product= new BigInteger("1");
                       
                }else{
                       
                        for(;n>=1;n--){//开始计算阶乘
                               
                                //BigInteger的方法multiply用于计算两个数的乘积,实例化一个BigInteger匿名对象,并将它与当前BigInteger对象相乘
                                product=product.multiply(new BigInteger(new Integer(n).toString()));
                        }
                }
               
                return product;
        }
       
       
       
        /***
         * 计算n!的结果中共有多少个0
         * @param n
         * @return
         */
        public static void getFactorialZeroCount(int n){
               
                //调用getFactorial(int n)方法计算n!,然后转为字符串
                String facResult=getFactorial(n).toString();
               
                int zeroCount=0;
               
                while(facResult.contains("0")){//当字符串中含有0时,zeroCount++,并且截取0之后的字符串作为下一次判断的对象,直到结果中不含0
                       
                        zeroCount++;
                       
                        facResult=facResult.substring(facResult.indexOf("0")+1);
                }
               
                //向控制台输出结果
                System.out.print(n+"!的结果中包含"+zeroCount+"个0");
        }
       
       
        /***
         * 程序入口
         * @param args
         */
        public static void main(String args[]){
               
                //计算n!的结果中共有多少个0的方法
                getFactorialZeroCount(1000);
               
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马