ios – 如何在Objective-C中对真正的大数进行取幂?

前端之家收集整理的这篇文章主要介绍了ios – 如何在Objective-C中对真正的大数进行取幂?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用Objective-C以编程方式计算8位数的结果时遇到了一些麻烦.

取这些数字,例如:16468920 ^ 258,这将导致数字为1862 digits in length.@H_301_3@

我天真地尝试过:@H_301_3@

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

…但结果输出0.@H_301_3@

然后我尝试了:@H_301_3@

long double result = powl(16468920,258);

…但结果输出inf.@H_301_3@

finding out about NSDecimal之后,我尝试了这个:@H_301_3@

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

…但结果输出NaN,所以我试过:@H_301_3@

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

…但此代码引发NSDecimalNumberOverflowException.@H_301_3@

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

解决方法

由于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.@H_301_3@

猜你在找的iOS相关文章