test: multiplication

This commit is contained in:
2026-04-27 18:48:56 -06:00
parent 5a5a5ffd30
commit ef454ce620

View File

@@ -1,6 +1,6 @@
use std::{fmt, ops};
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Fraction {
num: i64,
den: i64,
@@ -94,6 +94,7 @@ impl ops::Mul for Fraction {
den: self.den * other.den,
};
new.reduce();
new.correct_sign();
new
}
}
@@ -347,4 +348,88 @@ mod tests {
assert_eq!(c.num, 0);
assert_eq!(c.den, 1);
}
#[test]
fn test_mul_basic() {
let a = Fraction::new(2, 3).unwrap();
let b = Fraction::new(3, 4).unwrap();
let c = a * b;
assert_eq!(c.num, 1);
assert_eq!(c.den, 2);
}
#[test]
fn test_mul_with_zero() {
let a = Fraction::new(0, 5).unwrap();
let b = Fraction::new(3, 7).unwrap();
let c = a * b;
assert_eq!(c.num, 0);
assert_eq!(c.den, 1);
}
#[test]
fn test_mul_negative_positive() {
let a = Fraction::new(-2, 3).unwrap();
let b = Fraction::new(3, 5).unwrap();
let c = a * b;
assert_eq!(c.num, -2);
assert_eq!(c.den, 5);
}
#[test]
fn test_mul_negative_negative() {
let a = Fraction::new(-2, 3).unwrap();
let b = Fraction::new(-3, 5).unwrap();
let c = a * b;
assert_eq!(c.num, 2);
assert_eq!(c.den, 5);
}
#[test]
fn test_mul_result_reduced() {
let a = Fraction::new(4, 6).unwrap();
let b = Fraction::new(9, 12).unwrap();
let c = a * b;
assert_eq!(c.num, 1);
assert_eq!(c.den, 2);
}
#[test]
fn test_mul_by_one() {
let a = Fraction::new(5, 7).unwrap();
let b = Fraction::from(1);
let c = a * b;
assert_eq!(c.num, 5);
assert_eq!(c.den, 7);
}
#[test]
fn test_mul_large_numbers() {
let a = Fraction::new(1000, 2000).unwrap();
let b = Fraction::new(3000, 4000).unwrap();
let c = a * b;
assert_eq!(c.num, 3);
assert_eq!(c.den, 8);
}
#[test]
fn test_mul_commutative() {
let a = Fraction::new(7, 9).unwrap();
let b = Fraction::new(2, 5).unwrap();
let c1 = a * b;
let c2 = b * a;
assert_eq!(c1.num, c2.num);
assert_eq!(c1.den, c2.den);
}
#[test]
fn test_mul_with_negative_denominator_input() {
let a = Fraction::new(2, -3).unwrap(); // -2/3
let b = Fraction::new(3, 4).unwrap();
let c = a * b;
assert_eq!(c.num, -1);
assert_eq!(c.den, 2);
}
}