跳到正文

算法·理论

计算n的阶乘

kkkkkkkkkkkkksc03约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月17日
收录
2026年10月17日
更新
2026年11月15日
篇幅
约 4 分钟

版本

  1. v1当前

代码

C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <chrono>
const long long BASE = 1000000000LL; 
const int DIGITS_PER_BLOCK = 9;
struct BigInt {
    std::vector<int> digits;
    BigInt() {
        digits.push_back(1);
    }
    void multiply(int k) {
        long long carry = 0;
        for (size_t i = 0; i < digits.size(); ++i) {
            long long product = (long long)digits[i] * k + carry;
            digits[i] = static_cast<int>(product % BASE);
            carry = product / BASE;
        }
        while (carry > 0) {
            digits.push_back(static_cast<int>(carry % BASE));
            carry /= BASE;
        }
    }
    std::string toString() const {
        if (digits.empty()) return "0";
        std::string result;
        result += std::to_string(digits.back());
        for (int i = static_cast<int>(digits.size()) - 2; i >= 0; --i) {
            std::string block = std::to_string(digits[i]);
            while (block.length() < DIGITS_PER_BLOCK) {
                block.insert(block.begin(), '0');
            }
            result += block;
        }
        return result;
    }
};
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n;
    std::cin >> n;
    std::cout << "正在计算 " << n << "! ..." << std::endl;
    auto start = std::chrono::high_resolution_clock::now();
    BigInt fact;
    fact.digits.reserve(700000); 
    for (int i = 2; i <= n; ++i) {
        fact.multiply(i);
        if (i % (n/100) == 0) {
            std::cerr << "当前进度:" << i/(n/100) << "%" << std::endl;
        }
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    std::cerr << "计算耗时: " << diff.count() << " 秒" << std::endl;
	std::cout << "计算完成,结果位数: " << fact.toString().length() << std::endl;
    std::cout << fact.toString() << std::endl;
    return 0;
}
原文