质因数分解程序不适用于某些输入

Prime factorization programm doesn't work for certain inputs

我是初学者。我应该编写一个简单的原始分解程序,而我想出的东西有一个奇怪的行为。 输入假定在 64 位整数(long long)范围内。

它工作得很好,直到我输入一定长度的值,即 13。(附图片),在这种情况下,它只是关闭而没有错误,我假设这表明程序将数字视为 0,因为它否则应该报错。

现在,我认为问题可能出在指针或 scanf 函数中,所以如果有人指出我的错误所在,我将不胜感激。 我在 Windows 10 上用 VS 编程,使用标准命令提示符作为终端。

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<stdint.h>

int ReadInput(int64_t *n, int *ret);
void Primal_Factorization(int64_t n);

enum {INPUT_ERROR = 100, SUCCESS = 0};

int main()
{
    int ret = SUCCESS;
    int64_t n = 0;
    while (ReadInput(&n, &ret) > 0)
    {
        Primal_Factorization(n);
    }
    if (n < 0)
    {
        fprintf(stderr, "Error: Chybny vstup!\n");
        ret = INPUT_ERROR;
    }
    return ret;
}

int ReadInput(int64_t *n, int *ret){
    if(scanf("%lld", n) != 1){
        *n = 0;
        fprintf(stderr, "Error: Chybny vstup!\n");
        *ret = INPUT_ERROR;
    }
    return *n;
}

void Primal_Factorization(int64_t n){
    int64_t n_sqrt = sqrt(n);
    int count;
    int64_t n_origin = n;
    bool first_iteration = true;
    printf("Prvociselny rozklad cisla %lld je:\n", n);
    for (int i = 2; i <= n_sqrt; i++){
        count = 0;
        if(n % i == 0){
            if(first_iteration == false) printf(" x ");
            while (n % i == 0){
                n = n / i;
                count++;
            }
            if(count != 1) printf("%d^%d", i, count);
            else printf("%d", i);
            first_iteration = false;
        } else continue;
    }
    if(n_origin == n) printf("%lld\n", n);
    else if(n != 1) printf(" x %lld\n", n);
    else printf("\n");
}

在这个函数中:

int ReadInput(int64_t *n, int *ret){
    if(scanf("%lld", n) != 1){
        *n = 0;
        fprintf(stderr, "Error: Chybny vstup!\n");
        *ret = INPUT_ERROR;
    }
    return *n;
}

64 位整数被 return 编辑为 int,然后在 main() 函数中使用它来检查值是否为正。 int 的范围取决于系统,但如果 int 是 32 位(这种情况很常见),那么例如 10^18 将在截断为 32 位后得到值 -1486618624,即负值。因此程序终止,因为来自 ReadInput() 的 returned 值是负数,但它不会打印错误,因为 n(未截断的 64 位整数)是正数。

一个最小的修改是 ReadInput() return 一个 int64_t 而不是 int:

int64_t ReadInput(int64_t *n, int *ret)