We know that computers have different data types and can represent varying levels of data, such as:
unsigned int : 0~4294967295
INT : -2147483648~2147483647
unsigned long : 0~4294967295
long: -2147483648~2147483647
long long: -9223372036854775808 ~ 9223372036854775807
unsigned Long Long: 0 ~ 18446744073709551615
__int64: -9223372036854775808 ~ 9223372036854775807
unsigned __int64: 0 ~ 18446744073709551615
The data magnitude used in daily iOS development work does not exceed the above data type, and if it is two large numbers (say, 99999999999999999999999999999999999999 or more digits), how do you calculate it?
Here's my own algorithm for adding two large numbers written in OC:
(the basic idea is to use a string to simulate the process of adding two integers)
//two large number addition algorithm-(NSString *) Addtwonumberwithonenumstr: (NSString *) one anothernumstr: (NSString *) another{inti =0; intj =0; intMaxLength =0; intsum =0; intoverflow =0; intCarrybit =0; NSString*TEMP1 =@""; NSString*TEMP2 =@""; NSString*sums =@""; NSString*tempsum =@""; intLength1 = (int) One.length; intLength2 = (int) Another.length; //1. Invert strings for(i = length1-1; I >=0; i--) {Nsrange range= Nsmakerange (I,1); Temp1=[Temp1 Stringbyappendingstring:[one Substringwithrange:range]; NSLog (@"%@", TEMP1); } for(j = length2-1; J >=0; j--) {Nsrange range= Nsmakerange (J,1); Temp2=[Temp2 stringbyappendingstring:[another Substringwithrange:range]; NSLog (@"%@", TEMP2); } //2. Total missing number of digits is 0MaxLength = length1 > length2?length1:length2; if(MaxLength = =length1) { for(i = length2; i < length1; i++) {Temp2= [Temp2 stringbyappendingstring:@"0"]; NSLog (@"i =%d--%@", I,TEMP2); } }Else{ for(j = length1; J < Length2; J + +) {Temp1= [Temp1 stringbyappendingstring:@"0"]; NSLog (@"j =%d--%@", J,TEMP1); } } //3. Take a number to do the addition for(i =0; i < maxLength; i++) {Nsrange range= Nsmakerange (I,1); intA =[Temp1 Substringwithrange:range].intvalue; intb =[Temp2 Substringwithrange:range].intvalue; Sum= A + B +Carrybit; if(Sum >9) { if(i = = maxLength-1) {Overflow=1; } carrybit=1; Sum-=Ten; }Else{carrybit=0; } tempsum= [TempSum stringbyappendingstring:[nsstring stringWithFormat:@"%d", sum]]; } if(Overflow = =1) {TempSum= [TempSum stringbyappendingstring:@"1"]; } intSumlength = (int) Tempsum.length; for(i = sumlength-1; I >=0; i--) {Nsrange range= Nsmakerange (I,1); Sums=[sums Stringbyappendingstring:[tempsum Substringwithrange:range]; } NSLog (@"sums =%@", sums); returnsums;}
The algorithm may not write very concise, if you have a better writing, welcome in the comment area, the above all the content is the manual, if you need to reprint please indicate the source!
Calculate two large number addition algorithms (OC Implementation) in iOS