Skip to content

Commit

Permalink
Fix cases with b == 1 or a and n co-prime in `baby_step_giant_s…
Browse files Browse the repository at this point in the history
…tep.rs` (TheAlgorithms#635)
  • Loading branch information
vil02 authored Dec 19, 2023
1 parent 63e29bf commit f7f2769
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/math/baby_step_giant_step.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::math::greatest_common_divisor;
/// Baby-step Giant-step algorithm
///
/// Solving discrete logarithm problem:
Expand All @@ -10,8 +11,8 @@
use std::collections::HashMap;

pub fn baby_step_giant_step(a: usize, b: usize, n: usize) -> Option<usize> {
if b == 1 {
return Some(n);
if greatest_common_divisor::greatest_common_divisor_stein(a as u64, n as u64) != 1 {
return None;
}

let mut h_map = HashMap::new();
Expand Down Expand Up @@ -41,6 +42,9 @@ mod tests {
fn small_numbers() {
assert_eq!(baby_step_giant_step(5, 3, 11), Some(2));
assert_eq!(baby_step_giant_step(3, 83, 100), Some(9));
assert_eq!(baby_step_giant_step(9, 1, 61), Some(5));
assert_eq!(baby_step_giant_step(5, 1, 67), Some(22));
assert_eq!(baby_step_giant_step(7, 1, 45), Some(12));
}

#[test]
Expand Down Expand Up @@ -69,4 +73,11 @@ mod tests {
Some(14215560)
);
}

#[test]
fn no_solution() {
assert!(baby_step_giant_step(7, 6, 45).is_none());
assert!(baby_step_giant_step(23, 15, 85).is_none());
assert!(baby_step_giant_step(2, 1, 84).is_none());
}
}

0 comments on commit f7f2769

Please sign in to comment.