Ask your own question, for FREE!
Computer Science 11 Online
OpenStudy (anonymous):

Can someone explain this c++ program to me, especially the part in finding the GCD? Thank you. #include #include #include int main() { int a = 0; int b = 0; clrscr(); cout << "Enter First Number: "; cin >> a; cout << "Enter Second Number: "; cin >> b; cout<<"\n\n"; if((a<=0)||(b<=0)) exit(1); int c = 0; int d = 1; int gcd = 0, lcm; if(a >= b){c = a;} if(b > a){c = b;} while(d <= c/2) { if(a%d==0 && b%d==0){gcd = d;} ++d; } cout << "GCD is "<

ganeshie8 (ganeshie8):

int c = 0; int d = 1; int gcd = 0, lcm; if(a >= b){c = a;} if(b > a){c = b;} while(d <= c/2) { if(a%d==0 && b%d==0){gcd = d;} ++d; } it is computing the gcd of two input numbers by brute force : by checking every number from "1" to "half of biggest of the two input numbers" checking to see, if it is divisible by both "a" and "b"

OpenStudy (nick67):

Hi ganeshie8, don't you think the while condition could work checking from "1" to "half of lowest of the two input numbers" ?

ganeshie8 (ganeshie8):

it wont work. test with input and see : (2, 100) GCD of of two numbers can be lowest input number itself, as well. so checking till "half of lowest of input numbers" wont give the exact answer.. hope its clear nw... good observation btw :)

OpenStudy (nick67):

clear, thanks for explaining; so may be till "lowest of input numbers" could work ?

ganeshie8 (ganeshie8):

yw.. that works.. hmm it may iterate more times if the lowest number is not really that low. ex: 98, 100 it iterates 98 times, instead of 100/2 times. but on the other hand, with our current approach. it loops too many times if the number is very low... ex: 2, 100 it keeps iterating 100/2 times... so both are equally bad !!

OpenStudy (nick67):

ok, thank you

ganeshie8 (ganeshie8):

yw... :)

OpenStudy (anonymous):

Thank you!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!