maharshi kintada
maharshi kintada

Reputation: 5

How to print a very large value in c

I am newbie, please bear if my question is silly.

int main()
{
  int x=60674;
  printf("%lf \n",(double)(x*x));
  printf("%lld \n",(long long)(x*x));
  return 0;
}

Why is this not working?

Upvotes: 0

Views: 229

Answers (3)

Pankaj Prakash
Pankaj Prakash

Reputation: 2428

x is a signed integer that can hold value only upto -2,147,483,847 to +2,147,483,847 and on performing the operation

    x * x
==> 60674 * 60674 = 3,681,334,276  

which generally overflows the integer range. Hence you might need some big data type to hold that calculation 60674 * 60674

You can try two things to do that.

  1. Change the data type of x from int to long or for more range long long

    long long x = 60674;

  2. Type cast the calculation to long range data type. printf("%lld \n",((long long)x* (long long)x));

Upvotes: 0

nayana
nayana

Reputation: 3932

Additionaly you may use standardised ints:

#include <inttypes.h>
#include <stdio.h>

int main() {
        int x=60674;
        printf("%" PRIu64 "\n",(uint64_t)x * x);
        return 0;
}

Moreover you do not need to cast both variables .. the * will impose using the bigger type of the two multipliers.

Btw you could just use unsigned int .. the result would fit in UINT_MAX which is 4294967295 (from here )

Upvotes: 1

SurvivalMachine
SurvivalMachine

Reputation: 8356

x * x overflows, so you should cast them into long longs before the multiplication:

printf("%lld \n",((long long)x * (long long)x));

Upvotes: 5

Related Questions