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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,039 questions

40,766 answers

573 users

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

4 Answers

0 votes
#include <iostream>
 
int main()
{
    int a = 12 , b = 20, gcd;
 
    for (int i = 1; i <= a && i <= b; i++) {
        if (a % i == 0 && b % i == 0)
            gcd = i;
    }
 
    std::cout << "The GCD (greatest common divisor) of " << a << " and " << b << " is: " << gcd;
}
 
 
 
 
/*
run:
 
The GCD (greatest common divisor) of 12 and 20 is: 4
 
*/

 





answered May 28, 2017 by avibootz
edited Jul 31, 2023 by avibootz
0 votes
#include <iostream>
 
int main()
{
    int a = 12, b = 20, gcd;
 
    int i = a < b ? a : b;
 
    for (;i <= a && i <= b; i--) {
        if (a % i == 0 && b % i == 0) {
            gcd = i;
            break;
        }
    }
 
    std::cout << "The GCD (greatest common divisor) of " << a << " and " << b << " is: " << gcd;
}
 
 
 
 
/*
run:
 
The GCD (greatest common divisor) of 12 and 20 is: 4
 
*/

 





answered May 29, 2017 by avibootz
edited Jul 31, 2023 by avibootz
0 votes
#include <iostream>

int gcd(int a, int b);
  
int main()
{
    int a = 12, b = 20;
    
    int _gcd = gcd(a, b);
  
    std::cout << "The GCD (greatest common divisor) of " << a << " and " << b << " is: " << _gcd;
}
  
int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}
  
  
  
  
/*
run:
  
The GCD (greatest common divisor) of 12 and 20 is: 4
  
*/

 





answered May 29, 2017 by avibootz
edited Aug 1, 2023 by avibootz
0 votes
#include <iostream>
#include <algorithm>
  
int main()
{
    int a = 12, b = 20;
    
    int gcd = std::__gcd(a, b); 
  
    std::cout << "The GCD (greatest common divisor) of " << a << " and " << b << " is: " << gcd;
}
 
  
  
  
/*
run:
  
The GCD (greatest common divisor) of 12 and 20 is: 4
  
*/

 





answered Jul 31, 2023 by avibootz
edited Aug 1, 2023 by avibootz
...