fn main() {
let a = 17;
let b = 29;
let m = 10;
let result = (a + b) % m;
println!("{}", result);
}The sum is 17 + 29 = 46. Taking 46 modulo 10 gives 6 because 46 divided by 10 leaves a remainder of 6.
fn main() {
let x = 7;
let y = 8;
let m = 12;
let result = (x * y) % m;
println!("{}", result);
}7 * 8 = 56. 56 % 12 = 8 because 12 * 4 = 48 and 56 - 48 = 8.
fn main() {
let base = 3u64;
let exponent = 4u64;
let modulus = 5u64;
let mut result = 1u64;
for _ in 0..exponent {
result = (result * base) % modulus;
}
println!("{}", result);
}3^1 mod 5 = 3
3^2 mod 5 = 9 mod 5 = 4
3^3 mod 5 = 4 * 3 = 12 mod 5 = 2
3^4 mod 5 = 2 * 3 = 6 mod 5 = 1
But the code multiplies 4 times starting from 1, so final result is 1.
Re-check the loop: result starts at 1, multiply by 3 mod 5 four times:
Iteration 1: 1*3=3 mod5=3
Iteration 2: 3*3=9 mod5=4
Iteration 3: 4*3=12 mod5=2
Iteration 4: 2*3=6 mod5=1
Final result is 1.
fn mod_inverse(a: i64, m: i64) -> i64 {
let mut m0 = m;
let mut y = 0;
let mut x = 1;
let mut a = a;
if m == 1 {
return 0;
}
while a > 1 {
let q = a / m0;
let mut t = m0;
m0 = a % m0;
a = t;
t = y;
y = x - q * y;
x = t;
}
if x < 0 {
x += m;
}
x
}
fn main() {
println!("{}", mod_inverse(3, 11));
}The code correctly computes the modular inverse of 3 modulo 11 using the Extended Euclidean Algorithm. The inverse is 4 because 3 * 4 = 12 ≡ 1 (mod 11). No error occurs for coprime inputs like these.
Addition and multiplication distribute over modulo, but subtraction can cause negative results and division is not generally defined in modular arithmetic without modular inverse.
