如何在Objective-C中对非常大的数进行取幂?

时间:2013-06-25 02:28:23

标签: ios objective-c math

我在使用Objective-C以编程方式计算8位数字的结果时遇到了一些麻烦。

取这些数字,例如: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


关于我应该去哪个方向的任何指示?

2 个答案:

答案 0 :(得分: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 :(得分:0)

您遇到了这个问题,因为NSDecimalNumber可以存储的结果更大。

我建议您使用JKBigInteger代替它,它是LibTomMath C库的Objective-C包装器。并且非常易于使用和理解。

希望这可以提供帮助。