使用欧几里得算法识别两个值的最大公约数 (GCD)
Identify the greatest common divisor (GCD) of the two values using Euclid's Algorithm
我的程序向用户询问两个数字,然后我必须将这些数字传递给我的函数。我的功能应该是"使用欧几里得算法确定两个值的最大公约数(GCD)。如果此值大于1且小于两个数字中较小的一个,则返回true。将call-by-reference参数设置为GCD的值。在main()中输出GCD以及你的函数是否返回true或false。我该怎么做呢?
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;
}
老兄,再简单不过了…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
但你至少应该试着谷歌一下,伙计。div =)
这是你正在使用的最困难的逻辑,你可以从博客中获得非常简单的逻辑,我从
找到了这个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;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- 两个二项式系数模 10^9 + 7 的 GCD
- NTRUEncrypt:使用开源标准算法中的描述无法正确找到两个多项式的GCD,无法定义是否存在多边形的逆
- 一个数组可以划分的最大子数组,使得不同子数组中任意两个元素的 GCD 始终为 1?
- 使用欧几里得算法识别两个值的最大公约数 (GCD)