AC

robin88  •  9个月前


include

include

// 大数乘法
std::vector multiply(std::vector& num, int factor) {

int carry = 0;  
for (size_t i = 0; i < num.size(); ++i) {  
    int product = num[i] * factor + carry;  
    num[i] = product % 10;  
    carry = product / 10;  
}  
while (carry > 0) {  
    num.push_back(carry % 10);  
    carry /= 10;  
}  
return num;  

}

// 大数加法
std::vector add(std::vector& num1, const std::vector& num2) {

int carry = 0;  
size_t maxSize = std::max(num1.size(), num2.size());  
num1.resize(maxSize, 0); // 确保num1至少和num2一样长,不足部分用0填充  
for (size_t i = 0; i < maxSize || carry > 0; ++i) {  
    if (i == num1.size()) { // 如果需要,扩展num1来存储进位  
        num1.push_back(0);  
    }  
    int sum = num1[i] + (i < num2.size() ? num2[i] : 0) + carry;  
    num1[i] = sum % 10;  
    carry = sum / 10;  
}  
return num1;  

}

// 打印大数
void print(const std::vector& num) {

for (auto it = num.rbegin(); it != num.rend(); ++it) {  
    std::cout << *it;  
}  
std::cout << std::endl;  

}

int main() {

using namespace std;  

int N;  
cin >> N;  

vector<int> factorial(1, 1); // 初始化为1的阶乘,即{1}  
vector<int> sum(1, 1); // 初始化为1的阶乘的和,即{1}(实际上这里初始化为{0}也可以,因为后面会重新计算)  

// 动态规划计算阶乘和  
for (int i = 2; i <= N; ++i) {  
    factorial = multiply(factorial, i); // 计算i的阶乘  
    sum = add(sum, factorial); // 将当前阶乘累加到总和中  
}  

// 打印结果  
print(sum); // 输出累加结果S  
return 0;  

}


评论:

请先登录,才能进行评论