Program to find GCD of floating point numbers

The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers.

Input  : 0.3, 0.9
Output : 0.3

Input  : 0.48, 0.108
Output : 0.012

The simplest approach to solve this problem is :

We can do this using the Euclidean algorithm. This algorithm indicates that if the smaller number is subtracted from a bigger number, GCD of two numbers doesn’t change.

// CPP code for finding the GCD of two floating
// numbers.
#include <bits/stdc++.h>
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;
        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;



Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar