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);
}
}
|
|