Given an integer of 16 digit.I have to print its square using bit operations or any other method in c++.I tried to take the number as a long int but it is not working as the range of the long int is less than the desired input.
Asked
Active
Viewed 2,073 times
-4
-
Try converting it to float: `double d = (double)i`? Then the bit operations will be trickier, but there's plenty of material out there. Otherwise, if you're on gcc you can use [128 bit integers](http://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html). – Jens Mar 29 '14 at 10:47
-
If you need a lot of space you could always use `long long i = d*d` – Max Langerak Mar 29 '14 at 10:49
-
1And if that is still not enough, use two 128b integers and manually carry the bits over from one into the other. Take a look at similar questions here, like [this one](http://stackoverflow.com/questions/193398/multiplication-of-very-long-integers). – Jens Mar 29 '14 at 10:53
-
possible duplicate of [Arbitrary-precision arithmetic Explanation](http://stackoverflow.com/questions/1218149/arbitrary-precision-arithmetic-explanation) – sashoalm Mar 29 '14 at 11:02
-
The square of a 16 digit number can have up to 32-digits. I don't think any built-in type can handle this. – sashoalm Mar 29 '14 at 11:05
-
@sashoalm: Not in C or C++ if you're going with native machine types only. You'd use [big integer](https://mattmccutchen.net/bigint/) implementations though. The link you gave is great! :) – Jens Mar 29 '14 at 11:08
2 Answers
2
You can always choose a bigger primitive data type, but often this will just delay the problem. What should you do once you want to take a square of a long long, really?
If you need really big numbers, you need a more abstract, encapsulated data representation. C++ has the right tools to offer for this job, and the Boost libraries make extensive use of them with Boost.Multiprecision. Specifically, look at the documentation for <boost/multiprecision/cpp_int.hpp>
. It's complicated, but powerful.

Christian Hackl
- 27,051
- 3
- 32
- 62
0
The square is perfectly representable as an unsigned integer (32 bit):
#include <iostream>
#include <cstdint>
int main()
{
std::int32_t s = (std::int32_t(1) << 16) - 1;
std::uint32_t u = std::abs(s);
std::uint32_t square = u * u;
std::cout << square << " = " << std::hex << square << '\n';
return 0;
}
Having a signed integer you will face an overflow and get a negative number.
-
2I don't think he means 16 bit integers. I think he means 16 decimal digits (I'm a bit uncertain here myself). – Jens Mar 29 '14 at 10:59
-
1What is the point of `abs`? What is this signed 16 bit number whose square doesn't fit in an int32_t? – Marc Glisse Mar 29 '14 at 11:11
-