Modular Arithmetic
Modular Arithmetic
Modular Arithmetic is a system of arithmetic for integers where numbers wrap around after reaching a certain value called the modulus. It is a crucial concept in various fields, especially in cryptography and number theory.
Core Conceptsโ
Modulusโ
- The modulus is the integer at which numbers wrap around.
- For any integer , the expression gives the remainder of the division of by .
Basic Operationsโ
-
Addition :
Example:Code:
C++โ
int modular_add(int a, int b, int m) {
return (a + b) % m;
}Javaโ
public static int modularAdd(int a, int b, int m) {
return (a + b) % m;
}Pythonโ
def modular_add(a, b, m):
return (a + b) % mTime Complexity: โ
-
Subtraction :
Example:Code:
C++โ
int modular_sub(int a, int b, int m) {
return (a - b + m) % m; // ensure non-negative result
}Javaโ
public static int modularSub(int a, int b, int m) {
return (a - b + m) % m; // ensure non-negative result
}Pythonโ
def modular_sub(a, b, m):
return (a - b + m) % m # ensure non-negative resultTime Complexity: โ
-
Multiplication::
Example:Code:
C++โ
int modular_mul(int a, int b, int m) {
return (a * b) % m;
}Javaโ
public static int modularMul(int a, int b, int m) {
return (a * b) % m;
}Pythonโ
def modular_mul(a, b, m):
return (a * b) % mTime Complexity: โ
-
Exponentiation:
Example:Code:
C++โ
int modular_pow(int base, int exp, int mod) {
int result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 == 1) {
result = (result * base) % mod;
}
exp = exp >> 1; // equivalent to exp //= 2
base = (base * base) % mod;
}
return result;
}Javaโ
public static int modularPow(int base, int exp, int mod) {
int result = 1;
base = base % mod;
while (exp > 0) {
if ((exp & 1) == 1) {
result = (result * base) % mod;
}
exp >>= 1; // equivalent to exp /= 2
base = (base * base) % mod;
}
return result;
}Pythonโ
def modular_pow(base, exp, mod):
result = 1
base = base % mod
while exp > 0:
if (exp % 2) == 1:
result = (result * base) % mod
exp //= 2
base = (base * base) % mod
return resultTime Complexity: โ
Conclusionโ
Modular arithmetic is a powerful tool in mathematics with significant applications in cryptography, computer science, and number theory. Understanding its core operations and properties is essential for working with modern cryptographic systems and algorithms.
Telemetry Integration
Completed working through this block? Sync progress to workspace.