Sure, here is a Rust program to find the GCD (Greatest Common Divisor) of two numbers:
Rust
fn gcd(a: u64, b: u64) -> u64 {
// Check if one of the numbers is 0.
if a == 0 || b == 0 {
return 0;
}
// Loop while b is not 0.
while b != 0 {
// Swap a and b.
let temp = a;
a = b;
b = temp % b;
}
// Return a.
return a;
}
fn main() {
let a = 12;
let b = 18;
let gcd = gcd(a, b);
println!("The GCD of {} and {} is: {}", a, b, gcd);
}
This program first checks if one of the numbers is 0. If it is, then the program returns 0. Otherwise, the program loops while b is not 0. In each iteration of the loop, the program swaps a and b and then calculates the remainder of b divided by a. The program continues looping until b is 0. Finally, the program returns a.
To run this program, you can save it as a .rs file and then compile and run it using the following commands:
Code snippet
rustc gcd.rs
./gcd
This will print the following output:
Code snippet
The GCD of 12 and 18 is: 6
This indicates that the GCD of 12 and 18 is 6.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust program to find the GCD (Greatest Common Divisor) of two numbers:
Rust
This program first checks if one of the numbers is 0. If it is, then the program returns 0. Otherwise, the program loops while b is not 0. In each iteration of the loop, the program swaps a and b and then calculates the remainder of b divided by a. The program continues looping until b is 0. Finally, the program returns a.
To run this program, you can save it as a
.rsfile and then compile and run it using the following commands:Code snippet
This will print the following output:
Code snippet
This indicates that the GCD of 12 and 18 is 6.