HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMajor

Greatest common divisor

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
divisorcommongreatest

Problem

I wrote a program to find the greatest common divisor between two numbers. How do I improve this program?

#include
using namespace std;

int main() {

int first_number;
cout>first_number;

if(first_number > first_number;

int  second_number;
cout>second_number;

if(second_number > second_number;

int  gcd;
for(int i=1;i<=first_number&&i<=second_number;i++){

if(first_number%i==0 && second_number%i == 0 ){

gcd=i;

   }

}

cout<<"Greatest Common Divison (GCD):"<<gcd<<endl;
return 0;
}

Solution

A more elegant implementation of the gcd function:

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}


To ensure that the arguments are positive, it's easiest to use the abs(...) function.

Please also indent your code nicely to make it more readable.

And put spaces around operators. For example, instead of this:

for(int i=1;i<=first_number&&i<=second_number;i++){


Write like this:

for (int i = 1; i <= first_number &&i <= second_number; i++) {


Putting it together, the implementation of the entire program can become short and sweet:

#include 

using std::cin;
using std::cout;
using std::endl;

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int main() {
    int num1, num2;

    cout > num1;
    cout > num2;

    cout << "Greatest Common Divisor: " << gcd(abs(num1), abs(num2)) << endl;
}


You can play with this on ideone.

Code Snippets

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}
for(int i=1;i<=first_number&&i<=second_number;i++){
for (int i = 1; i <= first_number &&i <= second_number; i++) {
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int main() {
    int num1, num2;

    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;

    cout << "Greatest Common Divisor: " << gcd(abs(num1), abs(num2)) << endl;
}

Context

StackExchange Code Review Q#66711, answer score: 24

Revisions (0)

No revisions yet.