2018-2-14

# Smallest positive number that is evenly divisible by all of the numbers from 1 to 20 with Rust

The smallest common multiple of 1, 2 and 3 is the smallest common multiple of 1 and the smallest common multiple of 2 and 3.

The fifth Project Euler problem - Smallest Multiple - is stated as follows.

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

``````fn lcm(a: u64, b: u64) -> u64 {
if a <= 0 || b <= 0 {
0
} else {
a * b / gcd(a, b)
}
}

fn gcd(a: u64, b: u64) -> u64 {
if b <= 0 {
a
} else {
gcd(b, a % b)
}
}

fn main() {
let n = 20;
println!(
"{} is evenly divisible by all of the numbers from 1 to {}.",
(1..n).fold(n, |a, b| lcm(a, b)),
n
);
}
``````
Jan Järfalk — User experienced esthete, technician, geek and web worker. Aspiring artist and recreational mathematician. I indulge and travel plenty. Constraints are good.