我在 Objective-C 中以编程方式计算 8 位数字的 3 位数字次方的结果时遇到了一些问题。
以这些数字为例: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
。
关于我应该去哪个方向的任何指示?
最佳答案
由于 Objective-C 是 C 的超集,您可以使用 BN 这样的 C 库:
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。
关于ios - 如何在 Objective-C 中对非常大的数字求幂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17288187/