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:
- The function calculateGCD takes two integers a and b as input and returns their greatest common divisor.
- 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.
- 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.
- Finally, in the main function, we define two integers num1 and num2 with values 24 and 36, respectively.
- We call the calculateGCD function with num1 and num2 as arguments and store the result in the gcd variable.
- 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:
- The GCDCalculator class contains two methods: calculateGCD and main.
- The calculateGCD method takes two integers a and b as input and returns their greatest common divisor (GCD).
- 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.
- 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.
- Once the loop exits, the value of a will be the GCD of the original two numbers.
- The main method is the entry point of the program. It initializes two integers num1 and num2 with values 24 and 36, respectively.
- The calculateGCD method is called with num1 and num2 as arguments, and the result is stored in the gcd variable.
- The System.out.printf statement prints the GCD using a formatted string.
Java Output
The GCD of 24 and 36 is 12