2

If I wanted to do arithmetic with values greater than 2^32 and did not want to use long's, how would I do that?

I can think of a scheme where I implement numbers (to whatever number of bits I wish) by using multiple variables to implement a single number:

int upper32;  
int lower32;

The above 2 variables can represent a 2^64 bit value (if lower 32 overflows, I increment upper32 by one. This would require some overhead.

What are some better implementations?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Minh Tran
  • 494
  • 7
  • 17
  • the largest 32 bit integer is actually `(2^31)-1` – Ryan May 04 '15 at 01:54
  • Since this is tagged [tag:c], try http://gmplib.org – Greg Hewgill May 04 '15 at 01:55
  • 3
    Are you asking for libraries or algorithms for how you would implement this yourself? – merlin2011 May 04 '15 at 01:56
  • 1
    It's worth pointing out that `lower32` should actually be an unsigned int. – Degustaf May 04 '15 at 02:02
  • If you are going to use your mentioned method, it may be better to declare them as `int32_t` or `uint32_t` instead of `int` or `unsigned int`. – user12205 May 04 '15 at 02:50
  • Merlin, I'm unaware of how solve this problem so both! – Minh Tran May 04 '15 at 04:44
  • for operations like `+,-,++,--,` use carry ... [32 bit ALU in C++](http://stackoverflow.com/a/26603589/2521214) just get rid of the class structure and rewrite it to `C` format. now you can use this as a 32 bit module for any count of values ... if you need also higher operations like `*,/,...` then either implement them via polynomial operations with digit base insted of `x^i` or use any bigint library see [fast bignum sqr](http://stackoverflow.com/q/18465326/2521214) – Spektre May 04 '15 at 07:07
  • I've written a library to handle currency exactly not a double approximation. It has a sign portion and a nibble per digit. + - were easy, * a little harder and / % were pretty much brute force. The max dimensional of a number set at compile time. – phil May 04 '15 at 07:54

1 Answers1

1

If you want to deal with integers that are not larger than 2^64, then you can use long long or unsigned long long, which are 64 bit integers.

If you want to do arithmetics with larger numbers, take a look at gmp library, or write your own multiple precision arithmetic library (it's very simple).

Also, take a look at this