Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Write a function to find the greatest common divisor of two numbers

Write a function that takes two integers as input and calculates their greatest common divisor.

Program in C

C
#include <stdio.h>

int calculateGCD(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }

    return a;
}

int main() {
    int num1 = 24;
    int num2 = 36;

    int gcd = calculateGCD(num1, num2);

    printf("The GCD of %d and %d is %d\n", num1, num2, gcd);

    return 0;
}

Explanation:

  1. The function calculateGCD takes two integers a and b as input and returns their greatest common divisor.
  2. Inside the while loop, we continuously calculate the remainder by performing the modulo operation a % b. We update a with the value of b and b with the value of the remainder.
  3. The loop continues until b becomes zero, indicating that we have found the GCD. At this point, the value of a will be the GCD.
  4. Finally, in the main function, we define two integers num1 and num2 with values 24 and 36, respectively.
  5. We call the calculateGCD function with num1 and num2 as arguments and store the result in the gcd variable.
  6. We then print the GCD using the printf function.
C Output
The GCD of 24 and 36 is 12

Program in Java

Java
public class GCDCalculator {
    public static int calculateGCD(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }

        return a;
    }

    public static void main(String[] args) {
        int num1 = 24;
        int num2 = 36;

        int gcd = calculateGCD(num1, num2);

        System.out.printf("The GCD of %d and %d is %d\n", num1, num2, gcd);
    }
}

Explanation:

  1. The GCDCalculator class contains two methods: calculateGCD and main.
  2. The calculateGCD method takes two integers a and b as input and returns their greatest common divisor (GCD).
  3. Inside the method, there is a while loop that continues as long as b is not zero. This loop uses the Euclidean algorithm to calculate the GCD.
  4. In each iteration of the loop, the remainder of a divided by b is calculated using the modulo operator %. The value of a is updated to the value of b, and b is updated to the remainder.
  5. Once the loop exits, the value of a will be the GCD of the original two numbers.
  6. The main method is the entry point of the program. It initializes two integers num1 and num2 with values 24 and 36, respectively.
  7. The calculateGCD method is called with num1 and num2 as arguments, and the result is stored in the gcd variable.
  8. The System.out.printf statement prints the GCD using a formatted string.
Java Output
The GCD of 24 and 36 is 12