Convert given Decimal number into an irreducible Fraction
Last Updated :
23 Dec, 2023
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.50
Output: 9/2
Explanation:
9/2 in decimal is written as 4.5
Input: N = 0.75
Output: 3/4
Explanation:
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++
#include <bits/stdc++.h>
using namespace std;
long 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);
}
void decimalToFraction( double number)
{
double intVal = floor (number);
double fVal = number - intVal;
const long pVal = 1000000000;
long long gcdVal
= gcd(round(fVal * pVal), pVal);
long long num
= round(fVal * pVal) / gcdVal;
long long deno = pVal / gcdVal;
cout << (intVal * deno) + num
<< "/" << deno << endl;
}
int main()
{
double N = 4.5;
decimalToFraction(N);
return 0;
}
|
C
#include <math.h>
#include <stdio.h>
int gcfFinder( int a, int b)
{
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;
}
int main( void )
{
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;
}
|
Java
import java.util.*;
class GFG{
static 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);
}
static void decimalToFraction( double number)
{
double intVal = Math.floor(number);
double fVal = number - intVal;
final long pVal = 1000000000 ;
long gcdVal = gcd(Math.round(
fVal * pVal), pVal);
long num = Math.round(fVal * pVal) / gcdVal;
long deno = pVal / gcdVal;
System.out.println(( long )(intVal * deno) +
num + "/" + deno);
}
public static void main(String s[])
{
double N = 4.5 ;
decimalToFraction(N);
}
}
|
Python3
from math import floor
def 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)
def decimalToFraction(number):
intVal = floor(number)
fVal = number - intVal
pVal = 1000000000
gcdVal = gcd( round (fVal * pVal), pVal)
num = round (fVal * pVal) / / gcdVal
deno = pVal / / gcdVal
print ((intVal * deno) + num, "/" , deno)
if __name__ = = '__main__' :
N = 4.5
decimalToFraction(N)
|
C#
using System;
class GFG{
static 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);
}
static void decimalToFraction( double number)
{
double intVal = Math.Floor(number);
double fVal = number - intVal;
long pVal = 1000000000;
long gcdVal = gcd(( long )Math.Round(
fVal * pVal), pVal);
long num = ( long )Math.Round(fVal * pVal) / gcdVal;
long deno = pVal / gcdVal;
Console.WriteLine(( long )(intVal * deno) +
num + "/" + deno);
}
public static void Main(String []s)
{
double N = 4.5;
decimalToFraction(N);
}
}
|
Javascript
<script>
function 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 decimalToFraction(number)
{
let letVal = Math.floor(number);
let fVal = number - letVal;
let pVal = 1000000000;
let gcdVal = gcd(Math.round(
fVal * pVal), pVal);
let num = Math.round(fVal * pVal) / gcdVal;
let deno = pVal / gcdVal;
document.write((letVal * deno) +
num + "/" + deno);
}
let N = 4.5;
decimalToFraction(N);
</script>
|
Time complexity: O(log min(a, b))
Auxiliary space: O(1)
Approach 2: Follow the steps given below to solve the problem.
For larger decimal values the float function automatically rounds off the input resulting in an incorrect response
Using inbuilt python libraries doesn’t round off the input for example for the below input the decimal value the code above rounds off the input
- Import library Decimal to convert a string input into decimal
- Import library Fraction to convert a Decimal input into a fraction
- Now convert the fraction into the string and give the output
For example N = “123456789.25252525”
Decimal(N) takes string input and converts it into decimal value = 123456789.25252525
Now we convert the fraction into string using type casting str(493827157010101/4000000)
result “493827157010101/4000000”
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
#include <cmath>
long long gcd( long long a, long long b) {
return b == 0 ? a : gcd(b, a % b);
}
void decimalToFraction( const std::string &number) {
double decimal = std::stod(number);
int scale = std::to_string(decimal).length() - number.find( '.' ) - 1;
long long denominator = std:: pow (10, scale);
long long numerator = decimal * denominator;
long long commonDivisor = gcd(numerator, denominator);
numerator /= commonDivisor;
denominator /= commonDivisor;
std::cout << numerator << "/" << denominator << std::endl;
}
int main() {
std::string N = "123456789.25252525" ;
decimalToFraction(N);
return 0;
}
|
Java
import java.math.BigDecimal;
import java.math.BigInteger;
public class DecimalToFraction {
public static void main(String[] args) {
String N = "123456789.25252525" ;
decimalToFraction(N);
}
public static void decimalToFraction(String number) {
BigDecimal decimal = new BigDecimal(number);
BigInteger numerator = decimal.unscaledValue();
int scale = decimal.scale();
BigInteger denominator = BigInteger.TEN.pow(scale);
BigInteger gcd = numerator.gcd(denominator);
numerator = numerator.divide(gcd);
denominator = denominator.divide(gcd);
System.out.println(numerator + "/" + denominator);
}
}
|
Python3
from decimal import Decimal
from fractions import Fraction
def decimalToFraction(number):
f = Fraction(Decimal( str (number)))
print ( str (f))
if __name__ = = '__main__' :
N = "123456789.25252525"
decimalToFraction(N)
|
C#
using System;
class DecimalToFraction {
static long Gcd( long a, long b)
{
return b == 0 ? a : Gcd(b, a % b);
}
static void ConvertDecimalToFraction( string number)
{
decimal decimalNumber = decimal .Parse(number);
int scale = number.Length - number.IndexOf( '.' ) - 1;
long denominator = ( long )Math.Pow(10, scale);
long numerator
= ( long )(decimalNumber * denominator);
long commonDivisor = Gcd(numerator, denominator);
numerator /= commonDivisor;
denominator /= commonDivisor;
Console.WriteLine(numerator + "/" + denominator);
}
static void Main()
{
string N = "123456789.25252525" ;
ConvertDecimalToFraction(N);
}
}
|
Javascript
const Decimal = require( 'decimal.js' );
const { Fraction } = require( 'fractions' );
function decimalToFraction(number) {
const f = new Fraction( new Decimal(String(number)));
console.log(String(f));
}
const N = "123456789.25252525" ;
decimalToFraction(N);
|
Output
493827157010101/4000000
Time complexity: O(k + log n)
Auxiliary space: O(1)
Explanation:
The time complexity of the decimalToFraction function depends on the length of the input number and the efficiency of the Fraction constructor. In this case, the input number is converted to a Decimal object using the Decimal constructor, which has a time complexity of O(k), where k is the number of digits in the input number. Then, the Fraction constructor is called with the Decimal object, which has a time complexity of O(log n), where n is the value of the input Decimal object. Therefore, the overall time complexity of decimalToFraction is O(k + log n).
The auxiliary space complexity of the decimalToFraction function is O(1), as it only uses a constant amount of additional memory to store the Fraction object and its string representation of it.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...