Skip to content

Commit

Permalink
optimise mod_pow (#301)
Browse files Browse the repository at this point in the history
<!--- Please provide a general summary of your changes in the title
above -->

## Pull Request type

<!-- Please try to limit your pull request to one type; submit multiple
pull requests if needed. -->

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
  • Loading branch information
shramee authored May 15, 2024
1 parent 1b6091d commit db6ebd8
Showing 1 changed file with 3 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/math/src/mod_arithmetics.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,11 @@ pub fn div_mod(a: u256, b: u256, mod_non_zero: NonZero<u256>) -> u256 {
pub fn pow_mod(mut base: u256, mut pow: u256, mod_non_zero: NonZero<u256>) -> 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);
};

Expand Down

0 comments on commit db6ebd8

Please sign in to comment.