Algorithm to find the HCF

IT & Software

| 171 views

Write an algorithm to find the HCF (Highest Common Factor) of the two numbers entered by a user. Transform your algorithm into a C program, support your program with suitable comments.


An algorithm to find the Highest Common Factor (HCF), also known as the Greatest Common Divisor (GCD), of two numbers, followed by a C program that implements this algorithm.

Algorithm to Find HCF


  Start
  Input: Read two integers, num1 and num2.
  Check: If num2 is 0, then:
        Set HCF = num1
        Go to step 6
 Calculate:
        Set temp = num2
        Set num2 = num1 % num2 (find the remainder)
        Set num1 = temp
  Repeat: Go back to step 3.
  Output: Display HCF.
  End

C Program to Find HCF
#include 
// Function to calculate HCF using the Euclidean algorithm
int findHCF(int num1, int num2) {
    // Loop until num2 becomes 0
    while (num2 != 0) {
        // Store the current num2
        int temp = num2;
        // Update num2 to be the remainder of num1 divided by num2
        num2 = num1 % num2;
        // Update num1 to be the previous value of num2
        num1 = temp;
    }
    // When num2 is 0, num1 holds the HCF
    return num1;
}
int main() {
    int number1, number2, hcf;
    // Prompt user for input
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);
    // Calculate HCF
    hcf = findHCF(number1, number2);
    // Display the result
    printf("The HCF of ?nd %d is: %d\n", number1, number2, hcf);
    return 0; // Indicate successful completion
}


Explanation of the C Program


  Function findHCF: This function implements the Euclidean algorithm to find the HCF. It keeps updating num1 and num2 until num2 becomes 0.
  Main Function: It prompts the user to enter two integers, calls the findHCF function, and displays the result.
  Comments: Each significant step is commented for clarity, explaining what the code is doing.


📢 Join Our WhatsApp Channel

Get Daily GK, Current Affairs, Amazing Facts & Quiz Updates.

🚀 Join Now
Share this Post
About Author

Quizer Team

Comments

IgEGWPhmTjgGD 24 May, 2025

Leave a Comment

Your email address will not be published. Required fields are marked *

Daily Challenge

📅 Daily Quiz Challenge

Attempt today's quiz and improve your competitive exam preparation with fresh questions daily.

Start Quiz →
Mega Contest

🏆 Monthly Mega Quiz

Participate in monthly quiz contests and test your overall knowledge with top performers.

Explore Quiz →

🔥 Join Our WhatsApp Channel

Daily GK, Facts & Quiz Updates