Skip to content

Commit

Permalink
Euclid (Simon) (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tristan-H11 authored Apr 6, 2024
2 parents 72a0012 + 57fad56 commit a295b45
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions src/math_core/complex_number.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use bigdecimal::num_bigint::BigInt;
use bigdecimal::{Signed, Zero};
use std::cmp::Ordering;
use bigdecimal::{BigDecimal, Signed, Zero};
use std::ops::{Add, Div, Mul, Sub};
use bigdecimal::num_bigint::ToBigInt;
use bigdecimal::num_traits::Euclid;
use num::BigInt;
use sha2::digest::typenum::private::IsGreaterOrEqualPrivate;

#[derive(Clone, Debug, PartialEq)]
pub struct ComplexNumber {
Expand Down Expand Up @@ -29,18 +33,46 @@ impl ComplexNumber {
self.real.is_negative() && self.imaginary.is_negative()
}

pub fn absolute_value(&self) -> Option<BigDecimal>{
BigDecimal::from(&self.real * &self.real + &self.imaginary * &self.imaginary).sqrt()
}

pub fn is_greater_than(&self, other: &Self) -> bool{
self.absolute_value() > other.absolute_value()
}

pub fn is_less_than(&self, other: &Self) -> bool{
self.absolute_value() < other.absolute_value()
}

pub fn is_zero(&self) -> bool {
self.real.is_zero() && self.imaginary.is_zero()
}

pub fn div_round(&self, rhs: &Self) -> Self {
Self{
real: (BigDecimal::from(&self.real * &rhs.real + &self.imaginary * &rhs.imaginary) /
BigDecimal::from(&rhs.real * &rhs.real + &rhs.imaginary * &rhs.imaginary)).round(0).to_bigint().unwrap(),
imaginary: (BigDecimal::from(&self.imaginary * &rhs.real - &self.real * &rhs.imaginary) /
BigDecimal::from(&rhs.real * &rhs.real + &rhs.imaginary * &rhs.imaginary)).round(0).to_bigint().unwrap()
}
}
}

pub fn complex_euclidean_algorithm(a: ComplexNumber, b: ComplexNumber) -> ComplexNumber {
let mut g = a;
let mut g_prev = b;
let mut g:ComplexNumber;
let mut g_prev:ComplexNumber;
if a.is_greater_than(&b){
g = b;
g_prev = a;
} else {
g = a;
g_prev = b;
}

while !g.is_zero() {
let tmp = g.clone();
g = &g_prev - &(&g * &(&g_prev / &g));
g = &g_prev - &(&g * &(&g_prev.div_round(&g)));
g_prev = tmp.clone();
}
ComplexNumber {
Expand Down Expand Up @@ -143,6 +175,7 @@ impl Div for &ComplexNumber {

#[cfg(test)]
mod tests {
use num::Integer;
use super::*;

#[test]
Expand All @@ -155,6 +188,7 @@ mod tests {
real: BigInt::from(3),
imaginary: BigInt::from(4),
};

assert_eq!(complex_euclidean_algorithm(y.clone(), x.clone()), y);
assert_eq!(complex_euclidean_algorithm(x.clone(), y.clone()), y);
}
Expand Down

0 comments on commit a295b45

Please sign in to comment.