0

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?

Levi
  • 23
  • 3
  • Looks like there's a lot of noise int your code. You should be able to post an example without any calls or declarations of `random_prime` and `is_prime` and you could remove most includes. Create a [mre] – klutt Dec 31 '20 at 23:00
  • 1
    Why not `uint64_t p = random_prime();` and set up for the next stage? – tadman Dec 31 '20 at 23:01
  • 1
    `27,545,553,743` can't fit in an `uint32_t`, the max is `4,294,967,295`. It's not clear how you're getting that output, but I'm not familiar with that unusual `printf` notation. Is that just macros? – tadman Dec 31 '20 at 23:09
  • 1
    @tadman It's standard C: ["The fprintf macros for unsigned integers are: ..."](https://port70.net/~nsz/c/c11/n1570.html#7.8.1p3) – Andrew Henle Dec 31 '20 at 23:21
  • @AndrewHenle Wow, never seen it before, so thanks for the link. – tadman Dec 31 '20 at 23:24
  • 1
    @tadman The use of those is quite rare. I suspect they're used more in embedded programming communities, where `int` might not be 32 bits. – Andrew Henle Dec 31 '20 at 23:25

1 Answers1

4

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

Arthur Kalliokoski
  • 1,627
  • 12
  • 12