Reputation: 503
I'm having some trouble calculating the result of an 8-digit number to the power of a 3-digit number programmatically in Objective-C.
Take these numbers, for instance: 16468920^258
, which should result in a number that is 1862 digits in length.
I naïvely tried:
unsigned long long result = 1;
for (int i = 0; i < 258; i++)
result *= 16468920;
…but result
outputs 0
.
Then I tried:
long double result = powl(16468920, 258);
…but result
outputs inf
.
After finding out about NSDecimal, I tried this:
NSDecimal result;
NSDecimal number = [[NSDecimalNumber decimalNumberWithString:@"16468920"] decimalValue];
NSDecimalPower(&result, &number, 258, NSRoundPlain);
…but result
outputs NaN
, so I tried:
NSDecimalNumber *number = [[NSDecimalNumber alloc] initWithInt:16468920];
NSDecimalNumber *result = [number decimalNumberByRaisingToPower:258];
…but this code raises an NSDecimalNumberOverflowException
.
Any pointers as to which direction I should be going?
Upvotes: 7
Views: 1319
Reputation: 790
You get that issue because your result still bigger that NSDecimalNumber
could store.
I recommend you to could use JKBigInteger instead, it is a Objective-C wrapper around LibTomMath C library. And really easy to use and understand.
Hope this could help.
Upvotes: 0
Reputation: 9310
Since Objective-C is a superset of C, you can use a C library such a BN:
int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BN_CTX *ctx);
BN_exp() raises a to the p-th power and places the result in r ("r=a^p"). This
function is faster than repeated applications of BN_mul().
See, for example, here for how to get openssl into iOS.
Upvotes: 3