最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Incorrect results with gmp's mpz_mul function for very large numbers - Stack Overflow

programmeradmin0浏览0评论

While developing a program that needs to handle very large integers I stumbled over a bug, and created this simplified version of it. Basically when multiplying two very large numbers, the result is much smaller than it should be.

I already compiled gmp myself, made sure its compiled in 64 bit, tried different versions (including 6.3), all give me the same result.

# ./testcase 24000000000
Fac 1 28898879585 digits
Fac 2 36123599480 digits
Result has 17418344498 digits  (much too small)

However, with smaller inputs, the result is correct:

# ./testcase 14000000000
Fac 1 16857679758 digits
Fac 2 21072099697 digits
Result has 37929779454 digits

This is the code I used:

#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    if(argc != 2) {
        fprintf(stderr, "Exp not given\n");
        return 1;
    }
    unsigned long exp = atoll(argv[1]);

    mpz_t a, b, result;

    mpz_init(a);
    mpz_init(b);
    mpz_init(result);
    
    mpz_set_ui(a, 16);
    mpz_set_ui(b, 32);

    // Generate very large numbers
    mpz_pow_ui(a, a, exp);
    printf("Fac 1 %lu digits\n", mpz_sizeinbase(a, 10));
    mpz_pow_ui(b, b, exp);
    printf("Fac 2 %lu digits\n", mpz_sizeinbase(b, 10));
    
    mpz_mul(result, a, b);
    
    printf("Result has %lu digits\n", mpz_sizeinbase(result, 10));

    mpz_clear(a);
    mpz_clear(b);
    mpz_clear(result);
}

Can someone tell me what is my mistake here?

发布评论

评论列表(0)

  1. 暂无评论