java算法(统计阶乘尾部零的个数)

三号到期 2020-10-05 07:22:15

如何更高效的求n的阶乘,并统计阶乘尾部零的个数,各位大佬,请多多指教!!!
...全文
9441 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_39936465 2020-10-10
  • 打赏
  • 举报
回复
引用 7 楼 KeepSayingNo 的回复:
public class Test { public static void main(String[] args) { Test test = new Test(); System.out.println((test.jiechen(new BigDecimal(4)))); } public BigDecimal jiechen(BigDecimal input){ if(input == BigDecimal.ONE){ return input; } else { return input.multiply(jiechen(input.add(new BigDecimal(-1)))); } } }
我上面算的是50w阶乘的末尾0的个数,你试试你的程序算50w阶乘的时间
KeepSayingNo 2020-10-09
  • 打赏
  • 举报
回复
public class Test { public static void main(String[] args) { Test test = new Test(); System.out.println((test.jiechen(new BigDecimal(4)))); } public BigDecimal jiechen(BigDecimal input){ if(input == BigDecimal.ONE){ return input; } else { return input.multiply(jiechen(input.add(new BigDecimal(-1)))); } } }
qq_39936465 2020-10-09
  • 打赏
  • 举报
回复
算法

public class NewSolution {
	
    public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		long n=scanner.nextLong();
		long start=System.currentTimeMillis();
		int count=trailingZeros(n);
		System.out.println(count);
		long end=System.currentTimeMillis();
		System.out.println("最终用时:" + (end - start)+ "毫秒");
	}
    
    public static int trailingZeros(long n) {
    	int count=0;
    	while (n>5) {
			count+=n/5;
			n/=5;
		}
    	return count;
	}

}


500000
124999
最终用时:1毫秒
你试试用大数的速度,根本不能比
  • 打赏
  • 举报
回复
使用BIGINTEGER一下子搞定,简单。
三号到期 2020-10-06
  • 打赏
  • 举报
回复
谢谢
qybao 2020-10-05
  • 打赏
  • 举报
回复
逢末尾有几个0的数,相乘结果末尾必有几个0,比如a*10末尾必有1个0,a*100末尾必有2个0,等等。 逢末尾数5的,相乘必有1个0 所以统计一下有几个末尾是0或5的数
tianfang 2020-10-05
  • 打赏
  • 举报
回复
纠正一下,n的阶乘 共有 n/5+n/25+n/125…… +n/5^k 个0 5^k的时候,只增加n/5^k个5,因为5^(k-1)已经计算过
tianfang 2020-10-05
  • 打赏
  • 举报
回复
说说算法,5*2 =10,阶乘中2的个数足够多,主要要计算出5 的个数,那么就按5,25,…… 5^n ,去计算5的个数 5^n的时候,只增加n个,因为5^(n-1)已经计算过了

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧