-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;
}
4

2 回答 2

1

伙计,这再简单不过了…… STFG

您的代码已接近示例 2,但您在此行中有错误

   if ( b == 0 )
        return a;

检查和返回应该是相反的顺序

我会在伪代码中尝试这个 wiki 实现:

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

但你至少应该尝试用谷歌搜索一些东西。=)

于 2013-04-11T01:26:33.297 回答
0

这是您使用的最难的逻辑,您可以从博客中获得非常简单的逻辑,我从

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;

}
于 2014-03-22T14:36:44.080 回答