C Program to Calculate HCF of Two Numbers Using Euclidean Algorithm

Answered using GPT 4o mini by ChatGPT

Question:

Make a program of hcf of two numbers in c programming

Answer:

Certainly! Below is a simple C program to calculate the Highest Common Factor (HCF) of two numbers using the Euclidean algorithm.

#include <stdio.h>

// Function to calculate HCF using the Euclidean algorithm
int calculateHCF(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int num1, num2, hcf;

    // Input two numbers from the user
    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    // Calculate HCF
    hcf = calculateHCF(num1, num2);

    // Output the result
    printf("The HCF of %d and %d is: %d\n", num1, num2, hcf);

    return 0;
}

Explanation:

  1. Function calculateHCF(int a, int b): This function implements the Euclidean algorithm to find the HCF. It continues to replace a with b and b with a % b until b becomes zero. At that point, a contains the HCF.

  2. main() function:

    • It prompts the user to enter two integers.
    • It calls the calculateHCF function to compute the HCF of the two numbers.
    • Finally, it prints the result.

How to Compile and Run:

  1. Save the code in a file named hcf.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using:
    gcc hcf.c -o hcf
    
  4. Run the program using:
    ./hcf
    

You can then enter two numbers, and the program will output their HCF.