Basic Modular Operations
In this section, we will cover the fundamental operations in modular arithmetic. These operations are essential for performing calculations within a specified modulus.
Functions Overview
-
modulo(a: number, b: number): numberComputes the remainder whenais divided byb. -
modAdd(a: number, b: number, mod: number): numberAdds two numbers modulomod. -
modSubtract(a: number, b: number, mod: number): numberSubtracts two numbers modulomod. -
modMultiply(a: number, b: number, mod: number): numberMultiplies two numbers modulomod. -
modDivide(a: number, b: number, mod: number): numberDividesabybmodulomod. This operation requires the modular multiplicative inverse ofb.
Parameters
- a: The first number (or array of numbers) to operate on.
- b: The second number (or array of numbers) to operate with (if applicable).
- mod: The modulus to apply for the operation.
Return Value
Each function returns a number representing the result of the modular operation.
Examples
modulo
console.log(modulo(10, 3)); // Output: 1
modAdd
console.log(modAdd(5, 7, 6)); // Output: 0 (since (5 + 7) % 6 = 0)
modSubtract
console.log(modSubtract(7, 5, 6)); // Output: 2 (since (7 - 5) % 6 = 2)
modMultiply
console.log(modMultiply(5, 7, 6)); // Output: 5 (since (5 * 7) % 6 = 5)
modDivide
console.log(modDivide(4, 3, 5)); // Output: 3 (since 4 * 3^-1 mod 5 = 3)
Error Handling
Division by Zero: If a division by zero is attempted during modDivide, an error is thrown.
console.log(modDivide(4, 0, 5)); // Throws: "Division by zero is not allowed."
Invalid Inputs: If inputs are not numbers, an error is thrown.
console.log(modAdd("5", 7, 6)); // Throws: "Invalid input: must be a number."
Advanced Use Cases
Chaining with Other Operations
You can combine these modular operations with other arithmetic operations for complex calculations.
const result = new Chain(10)
.add(modulo(10, 3)) // Adds the result of modulo operation
.subtract(2)
.getResult();
console.log(result); // Output: 9
Notes
- Ensure the modulus (
mod) is always positive and non-zero for valid results. - For
modDivide, ensure that the divisor has a modular multiplicative inverse under the given modulus.