Home > Mobile >  warning: integer constant is too large for its type
warning: integer constant is too large for its type

Time:06-27

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 ?

CodePudding user response:

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.

CodePudding user response:

The problem with your code is that you're passing a value i.e. 1718944270642558716715u which is out of range for the unsigned long long numeric limit.

You can check the numeric limit of a type using:

  • For c
std::numeric_limits<unsigned long long>::max() // 18446744073709551615
  • For C
#include <stdio.h>
#include <limits.h>

int main(void)
{   
    printf("%llu", ULONG_LONG_MAX); // 18446744073709551615
}   

CodePudding user response:

when you code a function that you want to work for any type of variable try to use the largest variable size. In your case try long long or decimal.

  • Related