简体   繁体   中英

long and int not enough and double wouldn't work

I am using C++ and I've heard and experienced that the maximum value that can be stored in a int and a long are same.

But my problem is that I need to store a number that exceed the maximum value of long variable. The size of double variable is pretty enough.

But the problem is using double variable avoid me using the operator % which is necessary to code my function more easily and some times there seems to be no other ways than using it.

So please would you kindly tell me a way to achieve my target?

It depends on the purpose. For a better answer, give us more context

Have a look at (unsigned) long long or GMP

You can use type long long int or unsigned long long int

To know the maximum value that an untegral type can contain you can use the following construction as for example

std::numeric_limits<long long>::max();

To use it you have to include header <limits>

So, you want to compute the modulo of large integers. It's 99% likely you're doing encryption, which is hard stuff. Your question kind of implies that maybe you should look for some off-the-shelf solution for your top-level problem (the encryption).

Anyway, the standard answer is otherwise to use a library for large-precision integers, such as GNU MP .

#include <cmath>

int main ()
{
    double max_uint = 4294967295.0;
    double max1 = max_uint + 2.0;
    double max2 = (max1 + 1.0) * (max_uint + 1.0);
    double f = fmod(max2,max1);

    return 0;
}

max1 and max2 are both over unsigned int limit, and fmod returns correct max2 % max1 result, which is also over unsigned int limit: f == max_uint + 1.0 .

Edit:

good hint from anatolyg: this method works only for integers up to 2^52. This is because mantissa of double has 52 bit, and every higher integer is representable only with precision loss. Eg 2^80 could be == (2^80)+1 and == (2^80)+2 and so on. The higher the integers, the higher the inprecision, because densitiy of representable integers gets wider there.

But if you just need to have 20 extra bit compared to int with 32 bit, and have no other possibility to achieve this with an built-in integral type (with which the regular % will be faster I think), then you can use this...

first there's a difference between int and long type

but for To fix the your problem you can use

unsigned long long int

here is a list of some of the sizes you would expect in C++:

char      : 1 byte
short     : 2 bytes
int       : 4 bytes
long      : 4 bytes
long long : 8 bytes

float  : 4 bytes
double : 8 bytes 

I think this clearly explains why you are experiencing difficulties and gives you a hint on how to solve them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM