求阶乘的最后非零位

基本思想:将x个输入每10个一组进行分组,剩余的最后一组单独列出。将10个一组的数据相乘后再除以(5的倍数乘4),以第一组数据为例:(1*2*3*4*5*6*7*8*9*10)/(4*5*10)=1*2*3*4*6*7*8*9/4,最后一位是4,同理,别的几组最后一位数字也是4,易得最后一位数字为4或6。接下来处理与5的倍数相关的数据,即4*(5*10)4(15*20)…=10(1*2*3*4*5*6*7*8…),此处为递归。最后再处理最后一个分组,for语句进行处理。(代码实现只验证了部分数据)


import java.util.Scanner;

public class zqt{
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();

        int result = solve1(x);
        System.out.print(result);
    }

    private static int solve(int x) {
        int a = x / 10;
        int b = x % 10;
        int result = 1;
        if (a != 0) {
            if ((a % 2) == 1) {
                result = 4;
            } else {
                result = 6;
            }
        }

        int temp = 0;
        if (x == 1 || x == 2 || x ==3 || x ==4) {
            switch (x) {
                case 1:
                    return 1;
                case 2:
                    return 2;
                case 3:
                    return 6;
                case 4:
                    return 4;
            }
        } else {
            temp = temp + solve(x / 5);
        }

        result = result * temp;
        if (b < 5) {
            for (int i = 1; i <= b; i++) {
                result *= i;
            }
        } else {
            for(int i = 3; i <= b; i++) {
                if (i == 5) continue;
                result *= i;
            }
        }

        return result % 10;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值