Greatest common divisor iterative
To calculate the greatest common divisor (GCD) iteratively in Rust, you can use the Euclidean algorithm. Here's an example implementation:
fn gcd_iterative(a: u64, b: u64) -> u64 {
let mut x = a;
let mut y = b;
while y != 0 {
let temp = y;
y = x % y;
x = temp;
}
x
}
In this code, the gcd_iterative
function takes two unsigned 64-bit integers a
and b
as input and returns their GCD. It uses a while loop to iterate until y
becomes zero. Inside the loop, it calculates the remainder of x
divided by y
using the modulo operator %
and assigns it to y
. Then, it assigns the initial value of y
to x
. This process continues until y
becomes zero, at which point x
will hold the GCD of a
and b
.
You can call this function with your desired values to find their GCD. For example:
fn main() {
let a = 24;
let b = 36;
let gcd = gcd_iterative(a, b);
println!("The GCD of {} and {} is {}", a, b, gcd);
}
When you run this code, it will output:
The GCD of 24 and 36 is 12
This indicates that the GCD of 24 and 36 is 12.