Convert given Decimal number into an irreducible Fraction - GeeksforGeeks

12 May, 2021
Given a decimal number as N, the task is to convert N into an equivalent irreducible fraction.
An irreducible fraction is a fraction in which numerator and denominator are co-primes i.e., they have no other common divisor other than 1. 
Examples:
Input: N = 4.50Output: 9/2 Explanation:9/2 in decimal is written as 4.5
Input: N = 0.75Output: 3/4Explanation:3/4 in decimal is written as 0.75
Approach: Follow the steps given below to solve the problem.
Fetch integral value and fractional part of the decimal number ‘n’.
Consider the precision value to be 109 to convert the fractional part of the decimal to an integral equivalent.
Calculate GCD of the integral equivalent of fractional part and precision value.
Calculate numerator by dividing the integral equivalent of fractional part by GCD value. Calculate the denominator by dividing the precision value by GCD value.
From the obtained mixed fraction, convert it into an improper fraction.
For example N = 4.50, integral value = 4  and  fractional part = 0.50            Consider precision value to be (109) that is precision value = 1000000000            Calculate GCD(0.50 *  109, 109) = 500000000            Calculate numerator = (0.50 * 10^9) / 500000000 = 1 and denominator = 10^9/ 500000000 = 2            Convert mixed fraction into improper fraction that is fraction = ((4 * 2) + 1) / 2 = 9/2  
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Recursive function to// return GCD of a and blong long gcd(long long a, long long b){    if (a == 0)        return b;    else if (b == 0)        return a;    if (a < b)        return gcd(a, b % a);    else        return gcd(b, a % b);} // Function to convert decimal to fractionvoid decimalToFraction(double number){    // Fetch integral value of the decimal    double intVal = floor(number);     // Fetch fractional part of the decimal    double fVal = number - intVal;     // Consider precision value to    // convert fractional part to    // integral equivalent    const long pVal = 1000000000;     // Calculate GCD of integral    // equivalent of fractional    // part and precision value    long long gcdVal        = gcd(round(fVal * pVal), pVal);     // Calculate num and deno    long long num        = round(fVal * pVal) / gcdVal;    long long deno = pVal / gcdVal;     // Print the fraction    cout << (intVal * deno) + num         << "/" << deno << endl;} // Driver Codeint main(){    double N = 4.5;     decimalToFraction(N);     return 0;}
// C implementation of the above approach#include <math.h>#include <stdio.h> int gcfFinder(int a, int b){ // gcf finder    int gcf = 1;    for (int i = 1; i <= a && i <= b; i++)    {        if (a % i == 0 && b % i == 0)        {            gcf = i;        }    }    return gcf;} int shortform(int* a, int* b){    for (int i = 2; i <= *a && i <= *b; i++)    {        if (*a % i == 0 && *b % i == 0)        {            *a = *a / i;            *b = *b / i;        }    }    return 0;} // Driver Codeint main(void){    // converting decimal into fraction.    double a = 4.50;     int c = 10000;    double b = (a - floor(a)) * c;    int d = (int)floor(a) * c + (int)(b + .5f);     while (1)    {        if (d % 10 == 0)        {            d = d / 10;            c = c / 10;        }        else            break;    }    int* i = &d;    int* j = &c;    int t = 0;    while (t != 1)    {        int gcf = gcfFinder(d, c);        if (gcf == 1)        {            printf("%d/%d\n", d, c);            t = 1;        }        else        {            shortform(i, j);        }    }    return 0;}// this code is contributed by harsh sinha username-// harshsinha03
// Java program for the above approachimport java.util.*; class GFG{     // Recursive function to// return GCD of a and bstatic long gcd(long a, long b){    if (a == 0)        return b;    else if (b == 0)        return a;    if (a < b)        return gcd(a, b % a);    else        return gcd(b, a % b);}     // Function to convert decimal to fractionstatic void decimalToFraction(double number){       // Fetch integral value of the decimal    double intVal = Math.floor(number);      // Fetch fractional part of the decimal    double fVal = number - intVal;      // Consider precision value to    // convert fractional part to    // integral equivalent    final long pVal = 1000000000;      // Calculate GCD of integral    // equivalent of fractional    // part and precision value    long gcdVal = gcd(Math.round(                      fVal * pVal), pVal);       // Calculate num and deno    long num = Math.round(fVal * pVal) / gcdVal;    long deno = pVal / gcdVal;      // Print the fraction    System.out.println((long)(intVal * deno) +                           num + "/" + deno);}   // Driver Codepublic static void main(String s[]){    double N = 4.5;    decimalToFraction(N);}   } // This code is contributed by rutvik_56
# Python3 program for the above approachfrom math import floor # Recursive function to# return GCD of a and bdef gcd(a, b):         if (a == 0):        return b    elif (b == 0):        return a    if (a < b):        return gcd(a, b % a)    else:        return gcd(b, a % b) # Function to convert decimal to fractiondef decimalToFraction(number):         # Fetch integral value of the decimal    intVal = floor(number)     # Fetch fractional part of the decimal    fVal = number - intVal     # Consider precision value to    # convert fractional part to    # integral equivalent    pVal = 1000000000     # Calculate GCD of integral    # equivalent of fractional    # part and precision value    gcdVal = gcd(round(fVal * pVal), pVal)     # Calculate num and deno    num= round(fVal * pVal) // gcdVal    deno = pVal // gcdVal     # Print the fraction    print((intVal * deno) + num, "/", deno) # Driver Codeif __name__ == '__main__':         N = 4.5     decimalToFraction(N) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{     // Recursive function to// return GCD of a and bstatic long gcd(long a, long b){    if (a == 0)        return b;    else if (b == 0)        return a;    if (a < b)        return gcd(a, b % a);    else        return gcd(b, a % b);}     // Function to convert decimal to fractionstatic void decimalToFraction(double number){     // Fetch integral value of the decimal    double intVal = Math.Floor(number);     // Fetch fractional part of the decimal    double fVal = number - intVal;     // Consider precision value to    // convert fractional part to    // integral equivalent    long pVal = 1000000000;     // Calculate GCD of integral    // equivalent of fractional    // part and precision value    long gcdVal = gcd((long)Math.Round(                    fVal * pVal), pVal);     // Calculate num and deno    long num = (long)Math.Round(fVal * pVal) / gcdVal;    long deno = pVal / gcdVal;     // Print the fraction    Console.WriteLine((long)(intVal * deno) +                          num + "/" + deno);} // Driver Codepublic static void Main(String []s){    double N = 4.5;         decimalToFraction(N);}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to implement// the above approach // Recursive function to// return GCD of a and bfunction gcd(a, b){    if (a == 0)        return b;    else if (b == 0)        return a;    if (a < b)        return gcd(a, b % a);    else        return gcd(b, a % b);}      // Function to convert decimal to fractionfunction decimalToFraction(number){        // Fetch letegral value of the decimal    let letVal = Math.floor(number);       // Fetch fractional part of the decimal    let fVal = number - letVal;       // Consider precision value to    // convert fractional part to    // letegral equivalent    let pVal = 1000000000;       // Calculate GCD of letegral    // equivalent of fractional    // part and precision value    let gcdVal = gcd(Math.round(                      fVal * pVal), pVal);        // Calculate num and deno    let num = Math.round(fVal * pVal) / gcdVal;    let deno = pVal / gcdVal;       // Print the fraction    document.write((letVal * deno) +                           num + "/" + deno);}            // Driver Code               let N = 4.5;    decimalToFraction(N); </script>
9/2
Time complexity: O(log min(a, b)) Auxiliary space: O(1)
mohit kumar 29
rutvik_56
princiraj1992
harshsinha03
avijitmondal1998
Fraction
GCD-LCM
Mathematical
Recursion
School Programming
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Recursion
Program for Sum of the digits of a given number
Backtracking | Introduction