Calculate gcd of two numbers Following is my code to calculate gcd of two numbers. My intension is not to use any specialised algorithm, just simple maths. Do you see any problem in my solution?

#include &lt;iostream&gt;
#include &lt;algorithm&gt;

int main() {
    int n1, n2;

    std::cin &gt;&gt; n1 &gt;&gt; n2;

    int smaller = min(n1, n2);
    int greater = max(n1, n2);

    if(greater % smaller == 0)
    {
        std::cout &lt;&lt; smaller;
        return 0;
    }

    int gcd = 1;

    for (int i = 2; i &lt;= smaller / 2; i++) {
        if(smaller % i == 0 &amp;&amp; greater % i == 0)
            gcd = i;
    }

    std::cout &lt;&lt; gcd;
    return 0;
}
The code does not account for negative numbers, yet the number type (int) allows them. The program will print 1 for the input -15 10, although 5 is the correct answer.
The GCD is usually positive, but your program will print -10 on the input -10 10.
A function int gcd(int, int) will make it easier to test and re-use.
Since you provided a complete program you probably want to check whether the user actually inputs two numbers and not tree 0.1234 or something else that's not an int.


That being said, thank you for


not using namespace std;
properly indenting your code (you could add braces around the if, though)
using proper names where they were reasonable (n1 and n2 aren't long-lived enough)


I guess that you know that there are better algorithms, so for a simple algorithm like this there is not much to improve. You certainly have to consider negative numbers, though. 

Also, some variables are available for the whole scope (n1 and n2), but only used for a short time. Try to limit the scope of a variable as much as possible, as it prevents errors like

for(i = 2; i &lt;= n1 / 2; ++i) // should have been "smaller", whoops