Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c - Multiplying two large numbers gives the wrong result

I'm getting the wrong results when multiplying p*q in the below code:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <time.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <math.h>

uint32_t random_prime(void);
bool is_prime(uint32_t);

int main(void) {
    
    srand((unsigned int) time(NULL));
    uint32_t p = random_prime();
    uint32_t q = random_prime();
    while (p == q) {
        q = random_prime();
    }
    uint64_t N = (uint64_t) p * q;

    printf("
p = %"PRIo32"
", p);
    printf("q = %"PRIo32"
", q);
    printf("N = %"PRIo64"
", N);
}

Here is the output I'm getting:

p = 27545553743
q = 24276636245
N = 742634106633630654517

It's obviously the wrong result. I don't think it could be an overflow issue, since a uint64_t should be able to hold any results from two uint32_t. The max value of a uint32_t is 4294967295. 4294967295^2 = 18446744065119617025. The max value of a uint64_t is 18446744073709551615, which is larger. I have no idea why my output could be wrong. Help?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

N is the right result, since you're printing all the numbers in octal, not base 10.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...