Calculation Method of a * B mod C
Method 1:
Everyone can think of it. Calculate the value of a * B and then calculate the value of a * B mod C. This is the simplest, but there is a drawback: the value of a * B cannot be too large and may overflow.
Method 2:
Review the knowledge of hexadecimal conversion. Binary Conversion to hexadecimal can be added with the weight of 2 (which seems to be described in this way ). For example, 13 = (1101) 2 = 1*2 ^ 3 + 1*2 ^ 2 + 0*2 ^ 1 + 1*2 ^ 0. Similarly, when we calculate a * B, we can also convert B to the formula of adding 2 ^ n. Therefore, we can convert a * B mod C to [A * (2 ^ b0 + 2 ^ B1 + ...... 2 ^ bn)] mod c = [A * 2 ^ b0 + A * 2 ^ B1 + ...... A * 2 ^ bn] mod C. The formula (a + B) mod c = [(a mod c) + (B mod C)] mod C is used for calculation.
Code:
Int MUL (int A, int B, int C)
{
Int result, TMP;
TMP = A % C;
While (B)
{
If (B & 1) // determine whether to add a * 2 ^ n based on the value of 2 binary digits, because a right shift operation is performed on B, therefore, you only need to judge the last result each time.
{
Result + = TMP;
If (result> = C)
Result-= C;
}
TMP <= 1; // calculate the value of a * 2 ^ n.
If (TMP> = C)
TMP-= C;
B> = 1;
}
Return result;
}
Method 3:
Multiplication can be calculated as follows: a * B = (A & 1) * B + [(A> 1) * B] <1. At the same time, there is a formula: (a + B) mod c = [(a mod c) + (B mod C)] mod C
Unsigned long MUL (unsigned long a, unsigned long B, unsigned long C)
{
Unsigned long int a1 = A, B1 = B, C1 = C;
If (! A1)
Return 0;
Return (A1 & 1) * B1) % C1 + (MUL (A1> 1, B1, C1) <1) % C1) % C1;
}