Levi
Levi

Reputation: 23

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("\np = %"PRIo32"\n", p);
    printf("q = %"PRIo32"\n", q);
    printf("N = %"PRIo64"\n", 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?

Upvotes: 0

Views: 139

Answers (1)

Arthur Kalliokoski
Arthur Kalliokoski

Reputation: 1647

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

Upvotes: 4

Related Questions