gpt4 book ai didi

algorithm - 如何获得 double 的(最大公约数)GCD

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:11:42 25 4
gpt4 key购买 nike

这是一个简单的任务,但我似乎不知道该怎么做

这是一个示例函数结构

private double GetGCD(double num1, double num2)
{
//should return the GCD of the two double
}

测试数据

   num1 = 6;
num2 = 3;
*return value must be 3*

num1 = 8.8;
num2 = 6.6;
*return value must be 2.2*

num1 = 5.1;
num2 = 8.5;
*return value must be 1.7*

注意:最大小数位数为 1。 编程语言并不重要。我只需要算法

请帮忙..谢谢!

最佳答案

如果只有一位小数,将数字乘以 10,将它们转换为整数并运行 integer GCD function .

这也将节省您 floating point precision errors .

引用 this answer ,Python 中的基本欧几里德算法(对于整数!)是:

def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.

Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a

所以,你的代码应该是这样的:

 def gcd_floats(x,y):
return gcd( int(x*10), int(y*10) )/10

关于algorithm - 如何获得 double 的(最大公约数)GCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9392091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com