这是递归函数GCD正确的? [英] Is this recursive GCD function correct?
本文介绍了这是递归函数GCD正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一切编译和运行完美我的程序。我不得不写一个递归函数GCD。我用了两个功能然而,gcdRecursive和GCD。我可以凝聚这code到一个单一的功能,所以我不需要我的code以下内GCD功能?或者是我的code正确的,因为它是和都需要这两种功能。
无效gcdRecursive(INT * X,诠释* Y,int i)以{
如果(ⅰ> = 1){
如果(* X%我== 0安培;&放大器; * Y%我== 0){
的printf(%d个和%D的GCD为%d,* X * Y,I);
}
其他{
gcdRecursive(X,Y,I - 1);
}
}
}
无效GCD(INT * X,诠释* Y){
getValuesForGCD(X,Y);
gcdRecursive(X,Y,* X);
}
解决方案
是的,这是正确的,但它是迄今为止最佳的。
编辑:尝试使用这样的:
如果(X> Y)
最大公约数(X,Y)=最大公约数(Y,X);
如果(Y%X == 0)
最大公约数(X,Y)= X;
其他
最大公约数(X,Y)=最大公约数(X,Y%x)的
Everything compiles and runs perfectly for my program. I had to write a recursive GCD function. I used two functions however, gcdRecursive and gcd. Can I condense this code into a single function so I do not need the gcd function within my code below? Or is my code correct as it is and the two functions are both needed.
void gcdRecursive(int *x, int *y, int i){
if (i >= 1) {
if (*x % i == 0 && *y % i == 0) {
printf("The GCD of %d and %d is %d", *x, *y, i);
}
else {
gcdRecursive(x, y, i - 1);
}
}
}
void gcd(int *x, int *y){
getValuesForGCD(x, y);
gcdRecursive(x, y, *x);
}
解决方案
Yes it is correct but it is by far sub-optimal.
EDIT: try to use this:
if (x > y)
gcd(x,y) = gcd(y, x);
if (y % x == 0)
gcd(x, y) = x;
else
gcd(x, y) = gcd(x, y%x)
这篇关于这是递归函数GCD正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文