ios - 如何在 Objective-C 中对非常大的数字求幂?

标签 ios objective-c math

我在 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/

相关文章:

math - LUA中的正态分布曲线和随机数

c++ - 寻求有关 FFT 模板的帮助

ios - 在 Xcode 中将项目锁定为纵向?

ios - UIWebView无法加载(错误-999)

ios - 添加导航 Controller 可防止在 Root View Controller 中调用 updateViewConstraints

javascript - 如何编写一个 JavaScript 函数来调用另一个作为参数传递的函数?

ios - 如何获取AWS SNS发送的通知记录?

ios - Swift - tableView Cell 中的 ImageView 在向下滚动后向上滚动时消失

ios - Alamofire fire 变量类型没有下标成员

ios - 在模型层过滤 NSFetchedResultsController