MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / binary_mod_multiply

Function binary_mod_multiply

maths/binary_multiplication.py:61–95  ·  view source on GitHub ↗

Calculate (a * b) % c using binary multiplication and modular arithmetic. Parameters: a (int): The first number. b (int): The second number. modulus (int): The modulus. Returns: int: (a * b) % modulus. Examples: >>> binary_mod_multiply(2, 3, 5) 1 >>> b

(a: int, b: int, modulus: int)

Source from the content-addressed store, hash-verified

59
60
61def binary_mod_multiply(a: int, b: int, modulus: int) -> int:
62 """
63 Calculate (a * b) % c using binary multiplication and modular arithmetic.
64
65 Parameters:
66 a (int): The first number.
67 b (int): The second number.
68 modulus (int): The modulus.
69
70 Returns:
71 int: (a * b) % modulus.
72
73 Examples:
74 >>> binary_mod_multiply(2, 3, 5)
75 1
76 >>> binary_mod_multiply(5, 0, 7)
77 0
78 >>> binary_mod_multiply(3, 4, 6)
79 0
80 >>> binary_mod_multiply(10, 5, 13)
81 11
82 >>> binary_mod_multiply(2, 1, 5)
83 2
84 >>> binary_mod_multiply(1, 10, 3)
85 1
86 """
87 res = 0
88 while b > 0:
89 if b & 1:
90 res = ((res % modulus) + (a % modulus)) % modulus
91
92 a += a
93 b >>= 1
94
95 return res
96
97
98if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected