2013-06-25 71 views
7

我在Objective-C中以編程方式計算一個8位數字的結果與3位數字的結果有些麻煩。如何在Objective-C中取冪非常大的數字?

取這些數字,例如:16468920^258,這應導致一個數字是1862 digits in length


我天真的嘗試:

unsigned long long result = 1; 
for (int i = 0; i < 258; i++) 
    result *= 16468920; 

...但result輸出0


然後我嘗試:

long double result = powl(16468920, 258); 

...但result輸出inf


finding out about NSDecimal之後,我嘗試這樣做:

NSDecimal result; 
NSDecimal number = [[NSDecimalNumber decimalNumberWithString:@"16468920"] decimalValue]; 
NSDecimalPower(&result, &number, 258, NSRoundPlain); 

...但result輸出NaN,所以我嘗試:

NSDecimalNumber *number = [[NSDecimalNumber alloc] initWithInt:16468920]; 
NSDecimalNumber *result = [number decimalNumberByRaisingToPower:258]; 

...但是這個代碼引發NSDecimalNumberOverflowException


任何指針,以我應該走哪個方向?

+0

您將不得不使用這裏提到的一個庫 - > http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic,因爲將該數字存儲爲一個普通的二進制數字意味着上帝只知道有多少位 – borrrden

+3

你需要考慮一旦你得到它,你可以用這個號碼做些什麼。 (粗略5610位,BTW或701字節)。 –

回答

3

由於Objective-C的是C的超集,你可以用一個C庫這樣的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(). 

見,例如,對於here如何讓OpenSSL的進入的iOS。

+1

完美!這似乎已經成功了!我使用[OpenSSL for iOS](https://github.com/st3fan/ios-openssl)以及[OpenSSL的BigNumber數學函數包裝器](https://github.com/davedelong/CHMath)到將結果輸出爲'NSString'! – gomollon

0

你得到這個問題是因爲你的結果仍然大於NSDecimalNumber可以存儲的結果。

我建議您可以使用JKBigInteger來代替它,它是一個圍繞LibTomMath C庫的Objective-C包裝器。而且非常易於使用和理解。

希望這可以幫助。