forked from keep-starknet-strange/alexandria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcd_of_n_numbers.cairo
44 lines (41 loc) · 1.05 KB
/
gcd_of_n_numbers.cairo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//! # GCD for N numbers
use array::SpanTrait;
use option::OptionTrait;
// Calculate the greatest common dividor for n numbers
// # Arguments
// * `n` - The array of numbers to calculate the gcd for
// # Returns
// * `felt252` - The gcd of input numbers
fn gcd(mut n: Span<u128>) -> u128 {
// Return empty input error
if n.is_empty() {
panic_with_felt252('EI')
}
let mut a = *n.pop_front().unwrap();
loop {
match n.pop_front() {
Option::Some(b) => {
a = gcd_two_numbers(a, *b);
},
Option::None(()) => {
break a;
},
};
}
}
// Internal function to calculate the gcd between two numbers
// # Arguments
// * `a` - The first number for which to calculate the gcd
// * `b` - The first number for which to calculate the gcd
// # Returns
// * `felt252` - The gcd of a and b
fn gcd_two_numbers(mut a: u128, mut b: u128) -> u128 {
loop {
if b == 0 {
break a;
}
let r = a % b;
a = b;
b = r;
}
}