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.
Example:
Input : 0.3, 0.9
Output : 0.3
Input : 0.48, 0.108
Output : 0.012
The simplest approach to solve this problem is :
a=1.20
b=22.5
Expressing each of the numbers without decimals as the product of primes we get:
120
2250
Now, H.C.F. of 120 and 2250 = 2*3*5=30
Therefore,the H.C.F. of 1.20 and 22.5=0.30
(taking 2 decimal places)
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.
C++
#include <bits/stdc++.h>
using namespace std;
double gcd( double a, double b)
{
if (a < b)
return gcd(b, a);
if ( fabs (b) < 0.001)
return a;
else
return (gcd(b, a - floor (a / b) * b));
}
int main()
{
double a = 1.20, b = 22.5;
cout << gcd(a, b);
return 0;
}
|
Java
import java.io.*;
class GFG {
static double gcd( double a, double b)
{
if (a < b)
return gcd(b, a);
if (Math.abs(b) < 0.001 )
return a;
else
return (gcd(b, a -
Math.floor(a / b) * b));
}
public static void main(String args[])
{
double a = 1.20 , b = 22.5 ;
System.out.printf( "%.1f" ,gcd(a, b));
}
}
|
Python
import math
def gcd(a,b) :
if (a < b) :
return gcd(b, a)
if ( abs (b) < 0.001 ) :
return a
else :
return (gcd(b, a - math.floor(a / b) * b))
a = 1.20
b = 22.5
print ( '{0:.1f}' . format (gcd(a, b)))
|
C#
using System;
class GFG {
static float gcd( double a, double b)
{
if (a < b)
return gcd(b, a);
if (Math.Abs(b) < 0.001)
return ( float )a;
else
return ( float )(gcd(b, a -
Math.Floor(a / b) * b));
}
public static void Main()
{
double a = 1.20, b = 22.5;
Console.WriteLine(gcd(a, b));
}
}
|
PHP
<?php
function gcd( $a , $b )
{
if ( $a < $b )
return gcd( $b , $a );
if ( abs ( $b ) < 0.001)
return $a ;
else
return (gcd( $b , $a -
floor ( $a / $b ) * $b ));
}
$a = 1.20;
$b = 22.5;
echo gcd( $a , $b );
?>
|
Javascript
<script>
function gcd(a , b)
{
if (a < b)
return gcd(b, a);
if (Math.abs(b) < 0.001)
return a;
else
return (gcd(b, a - Math.floor(a / b) * b));
}
var a = 1.20, b = 22.5;
document.write( gcd(a, b).toFixed(1));
</script>
|
Output:
0.3
Time Complexity: O(log n)
Auxiliary Space: O(log n)
Last Updated :
23 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...