---
title: "Create a Rust program to find the GCD (Greatest Common Divisor) of two numbers."  
description: "Create a Rust program to find the GCD (Greatest Common Divisor) of two numbers."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-24  
canonical: https://www.mindstick.com/forum/158800/create-a-rust-program-to-find-the-gcd-greatest-common-divisor-of-two-numbers  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# Create a Rust program to find the GCD (Greatest Common Divisor) of two numbers.

Create a [Rust](https://www.mindstick.com/forum/160170/explain-rust-s-ownership-borrowing-and-lifetimes-system) [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) to find the GCD ([Greatest](https://www.mindstick.com/articles/12976/the-greatest-games-at-vegas-paradise) [Common](https://www.mindstick.com/articles/23170/10-most-common-accounting-mistakes-of-small-business) Divisor) of two numbers.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust program to find the GCD (Greatest Common Divisor) of two numbers:

Rust

```plaintext
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

```plaintext
rustc gcd.rs
./gcd
```

This will print the following output:

Code snippet

```plaintext
The GCD of 12 and 18 is: 6
```

This indicates that the GCD of 12 and 18 is 6.


---

Original Source: https://www.mindstick.com/forum/158800/create-a-rust-program-to-find-the-gcd-greatest-common-divisor-of-two-numbers

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
