黑马程序员技术交流社区
标题: 求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×...×999×1000 [打印本页]
作者: code2014 时间: 2014-5-9 08:06
标题: 求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×...×999×1000
public static void main(String[] args) {
BigInteger bir = new BigInteger("1");
for(int i=1;i<=1000;i++)
{
bir= bir.multiply(new BigInteger(String.valueOf(i)));
}
String s=bir.toString();
System.out.println(s);
int count=0;
for (int i = 0; i < s.length(); i++)
{
if(s.charAt(i)=='0') count++;
}
System.out.println("共有"+count+"个0");
作者: 陨落″烟雨。 时间: 2014-5-17 08:12
还是要找出规律才好- package cn.itcast.test;
- public class Test2 {
- /**
- * @param args
- * 1000!尾部有多少个零,用递归来实现
- * 10!尾部有几个零 5 10 有两个零 10/5=2
- * 20!尾部有几个零 5 10 15 20 有四个零 20/5=4
- * 30!尾部有几个零 5 10 15 20 25(5*5) 30 有七个零 30/5=6 + 6/5=1
- * 50!尾部有几个零 5 10 15 20 25(5*5) 30 35 40 45 50(5*5*2) 50/5=10 + 10/5 = 12
- * 150!尾部有几个零
- * 5 10 15 20 25(5*5) 30 35 40 45 50(5*5*2) 55 60 65 70 75(5*5*3)
- * 80 85 90 95 100(5*5*4) 105 110 115 120 125(5*5*5) 130 135 140 145 150(5*5*6)
- * 150/5 = 30 + 30 / 5 = 6 + 6/5
- */
- public static void main(String[] args) {
- int num = getZero(1000);
- System.out.println(num);
- }
-
- public static int getZero(int num) {
- if(num >= 1 && num <= 4) {
- return 0;
- }else {
- return num / 5 + getZero(num / 5);
- }
- }
- }
复制代码
作者: gentleman 时间: 2014-5-24 07:20
- package com.itheima;
- public class Multiply {
- public static void main(String[] args)
- {
- int mul=1,num=0,end=1000;
-
-
- for(int i=1;i<=end;i++)
- {
- mul=mul*i;
- //除去乘积后面所有0,并累加这些0
- while(mul%10==0)
- {
- mul=mul/10;
- num++;
- }
- //取得最后以为有效数字,因为下一个乘积末尾是否有0只与末尾数有关
- mul=mul%10;
-
-
- }
- System.out.println(end+"的阶乘,共有"+num+"个零");
- }
- }
复制代码
也可以这样做
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |