How can I make a 23 decimal integer and then wrap it in NSNumber and then an NSString in objective-c

StackOverflow https://stackoverflow.com/questions/21421339

문제

I want to get 18^18 (23 decimals) into an integer in objective-c, and then into NSNumber and then into NSString.

I can get 15^15 (18 decimals) working as follows

15^15 = 437893890380859375 (18 decimal)

unsigned long long myFirstInt = pow(self.myBottomNumber, self.myTopNumber);
[self.answerButton setTitle:[[NSNumber numberWithUnsignedLongLong:myFirstInt] stringValue]        forState:UIControlStateNormal];
NSLog(@"ull %lld",myFirstInt);

int64_t myFirstInt = pow(self.myBottomNumber, self.myTopNumber);
[self.answerButton setTitle:[[NSNumber numberWithUnsignedLongLong:myFirstInt] stringValue] forState:UIControlStateNormal];
NSLog(@"int64 %lld",myFirstInt);

--

Is there a theorem or algorithm that can pack 20+ decimal numbers into a NSString in objective-c?

16^16 = 18446744073709551616 (20 decimal)

17^17 = 827240261886336764177 (21 decimals)

18^18 = 39346408075296537575424 (23 decimal)

도움이 되었습니까?

해결책

What you want is NSDecimalNumber. It allows you to represent numbers with greater accuracy and range, but with the trade-off that they're slower, take more memory, and can't be manipulated as easily as C-primitive number types.

Example:

NSDecimalNumber *fifteen = [NSDecimalNumber decimalNumberWithString:@"15"];
NSDecimalNumber *result = [fifteen decimalNumberByRaisingToPower:15];
NSString *string = [result stringValue];

More information can be found here: https://developer.apple.com/library/mac/documentation/cocoa/Reference/Foundation/Classes/NSDecimalNumber_Class/Reference/Reference.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top