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

#include&lt;iostream&gt;
using namespace std;

int main() {

int first_number;
cout&lt;&lt;"Enter First Number : ";
cin&gt;&gt;first_number;

if(first_number &lt; 0)
cout &lt;&lt; "Please enter a positive number" &lt;&lt; endl;
cin &gt;&gt; first_number;

int  second_number;
cout&lt;&lt;"Enter Second Number: ";
cin&gt;&gt;second_number;


if(second_number &lt; 0)
cout &lt;&lt; "Please enter a positive number" &lt;&lt; endl;
cin &gt;&gt; second_number;

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

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

gcd=i;

   }

}

cout&lt;&lt;"Greatest Common Divison (GCD):"&lt;&lt;gcd&lt;&lt;endl;
return 0;
}
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&lt;=first_number&amp;&amp;i&lt;=second_number;i++){



Write like this:

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




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

#include &lt;iostream&gt;

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 &lt;&lt; "Enter first number: ";
    cin &gt;&gt; num1;
    cout &lt;&lt; "Enter second number: ";
    cin &gt;&gt; num2;

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


You can play with this on ideone.