From db6ebd82e8b36c3ec0106b62b39d76c37ec57bee Mon Sep 17 00:00:00 2001 From: Shramee Srivastav Date: Wed, 15 May 2024 22:12:01 +0530 Subject: [PATCH] optimise mod_pow (#301) ## Pull Request type Please check the type of change your PR introduces: - [ ] Bugfix - [ ] Feature - [ ] Code style update (formatting, renaming) - [x] Refactoring (no functional changes, no API changes) - [ ] Build-related changes - [ ] Documentation content changes - [ ] Other (please describe): ## What is the current behavior? ```diff running 3 tests - test alexandria_math::tests::mod_arithmetics_test::pow_mod_1_test ... ok (gas usage est.: 28413612) + test alexandria_math::tests::mod_arithmetics_test::pow_mod_1_test ... ok (gas usage est.: 27142740) - test alexandria_math::tests::mod_arithmetics_test::pow_mod_2_test ... ok (gas usage est.: 28413612) + test alexandria_math::tests::mod_arithmetics_test::pow_mod_2_test ... ok (gas usage est.: 27142740) - test alexandria_math::tests::mod_arithmetics_test::pow_mod_test ... ok (gas usage est.: 28443352) + test alexandria_math::tests::mod_arithmetics_test::pow_mod_test ... ok (gas usage est.: 27173670) ``` Issue Number: N/A ## What is the new behavior? No changes in functionality, just slightly faster `pow_mod`. ## Does this introduce a breaking change? - [ ] Yes - [x] No --- src/math/src/mod_arithmetics.cairo | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/math/src/mod_arithmetics.cairo b/src/math/src/mod_arithmetics.cairo index 26a429eb..d424c417 100644 --- a/src/math/src/mod_arithmetics.cairo +++ b/src/math/src/mod_arithmetics.cairo @@ -95,12 +95,11 @@ pub fn div_mod(a: u256, b: u256, mod_non_zero: NonZero) -> u256 { pub fn pow_mod(mut base: u256, mut pow: u256, mod_non_zero: NonZero) -> u256 { let mut result: u256 = 1; while (pow != 0) { - if ((pow & 1) > 0) { + let (q, r) = DivRem::div_rem(pow, 2); + if r == 1 { result = mult_mod(result, base, mod_non_zero); } - - pow = pow / 2; - + pow = q; base = mult_mod(base, base, mod_non_zero); };