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

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

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

我天真地尝试过:

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

…但结果输出0.

然后我尝试了:

long double result = powl(16468920,258);

…但结果输出inf.

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

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

…但结果输出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 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...