📜  查找浮点数的GCD的程序

📅  最后修改于: 2021-05-06 17:25:05             🧑  作者: Mango

两个或更多数字(不是全零)的最大公约数(GCD)是将每个数字相除的最大正数。
例子:

Input  : 0.3, 0.9
Output : 0.3

Input  : 0.48, 0.108
Output : 0.012

解决此问题的最简单方法是:
a = 1.20
b = 22.5
将每个不带小数的数字表示为素数的乘积,我们得到:
120 =2^3*3*5
2250 =2*3^2*5^3
现在,HCF为120和2250 = 2 * 3 * 5 = 30
因此,HCF为1.20和22.5 = 0.30
(小数点后两位)
我们可以使用欧几里得算法来做到这一点。该算法表明,如果从较大的数字中减去较小的数字,则两个数字的GCD不会改变。

C++
// CPP code for finding the GCD of two floating
// numbers.
#include 
using namespace std;
 
// Recursive function to return gcd of a and b
double gcd(double a, double b)
{
    if (a < b)
        return gcd(b, a);
 
    // base case
    if (fabs(b) < 0.001)
        return a;
 
    else
        return (gcd(b, a - floor(a / b) * b));
}
 
// Driver Function.
int main()
{
    double a = 1.20, b = 22.5;
    cout << gcd(a, b);
    return 0;
}


Java
// JAVA code for finding the GCD of
// two floating numbers.
import java.io.*;
 
class GFG {
     
    // Recursive function to return gcd
    // of a and b
    static double gcd(double a, double b)
    {
        if (a < b)
            return gcd(b, a);
      
        // base case
        if (Math.abs(b) < 0.001)
            return a;
      
        else
            return (gcd(b, a -
                   Math.floor(a / b) * b));
    }
      
    // Driver Function.
    public static void main(String args[])
    {
        double a = 1.20, b = 22.5;
        System.out.printf("%.1f" ,gcd(a, b));
    }
}
 
/*This code is contributed by Nikita Tiwari.*/


Python
# Python code for finding the GCD of
# two floating numbers.
 
import math
 
# Recursive function to return gcd
# of a and b
def gcd(a,b) :
    if (a < b) :
        return gcd(b, a)
     
    # base case
    if (abs(b) < 0.001) :
        return a
    else :
        return (gcd(b, a - math.floor(a / b) * b))
     
      
# Driver Function.
a = 1.20
b = 22.5
print('{0:.1f}'.format(gcd(a, b)))
 
# This code is contributed by Nikita Tiwari.


C#
// C# code for finding the GCD of
// two floating numbers.
using System;
 
class GFG {
     
    // Recursive function to return gcd
    // of a and b
    static float  gcd(double a, double b)
    {
        if (a < b)
            return gcd(b, a);
     
        // base case
        if (Math.Abs(b) < 0.001)
            return (float)a;
     
        else
            return (float)(gcd(b, a -
                Math.Floor(a / b) * b));
    }
     
    // Driver Function.
    public static void Main()
    {
        double a = 1.20, b = 22.5;
 
        Console.WriteLine(gcd(a, b));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

0.3