TheAlgorithms / Rust

All Algorithms implemented in Rust
MIT License
22.91k stars 2.24k forks source link

Fixed `gcd_extended` and `mod_inverse` for modular exponential #750

Closed Cheshulko closed 5 months ago

Cheshulko commented 5 months ago

Pull Request Template

Description

Fixed the implementation of gcd_extended and mod_inverse. Reference: Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein - Introduction to algorithms, 3rd edition. Page 937. The extended form of Euclid’s algorithm

Type of change

Current implementation is wrong. Examples:

mod_inverse(7, 13)
Current: 0
Correct: 2

mod_inverse(5, 31)
Current: 0
Correct: 25

mod_inverse(10, 11)
Current: 0
Correct: 10

The test

assert_eq!(
    modular_exponential(123, -45, 67),
    mod_inverse(123, 67).pow(45) % 67
); // Inverse of 123 mod 67 is calculated via the function

passed because mod_inverse(123, 67) is 0 in current implementation. Correct value is 6 and it overflows i64 6.pow(45) = 1,03945637534×10³⁵.

Checklist:

codecov-commenter commented 5 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 95.01%. Comparing base (864ef42) to head (e0483a9).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #750 +/- ## ======================================= Coverage 95.00% 95.01% ======================================= Files 303 303 Lines 22522 22529 +7 ======================================= + Hits 21398 21405 +7 Misses 1124 1124 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.