cargumentsconstantsmaxunsigned-long-long-int

warning: integer constant is too large for its type


how to find the correct type for largest number ?

#include <stdio.h>
/**
 * factor_prime - prints the prime factors of a number
 * @n: number
 */

void factor_prime(unsigned long long n)
{
    long i;
    long inter = n;

    printf("n : %lld\n", n);
    for (i  = 2; i <= n; i++)
    {
        if (n % i == 0)
        {
            n = n / i;
            printf("%ld=%lld*%ld\n", inter, n, i);
            return;
        }
    }
}

int main(void)
{
    factor_prime(1718944270642558716715u);
}

output : 3397071787570416427=35568825191561*95507

expected : 1718944270642558716715=343788854128511743343*5

how to fix ?


Solution

  • You are using a too big integer constant that can not be represented in any object of an integer type.

    Consider this demonstration program.

    #include <stdio.h>

    #include <limits.h>
    #include <inttypes.h>
    
    int main( void )
    {
        printf( "%llu\n", ULLONG_MAX );
        printf( "%" PRIuMAX "\n", UINTMAX_MAX );
    }
    

    Its output is

    18446744073709551615
    18446744073709551615
    

    The outputted constant contains only 20 digits while your constant 1718944270642558716715u that you are trying to use contains 22 digits.

    Pay attention to that in any case your function is incorrect. The function parameter has the type unsigned long long that you are assigning to a variable of the signed type long

    void factor_prime(unsigned long long n)
    {
        long i;
        long inter = n;
        //...
    

    As you are trying to pass a very big number then the assignment results in getting an invalid value.