The traditional (if inefficient) algorithm is:
# Pseudocode
gcd ( m, n )
begin
while m != n do
if m > n
m := m - n
else
n := n - m
loop
return m
end
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Thanks for the reply but I'm still confused
Well, aside from spelling out the algorithm so that it's trivial to convert to C++, there's not much more I can do to help you. Search google for analyses on the algorithm. It's been around for a while, so you shouldn't have trouble finding anything.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Ever tought about using the Algorithm of Euclides?
The pseudocode I gave was the Euclidean algorithm. It was an earlier formulation of the problem using subtraction instead of the later (more efficient) algorithm that uses the remainder of integer division.
>The problem is I have to use this basic shell to get my answer.
Then it's homework, and we won't do it for you. Unless you're incapable of doing simple math, it's a small step to convert the algorithm I gave you into something that fits your shell.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Any suggestions?
Read a book on C++, and read the warnings your compiler gives you:
#include <iostream>
using namespace std;
int main()
{
int m;
int n;
int firstNum;
int secondNum;
cout << "Enter 1st number:" << endl;
cin >> firstNum;
cout << "Enter 2nd number:" << endl;
cin >> secondNum;
m = firstNum;
n = secondNum;
while (m != n)
{
if (m > n)
m = m - n;
else
n = n - m;
}
cout << "the gcd of " << firstNum
<< " and " << secondNum
<< " is " << m << endl;
return 0;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>its not giving me any warnings
Your settings are too low. Turn your compiler up to the highest warning level and you'll catch more problems.
>Can't someone just give me the answer
No, because then you wouldn't learn squat. The whole point of this exercise is for you to learn, not for you to get people who already know how to do it to do it for you.
>I still don't see exactly what I was doing wrong
while (m != n);
This is a complete loop. The semicolon acts as the loop body. The problem is more obvious when you put the body on its own line:
while (m != n)
;
>what does := mean?
It's my pseudocode convention for assignment, borrowed from Pascal.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Did you try it? Or did you just come running here to get our okay before experimenting? I'll let you in on a little secret. I don't know about everyone else, but most of my advanced knowledge comes from experimentation on my own. If I had waited for someone to tell me about this stuff, I wouldn't be able to program my way out of a wet paper bag.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401