Ahmed Magdy
Ahmed Magdy

Reputation: 25

Setting one's own type limits in C?

Can I set my own limits for data types in C? I'm solving some problem which involves some mega-great numbers, and I wish to perform many additions and multiplications and to take the final result modulo some desired number, say 1537849. So I wonder if it's possible to reset the limits of data types such that the values are automatically taken modulo the number I wish when the outcome of any of the operations exceeds my specified number, just as the processor normally does but with the limits I wish. And if such a thing isn't possible, what is the most efficient way to negotiate such a problem?

edit:

Consider one would want to calculate (2^1000) % 1537849 and place the result in the variable monster. Below is my attempt to conquer the problem:

uint64_t monster = 1;
uint32_t power = 1000;
for (uint32_t i = 0; i < power; i ++ ) {
    monster *= 2;
    if (i%64==63) monster %= 1537849;
}
monster %= 1537849;

Is there any better way of doing so (different algorithm, using libraries, whatever ...)??

Upvotes: 1

Views: 176

Answers (2)

chux
chux

Reputation: 154280

Can I set my own limits for data types in C?

The limits of basic types are fixed per the compiler.

I wish to perform many additions and multiplications and to take the final result modulo some desired number, say 1537849

At any stage in the addition and multiplication, code can repeatedly perform the modulo. If the original numbers are N-bit, than at most N-bit math is needed - although it is easier to do with 2N-bit math. Unlimited wide math is inefficient and not needed for this task.

Example code for +, * and pow() with modulo limitations:
Modular exponentiation without range restriction

uintmax_t addmodmax(uintmax_t a, uintmax_t b, uintmax_t mod);
uintmax_t mulmodmax(uintmax_t a, uintmax_t b, uintmax_t mod);
uintmax_t powmodmax(uintmax_t x, uintmax_t expo, uintmax_t mod);

Upvotes: 3

user2371524
user2371524

Reputation:

Can I set my own limits for data types in C?

No, short of writing your own compiler and libraries.

I'm solving some problem which involves some mega-great numbers which easily exceed the types' limits

There are algorithms for handling huge numbers in parts ... and there are libraries that already do the work for you, e.g. have a look at the GNU multi precision arithmetic library (GMP).

Upvotes: 3

Related Questions