From cb0bc911a4cffdd6b4af35e64a6e6f6d93e53625 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Sun, 28 May 2023 00:09:46 +0200 Subject: [PATCH] gyllois python interface --- src/lib.rs | 1 + src/math/gallois.rs | 5 +++++ src/math/gcd.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 79112f5..0b2fc5b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,6 +54,7 @@ fn register_math_module(py: Python, parent_module: &PyModule) -> PyResult<()> { math_module.add_function(wrap_pyfunction!(math::pm1::py_p_minus_one, math_module)?)?; math_module.add_function(wrap_pyfunction!(math::gcd::gcd, math_module)?)?; math_module.add_function(wrap_pyfunction!(math::gcd::egcd, math_module)?)?; + math_module.add_function(wrap_pyfunction!(math::gcd::alt_egcd, math_module)?)?; math_module.add_function(wrap_pyfunction!(math::factorise::prime_factors , math_module)?)?; math_module.add_class::()?; parent_module.add_submodule(math_module)?; diff --git a/src/math/gallois.rs b/src/math/gallois.rs index 374894d..4539866 100644 --- a/src/math/gallois.rs +++ b/src/math/gallois.rs @@ -375,5 +375,10 @@ fn test_gallois_inverse() { assert_eq!(field.inverse(54).unwrap(), 20); assert!(field.inverse(0).is_err()); + let field = GalloisFiled::new(1151, true); + assert_eq!(field.inverse(6).unwrap(), 14); + assert_eq!(field.inverse(54).unwrap(), 20); + assert!(field.inverse(0).is_err()); + // TODO add a test for a field that has a non prime base } diff --git a/src/math/gcd.rs b/src/math/gcd.rs index 54d203c..ffc9f91 100644 --- a/src/math/gcd.rs +++ b/src/math/gcd.rs @@ -23,6 +23,32 @@ pub fn egcd(mut a: u128, mut b: u128) -> Vec { return vec![egcd.gcd, egcd.x, egcd.y] } +#[pyfunction] +/// own implementation of egcd +pub fn alt_egcd(mut a: i128, mut b: i128, recursion: bool) -> Vec { + if recursion && a > b { + let tmp = a; + a = b; + b = tmp; + } + if a == 0 { + return vec![b, 0, 1] + } + let v = alt_egcd(b % a, a, true); + let mut result = vec![ + v[0], + v[2] - (b.checked_div(a).unwrap()) * v[1], + v[1], + ]; + return result; +} + +#[test] +fn test_alt_gcd() { + assert_eq!(egcd(12193, 123213), alt_egcd(12193, 123213, false)); + assert_eq!(egcd(52193, 123212), alt_egcd(52193, 123212, false)); +} + #[pyfunction] /// euclidian algorithm pub fn gcd(a: u128, b: u128) -> u128 {