打印100的阶乘(大数问题,Java好解)

该博客介绍了如何使用Java来计算1到100之间的正整数阶乘,特别适合处理大数问题。提供了输入输出示例,帮助理解算法的实现。

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

FCTRL2 - Small factorials


You are asked to calculate factorials of some small positive integers.

Input

An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.

Output

For each integer n given at input, display a line with the value of n!

Example

Sample input:
4
1
2
5
3

Sample output:

1
2
120
6
    #include <iostream>  
    #include <vector>  
      
    std::vector<int> v;  
      
    void fact(int n)  
    {  
        v.clear();  // !  
        v.resize(200, 0);  
        v[199] = 1;  
      
        for(int i = 2; i <= n; ++i)  
        {  
            int carry = 0;  
            for(int j = 199; j >= 0; --j)  
            {  
                v[j] = v[j] * i + carry;  
                carry = v[j] / 10;  
                v[j] %= 10;  
            }  
        }  
    }  
      
    int main()  
    {  
        int T;  
        std::cin >> T;  
        int n;  
      
        while(T--)  
        {  
            std::cin >> n;  
      
            fact(n);  
      
            int i = 0;  
            while(v[i] == 0)  
            {  
                ++i;  
            }  
            for(; i < 200; ++i)  
            {  
                std::cout << v[i];  
            }  
            std::cout << std::endl;  
        }  
      
        return 0;  
    }  

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
/****************************************************************************************************************/
public class Main {
    public static void main(String[] args)throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BigInteger[] fac = new BigInteger[101];
        fac[0] = fac[1] = BigInteger.ONE;
        
        for(int i = 2;i <= 100;i++)
        {
            BigInteger temp = BigInteger.valueOf(i);
            fac[i] = fac[i-1].multiply(temp);
        }
        
        int t = Integer.parseInt(bf.readLine());
        while(t-- > 0){
            int num = Integer.parseInt(bf.readLine());
            System.out.println(fac[num]);
        }
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值