You should use the Euclidean algorithm to find GCD, its much easier and faster that way. Since you would use the remainders got by dividing one number by another and find the GCD (final remaining remainder).
Here's the implementation in Standard C++ code:
Code:
#include<iostream>
using namespace std;
int gcd(int a, int b)
{
int t;
while(b!=0)
{
t = b;
b = a%b; // B's now the remainder of A/B.
a = t;
} // And we go to the next iteration.
return a;
}
int main()
{
int a,b,c,g;
cout<<"Enter 3 numbers: ";
cin>>a>>b>>c;
g=gcd(gcd(a,b),c); // Comm./Asso. laws...
cout<<"The GCD of the 3 numbers is: "<<g<<endl;
return 0;
}
Your way takes some extra number crunching and thus its way slow for large numbers.
Apart from that,
it sure is correct in its answer. Your teacher is probably acting oversmart.
Lets try an example of
12121212, 18181818, 24242424
Time taken
Code:
bigbang@pysnakums:~$ time ./yours
GCD is
6060606
real 0m0.271s
user 0m0.272s
sys 0m0.000s
bigbang@pysnakums:~$ time ./euclid
The GCD of the 3 numbers is: 6060606
real 0m0.003s
user 0m0.004s
sys 0m0.000s