Search code examples
cintmodulusnegative-numberint128

C modulus returning negative number


I have data type unsigned __int128 data; so I don't think this is a type issue, but I have no idea why it is occuring

#include <stdio.h>

int main(int argc, char *argv[]) {
    unsigned __int128 z = 1911602146;
    unsigned __int128 n = 4003562209;

    //case 1
        unsigned __int128 result = fmod((pow(z, 2)  * 2), n);
        printf("%d\n", result);

    //case 2
        unsigned __int128 result_2 = fmod(pow(z, 2), n);
        printf("%d\n", result_2);
}

returns:

-669207835 => this is the correct option and it should be 7629321670
-480306461

Solution

  • First avoid the floating-point trip during the calculation.
    Then, only for printing, convert the result (which is < 10^10) to double in order to use the printf function

    unsigned __int128 z = 1911602146;
    unsigned __int128 n = 4003562209;
    
    unsigned __int128 result = (z * z * 2) % n;
    printf("%.0lf\n", (double)result);
    
    unsigned __int128 result_2 = (z * z) % n;
    printf("%.0lf\n", (double)result_2);
    

    That should give you

    3625759213
    3814660711
    

    (you cannot get 7629321670 anyway as a result, since it is bigger than the modulo operand, 'n')