ub求助

P1009 [NOIP1998 普及组] 阶乘之和

cosmos31415926 @ 2023-11-06 14:28:48

有人说可能有undefined behavior,大佬们帮忙看看


#include <bits/stdc++.h>
using namespace std;
int n;
int ans[100], mem[100];
bool zero_over;
void mem_multiply_i(int num)
{
    int first_digit[100];
    int second_digit[100];
    int first = num % 10, second = num / 10;
    int carry = 0;
    for (int i = 0; i < 100; i++)
    {
        first_digit[i] = mem[i] * first % 10 + carry;
        carry = mem[i] * first / 10;
        if (first_digit[i] >= 10)
        {
            carry += first_digit[i] / 10;
            first_digit[i] %= 10;
        }
    }
    if (second == 0)
    {
        for (int i = 0; i < 100; i++)
        {
            mem[i] = first_digit[i];
        }
        return;
    }
    carry = 0;
    for (int i = 1; i < 100; i++)
    {
        second_digit[i] = mem[i - 1] * second % 10 + carry;
        carry = mem[i - 1] * first / 10;
        if (second_digit[i] >= 10)
        {
            carry += second_digit[i] / 10;
            second_digit[i] %= 10;
        }
    }
    carry = 0;
    for (int i = 0; i < 100; i++)
    {
        mem[i] = first_digit[i] + second_digit[i] % 10 + carry;
        carry = first_digit[i] + second_digit[i] / 10;
        if (mem[i] >= 10)
        {
            carry += mem[i] / 10;
            mem[i] %= 10;
        }
    }
}

void ans_plus_mem()
{
    int carry = 0;
    for (int i = 0; i < 100; i++)
    {
        ans[i] += carry;
        carry = (ans[i] + mem[i]) / 10;
        ans[i] = (ans[i] + mem[i]) % 10;
        if (ans[i] >= 10)
        {
            carry += ans[i] / 10;
            ans[i] %= 10;
        }
    }
}

int main()
{
    scanf("%d", &n);
    mem[0] = 1;
    for (int i = 1; i <= n; i++)
    {
        mem_multiply_i(i);
        ans_plus_mem();
    }
    for (int i = 99; i >= 0; i--)
    {
        if (zero_over or ans[i] != 0)
        {
            zero_over = true;
            printf("%d", ans[i]);
        }
    }
    return 0;
}

by 编码落寞 @ 2023-11-06 15:44:21

@cosmos31415926

    int first_digit[100];
    int second_digit[100];

建议初始化


|