Search code examples
cvariablestypesmultiplication

C: two integers multiply to negative value (overflow shouldn't happen yet)


I am learning C at the moment and we got a pretty simple matrix multiplication exercise that seems to work well for most test cases. However, one case doesn't work and I already narrowed it down to this piece of code that doesn't produce the expected result:

#include <stdio.h>

int main(){
    int a1 = 1261373;
    int b1 = 1261373;
    int a2 = 1669717;
    int b2 = 1293027;
    long mult1 = a1*b1;
    long mult2 = a2*b2;
    printf("mult1=%ld , mult2=%ld", mult1, mult2);
}

The output I get is:

mult1=1923945609 , mult2=-1379386529

Instead of the expected:

mult1=1591061845129, mult2=2158989163359

Obviously, especially with the second result I thought of an overflow first. But that really shouldn't happen with such small numbers, should it? The input is definetly an integer (we can't change that) and the output should be a long so I can't change the data types and I have no idea how it gets a negative number for the second multiplication or why the first result is wrong.

Any help would be greatly appreciated!


Solution

  • Try this one

    #include <stdio.h>
    
    int main(){
        int a1 = 1261373;
        int b1 = 1261373;
        int a2 = 1669717;
        int b2 = 1293027;
        long mult1 = (long long)a1*b1; //Type cast one operand to long long
        long mult2 = (long long)a2*b2;
        printf("mult1=%ld , mult2=%ld", mult1, mult2);
    }