Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to calculate the GCD (greatest common divisor) of two integers in C

3 Answers

0 votes
#include <stdio.h>

// Function to calculate GCD
int compute_gcd(int a, int b) {
    int gcd;

    for (int i = 1; i <= a && i <= b; i++) {
        if (a % i == 0 && b % i == 0)
            gcd = i;
    }

    return gcd;
}

int main(void) {
    int a = 12, b = 20;

    // Call the function to compute GCD
    int gcd = compute_gcd(a, b);

    // Print the result
    printf("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd);

    return 0;
}


/*
run:
  
The GCD (greatest common divisor) of 12 and 20 is: 4
  
*/

 



answered Oct 27, 2016 by avibootz
edited May 9, 2025 by avibootz
0 votes
#include <stdio.h>

// Function to calculate GCD
int compute_gcd(int a, int b) {
    int i = a < b ? a : b;
    
    for (; i >= 1; i--) { // Iterate downward to find the largest common divisor
        if (a % i == 0 && b % i == 0) {
            return i; // Return the first found GCD
        }
    }
    
    return 1; // Default return if no common divisor is found
}

int main(void) {
    int a = 12, b = 20;

    // Call the function to compute GCD
    int gcd = compute_gcd(a, b);

    // Print the result
    printf("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd);

    return 0;
}



/*
run:
  
The GCD (greatest common divisor) of 12 and 20 is: 4
  
*/

 



answered May 29, 2017 by avibootz
edited May 9, 2025 by avibootz
0 votes
#include <stdio.h> 

// Function prototype for computing the greatest common divisor (GCD)
int gcd(int a, int b);

int main(void) {   
    // Declare and initialize two integers
    int a = 12, b = 20;

    // Print the GCD of the two numbers using the gcd function
    printf("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd(a, b));
     
    return 0; // Exit the program
}

// Recursive function to compute the GCD
int gcd(int a, int b)  {
    // Base case: if b is 0, return a as the GCD
    return b == 0 ? a : gcd(b, a % b); // Recursive call with b and remainder of a divided by b
}


   
/*
run:
 
The GCD (greatest common divisor) of 12 and 20 is: 4
  
*/

 



answered May 29, 2017 by avibootz
edited May 9, 2025 by avibootz
...