WhatsInAName
WhatsInAName

Reputation: 969

What kind of datatype will hold 3000000^2 in C++?

What will hold something like 3000000^2 without overflow?

Upvotes: 1

Views: 385

Answers (4)

juanchopanza
juanchopanza

Reputation: 227618

You can check with std::numeric_limits. In c++11, long long is a standard integer of at least 64 bits, so, for example, unsigned long long has these limits:

#include <iostream>
#include <limits>


int main() {
  std::cout << "sizeof : " << sizeof(unsigned long long) << "\n"; 
  std::cout << "min    : "<< std::numeric_limits<unsigned long long>::min() << "\n";
  std::cout << "max    : "<< std::numeric_limits<unsigned long long>::max() << "\n\n";
}

producing on my platform:

sizeof : 8
min    : 0
max    : 18446744073709551615

C++ provides various integer types, but as far as I know the 64 bit types were not mandated by the standard pre-c++11. I long long is the only standard integer to be at least 64 bits, so you would need a compiler with c++11 support. But it could be that your compiler supports some other non-standard 64 bit type.

Upvotes: 2

Michael Slade
Michael Slade

Reputation: 13877

When you say "something like", it suggests that you are not actually sure how large the number is that you want to store.

Take a look here (say), and see which numeric type is best for your application.

Note that there is on 64-bit integer in that list; that's because it's not quite available everywhere.

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181097

3000000^2 is less than 2^48, so an uint64_t from cstdint or stdint.h will hold your number with good margin.

Upvotes: 5

unsym
unsym

Reputation: 2200

The 64 bit integer:

long long int

Upvotes: 2

Related Questions