Skip to content

Commit 3fc6cac

Browse files
authored
feat: add gcd_of_n_numbers (rust-lang#304)
1 parent 417a0c1 commit 3fc6cac

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ These are for demonstration purposes only.
4141
- [x] [Baby-Step Giant-Step Algorithm](./src/math/baby_step_giant_step.rs)
4242
- [x] [Extended euclidean algorithm](./src/math/extended_euclidean_algorithm.rs)
4343
- [x] [Greatest common divisor](./src/math/greatest_common_divisor.rs)
44+
- [x] [Greatest common divisor of n numbers](./src/math/gcd_of_n_numbers.rs)
4445
- [x] [Miller Rabin primality test](./src/math/miller_rabin.rs)
4546
- [x] [Pascal's triangle](./src/math/pascal_triangle.rs)
4647
- [x] [Square root with Newton's method](./src/math/square_root.rs)

src/math/gcd_of_n_numbers.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/// returns the greatest common divisor of n numbers
2+
pub fn gcd(nums: &[usize]) -> usize {
3+
if nums.len() == 1 {
4+
return nums[0];
5+
}
6+
let a = nums[0];
7+
let b = gcd(&nums[1..]);
8+
gcd_of_two_numbers(a, b)
9+
}
10+
11+
fn gcd_of_two_numbers(a: usize, b: usize) -> usize {
12+
if b == 0 {
13+
return a;
14+
}
15+
gcd_of_two_numbers(b, a % b)
16+
}
17+
18+
#[cfg(test)]
19+
mod tests {
20+
use super::*;
21+
#[test]
22+
fn it_works() {
23+
assert_eq!(gcd(&[1, 2, 3, 4, 5]), 1);
24+
assert_eq!(gcd(&[2, 4, 6, 8, 10]), 2);
25+
assert_eq!(gcd(&[3, 6, 9, 12, 15]), 3);
26+
assert_eq!(gcd(&[10]), 10);
27+
assert_eq!(gcd(&[21, 110]), 1);
28+
}
29+
}

src/math/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ mod baby_step_giant_step;
22
mod extended_euclidean_algorithm;
33
mod fast_fourier_transform;
44
mod fast_power;
5+
mod gcd_of_n_numbers;
56
mod greatest_common_divisor;
67
mod linear_sieve;
78
mod miller_rabin;
@@ -23,6 +24,7 @@ pub use self::fast_fourier_transform::{
2324
inverse_fast_fourier_transform,
2425
};
2526
pub use self::fast_power::fast_power;
27+
pub use self::gcd_of_n_numbers::gcd;
2628
pub use self::greatest_common_divisor::{
2729
greatest_common_divisor_iterative, greatest_common_divisor_recursive,
2830
};

0 commit comments

Comments
 (0)