Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exponentiate really large numbers in Objective-C?

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?

like image 306
gomollon Avatar asked Jun 25 '13 02:06

gomollon


1 Answers

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.

like image 73
sjs Avatar answered Oct 16 '22 07:10

sjs