2013-06-25 69 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包装器。而且非常易于使用和理解。

希望这可以帮助。