• To check GCD of two numbers first we need to read input from user. i.e ask user to enter two numbers
  • Store those two numbers in two integer variables
  • Check if number is factor of given two numbers by iterating in for loop.

gcd of two numbers in c


  1. #include <stdio.h>
  2. // program to check gcd of two numbers in c 
  3. // write a c program to find gcd of two integers
  4. // www.instanceofjava.com
  5. int main()
  6. {
  7.     int number1, number2, i, gcd;
  8.     // read input from user
  9.     printf(" please enter any two numbers: ");
  10.     scanf("%d %d", &number1, &number2);

  11.     for(i=1; i <= number1 && i <= number2; ++i)
  12.     {
  13.         // checking  if i is divisible by both numbers / factor of both numbers
  14.         if(number1%i==0 && number2%i==0)
  15.             gcd = i;
  16.     }

  17.     printf("GCD of %d and %d is %d", number1, number2, gcd);

  18.     getch();
  19. }


Output:

gcd of two integers in c




  1. #include <stdio.h>
  2. // Function to compute Greatest Common Divisor using Euclidean Algorithm
  3. int gcd(int a, int b) {
  4.     while (b != 0) {
  5.         int temp = b;
  6.         b = a % b;
  7.         a = temp;
  8.     }
  9.     return a;
  10. }

  11. int main() {
  12.     int num1, num2;

  13.     // enter  two numbers from the user
  14.     printf("Enter two numbers to find their GCD: ");
  15.     scanf("%d %d", &num1, &num2);

  16.     // Ensure numbers are positive
  17.     if (num1 < 0) num1 = -num1;
  18.     if (num2 < 0) num2 = -num2;

  19.     // Calculate and display the GCD
  20.     int result = gcd(num1, num2);
  21.     printf("The GCD of %d and %d is: %d\n", num1, num2, result);

  22.     return 0;
  23. }


Explanation:

  1. Input:
    • The user enters two numbers.
  2. Logic:
    • The findGCD function uses the Euclidean algorithm:
      • Replace aa with bb and bb with a%ba \% b until b=0b = 0.
      • The final value of aa is the GCD.
  3. Output:
    • The program prints the GCD of the two input numbers.



Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu