Split the fraction into sum of multiple fractions having numerator as 1
Last Updated :
23 Aug, 2021
Given two positive integers N and D representing a fraction as N/D, the task is to split the fraction into the sum of multiple fractions having numerator as 1.
Examples:
Input: n = 4, d = 5
Output: 1/2, 1/4, 1/20
Explanation: 1/2 + 1/4 + 1/20 = 4/5
Input: n = 15, d = 16
Output: 1/2, 1/3, 1/10, 1/240
Approach: The idea is that all positive fractions of the form n/d can be written as a sum of distinct unit fractions. The answer can be found by removing largest unit fraction 1/x till the fraction reaches to zero where x can be found as ceil(d/n). After finding the unit fraction, update the fraction to n/d – 1/x so n changes to nx-d and d changes to dx at each step.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> FractionSplit( long long n, long long d)
{
vector<string> UnitFactions;
while (n > 0) {
long long x = (d + n - 1) / n;
string s = "1/" + to_string(x);
UnitFactions.push_back(s);
n = n * x - d;
d = d * x;
}
return UnitFactions;
}
int main()
{
long long n = 13, d = 18;
auto res = FractionSplit(n, d);
for (string s : res)
cout << s << ", " ;
return 0;
}
|
Java
import java.util.Vector;
public class GFG {
static Vector<String> FractionSplit( long n, long d)
{
Vector<String> UnitFactions = new Vector<>();
while (n > 0 ) {
long x = (d + n - 1 ) / n;
String s = "1/" + String.valueOf(x);
UnitFactions.add(s);
n = n * x - d;
d = d * x;
}
return UnitFactions;
}
public static void main(String[] args)
{
long n = 13 , d = 18 ;
Vector<String> res = FractionSplit(n, d);
for (String s : res)
System.out.print(s + ", " );
}
}
|
Python3
def FractionSplit(n, d):
UnitFactions = []
while (n > 0 ):
x = (d + n - 1 ) / / n
s = "1/" + str (x)
UnitFactions.append(s);
n = n * x - d;
d = d * x
return UnitFactions;
n = 13 ;
d = 18 ;
res = FractionSplit(n, d);
for s in res:
print (s + ", " , end = " " );
|
C#
using System;
using System.Collections.Generic;
class GFG{
static List< string > FractionSplit( long n, long d)
{
List< string > UnitFactions = new List< string >();
while (n > 0)
{
long x = (d + n - 1) / n;
string s = "1/" + x.ToString();
UnitFactions.Add(s);
n = n * x - d;
d = d * x;
}
return UnitFactions;
}
public static void Main( string [] args)
{
long n = 13, d = 18;
List< string > res = FractionSplit(n, d);
foreach ( string s in res)
Console.Write(s + ", " );
}
}
|
Javascript
<script>
function FractionSplit(n, d) {
let UnitFactions = [];
while (n > 0) {
let x = Math.floor((d + n - 1) / n);
let s = "1/" + String(x);
UnitFactions.push(s);
n = n * x - d;
d = d * x;
}
return UnitFactions;
}
let n = 13, d = 18;
let res = FractionSplit(n, d);
for (let s of res)
document.write(s + ", " );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...