-2

My program asks a user for two numbers, and then I have to pass those numbers to my function. My function is supposed to "Identify the greatest common divisor (GCD) of the two values using Euclid's Algorithm. Return true if this value is greater than 1 and less than the smaller of the two numbers. Set the call-by-reference parameter to the value of the GCD. In main() output the GCD and whether or not your function returned true or false." How do I do this?

int gcd (int a, int b)
{
    int c;

    if ( b == 0 )
        return a;

    else
        while ( b != 0 )
        {
            c = b;
            b = a % b;
            a = c;
        }

        return a;
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • Please include the code you've already written, and indicate which part of it is causing a problem for you. – Simon MᶜKenzie Apr 11 '13 at 00:38
  • should i just copy and paste or is there a specific way to show you? –  Apr 11 '13 at 00:41
  • 1
    @user2085305 Just do the best you can. :) – Drew Dormann Apr 11 '13 at 00:42
  • I am doing what I can, and what I know. The rest I must learn, right? So far, that is what I have, or the what I know part. Now is the part where I begin to learn a little more, from you guys, and begin to improve. –  Apr 11 '13 at 00:48
  • 3
    To help keep your code simple, you should note that if you *completely remove* the three lines `if ( b == 0 ) return a; else` your function doesn't change. It will still return `a` if `b == 0`. – Drew Dormann Apr 11 '13 at 00:53
  • Your gcd function appears to be correct - e.g. `gcd(1071, 462)==gcd(462,1071)==21`. What's your actual problem? – Simon MᶜKenzie Apr 11 '13 at 01:04

2 Answers2

1

Dude, it could not have been simpler... STFG

Your code is getting close to the example 2, but you have an error in this line

   if ( b == 0 )
        return a;

The checking and returning should be in opposite order

I would try this wiki implementation in pseudo-code:

function gcd(a, b)
    while b ≠ 0
       t := b
       b := a mod t
       a := t
    return a

but you should at least try to google something up man. =)

Kupto
  • 2,802
  • 2
  • 13
  • 16
0

this is the most hardest logic that you are using, there are very easy logics that you can get from blogs, i found this one from

http://www.programmingtunes.com/finding-greatest-common-divisor-of-2-numbers-c/:

//greatest common divisor of 2 numbers in C++
#include <iostream>
using namespace std;
void main()
{
int x = 24;
int y = 18;
int temp = 1 ;
for(int i = 2; i<=y; i++)
{
    if(x%i == 0 && y%i == 0)
    {
    temp = i;
    }

}

cout<<temp<<endl;

}
Pukki
  • 586
  • 1
  • 7
  • 18