0
#include<stdio.h>
#include<stdlib.h>
int main()
{
    long long int n;
    char c[200];
    scanf("%lld",&n);
    itoa(n*n*n*n,c,10);
    printf("%s",c);

}

input: 90625

output: -1726117887

basically, my code is calculating n^4 and converting it into a string. but the problem is I am not able to do so for bigger numbers. please resolve my issue.

dreamlax
  • 93,976
  • 29
  • 161
  • 209
Yash Gupta
  • 19
  • 4
  • 1
    67451572418212890625 is too big to fit in a 64-bit int. You need [bignums](https://stackoverflow.com/questions/45527972/big-numbers-in-c). – tadman Mar 20 '21 at 05:45
  • The `itoa()` call is completely pointless here. You're using `printf` which already has this conversion capability: `printf("%lld", n*n*n*n)` – tadman Mar 20 '21 at 05:46
  • It's not possible in this way, it won't fit in a long long int, better is to make a char[200] and fill it manually. You can do a loop for three times multiplication each time taking an input as a char[] and a long long int and returning a char[]. – TheSYNcoder Mar 20 '21 at 05:48
  • 1
    Consider using libraries like http://gmplib.org/ but be aware that C is not the same as C++. Read [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) -or a newer C standard- and [n3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) or a newer C++ standard. See [this website](https://en.cppreference.com/w/) – Basile Starynkevitch Mar 20 '21 at 05:59
  • Calculate `4*log(90625)/log(2)` (in any base of logarithms) and the result is about `65.9`. That means you need a minimum of a 66 bit integral type to be able to represent `90625` to the fourth power. A `long long int` is only guaranteed to be (no smaller than) a 64-bit type, and includes a sign bit, so cannot represent a value that needs to be represented using a 66-bit type. You'll need to find (or roll your own) a library to handle such values. Incidentally, `n*n*n*n` can be done with exactly two multiplications (no need for 4) if you use a type that can represent sufficiently large values – Peter Mar 20 '21 at 06:05

1 Answers1

2

There are many problems:

  • itoa is for integer, you are trying to call a function that returns an integer with a value that exceeds (overflow) INT_MAX, as (90625^4) is way bigger than the maximum value that can fit into an int.

  • If you check the value of unsigned long long, 18446744073709551615, you will see that you are short of only one more power of 10 (0.27348130536 if divided by 90625^4). Your best bet is to use a library that can handle such number, you can use the one suggested by tadman: big num

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81