# Greatest common divisor

• 04-13-2005
wiz23
Greatest common divisor
I am working on the greatest common divisor (gcd), previously I have already declare a = 667 and c = 140 and now I am trying to get the (gcd) working. The answer to this is 1. Here is my code:
Code:

```int gcd(int a, int c); {  int g;  g = a;  while (a%g!=0||c%g!=0) { g--; } return g; }```
Is this the right code for (gcd). If so I find it hard to display on the screen as once compile it then disappear. Is there a way that can make g display itself such as
Code:

`cout << g << endl;`
• 04-13-2005
laserlight
Quote:

Is this the right code for (gcd).
Test and find out.
You should get an error concerning a certain semi-colon placed inappropriately.

Offhand the algorithm probably works, but looks inefficient.
Search the Web for a GCD algorithm by the very late Euclid.

Quote:

If so I find it hard to display on the screen as once compile it then disappear.
Run your program from command line, or do a
std::cin.sync(); std::cin.get();
before returning 0 in main().
• 04-13-2005
joshdick
FAQ > How do I... (Level 1) > Stop my Windows Console from disappearing everytime I run my program?
http://faq.cprogramming.com/cgi-bin/...&id=1043284385

Search the board for GCD.
• 04-13-2005
XSquared
Putting aside any syntax-related problems your code has, it should work to calculate the GCD. Of course, if you want to do it efficiently, you will want to use the Euclidean algorithm.
• 04-13-2005
wiz23
Is this GCD code alright?
Code:

```int gcd (int x, int y) {  if (x % y == 0)   return y;  else   return gcd (y, x % y); }```
But for my one, I am currently using a = 667 and c = 140, so does this mean is like
Code:

```int gcd (int a, int c) {  if (a % c == 0)   return c;  else   return gcd (c, a % c); }```
If so, how can I display the gcd on the screen because the return function will eventually disappear. Is there a way that the
Code:

`cout <<`
can be used here so I can display it.
• 04-13-2005
XSquared
Code:

`cout<<gcd(667,140)<<endl;`
That should work just fine.