[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
We know that on the 32-bit cpu of x86, int represents 32-bit. If it is calculated as an integer, it is about more than 4 billion. Similarly, if the maximum integer that can be expressed on a 64-bit cpu is a 64-bit binary, the value is much larger. What if I want to represent a large integer in 32-bit format? We can only find a solution on our own.
First, let's review how the addition, subtraction, and multiplication and division of integers are implemented:
(1) Remember the multiplication formula between 9*9
(2) Remember the addition and subtraction between a single bit and a single bit
(3) All multiplication is represented by addition and left shift, and all Subtraction is represented by subtraction and right shift.
After understanding the above principles, we can manually write a large integer addition:
Int * big_int_add (int src1 [], int length1, int src2 [], int leng22)
{
Int * dest = NULL;
Int length;
Int index;
Int smaller;
Int prefix = 0;
If (NULL = src1 | 0> = length1 | NULL = src2 | 0> = leng22)
Return NULL;
Length = length1> leng22? (Length1 + 1): (length1 + 1 );
Dest = (int *) malloc (sizeof (int) * length );
Assert (NULL! = Dest );
Memset (dest, 0, sizeof (int) * length );
Smaller = (length1 <length1 )? Lengh2: length1;
For (index = 0; index <smaller; index ++)
Dest [index] = src1 [index] + src2 [index];
If (length1> length1 ){
For (; index <length1; index ++)
Dest [index] = src1 [index];
} Else {
For (; index <leng2; index ++)
Dest [index] = src2 [index];
}
For (index = 0; index <length; index ++ ){
Dest [index] + = prefix;
Prefix = dest [index]/10;
Dest [index] % = 10;
}
Return dest;
}
Int * big_int_add (int src1 [], int length1, int src2 [], int leng22)
{
Int * dest = NULL;
Int length;
Int index;
Int smaller;
Int prefix = 0;
If (NULL = src1 | 0> = length1 | NULL = src2 | 0> = leng22)
Return NULL;
Length = length1> leng22? (Length1 + 1): (length1 + 1 );
Dest = (int *) malloc (sizeof (int) * length );
Assert (NULL! = Dest );
Memset (dest, 0, sizeof (int) * length );
Smaller = (length1 <length1 )? Lengh2: length1;
For (index = 0; index <smaller; index ++)
Dest [index] = src1 [index] + src2 [index];
If (length1> length1 ){
For (; index <length1; index ++)
Dest [index] = src1 [index];
} Else {
For (; index <leng2; index ++)
Dest [index] = src2 [index];
}
For (index = 0; index <length; index ++ ){
Dest [index] + = prefix;
Prefix = dest [index]/10;
Dest [index] % = 10;
}
Return dest;
} The biggest feature of the above algorithm is that the hexadecimal system is not taken into account during computation. After all the results are obtained, the system starts to process each bit.
Discussion:
After seeing the above algorithm, you can consider:
(1) How should I write subtraction?
(2) What about multiplication? What about division?