我在使用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.