求出1000(n)的阶乘所有零和尾部零的个数

本文介绍了一种不使用递归的方法来计算1000的阶乘中所有零的数量及尾部零的数量,并提供了一种递归方法来高效地计算尾部零的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不用递归做:

import java.math.BigInteger;

public class Test {

    /**
     * @param args
     * 求出1000的阶乘所有零和尾部零的个数,不用递归做
     */
    public static void main(String[] args) {
        //所有0
        demo1();
        //尾部0
        demo2();
    }

    public static void demo2() {		//获取1000的阶乘尾部有多少个零
        BigInteger bi1 = new BigInteger("1");
        for(int i = 1; i <= 1000; i++) {
            BigInteger bi2 = new BigInteger(i+"");
            bi1 = bi1.multiply(bi2);
        }
        String str = bi1.toString();
        StringBuilder sb = new StringBuilder(str);
        str = sb.reverse().toString();	//链式编程

        int count = 0;
        for(int i = 0; i < str.length(); i++) {
            if('0' != str.charAt(i)) {
                break;
            }else {
                count++;
            }
        }

        System.out.println(count);
}

    public static void demo1() {		//求1000的阶乘中所有的零
        BigInteger bi1 = new BigInteger("1");
        for(int i = 1; i <= 1000; i++) {
            BigInteger bi2 = new BigInteger(i+"");
            bi1 = bi1.multiply(bi2);
        }
        String str = bi1.toString();
        int count = 0;
        for(int i = 0; i < str.length(); i++) {
            if('0' == str.charAt(i)) {
                count++;
            }
        }
        System.out.println(count);
    }

}

输出:

472
249

用递归做(尾部零的个数):

public class Test {

    /**
     * @param args
     * 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100...1000  1000 / 5 = 200
     * 5 * 5	5 * 5 * 2 	5 * 5 * 3	5 * 5 * 4	5 * 5 * 5	5 * 5 * 6	200 / 5 = 40
     * 5 * 5 * 5 * 1	5 * 5 * 5 * 2	5 * 5 * 5 * 3	5 * 5 *  5 * 4	5 * 5 *  5 * 5	5 * 5 *  5 * 6  5 * 5 *  5 * 7  5 * 5 *  5 * 8
    40 / 5 = 8
    5 * 5 * 5 * 5														8 / 5 = 1
     */
    public static void main(String[] args) {
        System.out.println(fun(1000));
    }

    public static int fun(int num) {
        if(num > 0 && num < 5) {
            return 0;
        }else {
            return num / 5 + fun(num / 5);
        }
    }
}

输出:

249

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值