14:求10000以内n的阶乘

一、题目链接

http://noi.openjudge.cn/ch0106/14/

二、解题思路

◎ 根据题意,n!=基数1循环乘上2、3、4、…、n;
◎ 从低位到高位,用当前结果的每一位数字乘上当前乘数,同时加上进位,形成新的计算结果。

三、实施步骤

四、Java程序

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    /**
     * 计算给定整数的阶乘
     *
     * @param n int类型的整数,代表给定整数
     * @return int类型的数组,存储n!
     */
    public int[] factorial(int n) {
        int[] ans = new int[35660]; // 存储n!
        ans[0] = 1; // 阶乘的基数为1
        int length = 1; // 计算结果的实际长度,初始时为1
        int carry; // 每次计算的进位
        int i;
        int j;
        /* 标记i代表每次的乘数,i从2开始,到n为止,更新步长为1 */
        for (i = 2; i <= n; i++) {
            carry = 0; // 初始化当前计算的进位
            /* 标记j代表当前结果的每个数位,j从0开始,到length-1为止,更新步长为1 */
            for (j = 0; j < length; j++) {
                ans[j] = carry + ans[j] * i; // 当前数位乘上当前乘数i,同时加上进位
                carry = (ans[j] > 9 ? ans[j] / 10 : 0); // 更新进位
                ans[j] = (ans[j] > 9 ? ans[j] % 10 : ans[j]); // 更新当前数位
            }
            /* 计算结果产生更高的进位时 */
            while (carry > 0) {
                ans[length] = (carry > 9 ? carry % 10 : carry); // 设置更高一位的数字
                length++; // 计算结果的实际长度加1
                carry = carry / 10; // 更新进位
            }
        }
        /* ans中,小的下标代表低的位数,因此需要返回结果的倒序 */
        for (i = 0; i < length / 2; i++) {
            carry = ans[i];
            ans[i] = ans[length - i - 1];
            ans[length - i - 1] = carry;
        }
        return Arrays.copyOfRange(ans, 0, length); // ans[0]~ans[length-1]构成最终计算结果
    }

    public static void main(String[] args) {
        Main test = new Main();
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int[] ans = test.factorial(n);
        for (int i : ans) {
            System.out.print(i);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江苏科技大学_计算机学院_潘磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值