Convert given Float value to equivalent Fraction
Given a floating-point number in the form of a string N, the task is to convert the given floating-point number into fractions.
Enclosed sequence of digits in “()” in the floating-point representation expresses recurrence in the decimal representation.
For example, 1.(6) represents 1.666….
Examples:
Input: N = “1.5”
Output: 3 / 2
Explanation:
The value of 3 / 2 will be equal to 1.5Input: N = “1.(6)”
Output: 5 / 3
Explanation:
The value of 5 / 3 will be equal to 1.666… which is represented as 1.(6).
Approach: The idea is to use the Greatest Common Divisor of two numbers and some mathematical equations to solve the problem. Follow the below steps to solve the problem:
- Let there be x numbers after the decimal except for the recurring sequence.
- If there is no recurring sequence then multiply the given number with 10x and let the GCD of 10x and the resultant number be g. Print resultant divided by g as the numerator and 10x divided by g as the denominator.
For example, if N = “1.5” then x = 1.
Multiplying N with 10, the resultant will be 15 and the GCD of 10 and 15 is 3.
Therefore, print 15/3 = 5 as the numerator and 10/5 as the denominator.
- If the recurrence sequence is present, then multiply N with 10x. For example, if N = 23.98(231) multiply it with N*(102).
- Let the total number of digits in a sequence be y. For 102*N = 2398.(231), y becomes 3.
- Multiply 10y with N*10x. For 102*N = 2398.(231), multiply it with 103 i.e., 102*N*103 = 2398231.(231).
- Now, subtract, N*10y+x with N*10x and let the result be M. For the above example, 102*N*(103-1) = 2395833.
- Therefore, N = M / ((10x)*(10y – 1)). For the above example, N = 2395833 / 999000.
- Find the GCD of M and ((10x)*(10y – 1)) and print M / gcd as the numerator and ((10x)*(10y – 1)) as the denominator.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Function to convert the floating// values into fractionvoid findFraction(string s){ // Initialize variables string be_deci = "", af_deci = "", reccu = ""; bool x = true, y = false, z = false; // Traverse the floating string for (int i = 0; i < s.size(); ++i) { // Check if decimal part exist if (s[i] == '.') { x = false; y = true; continue; } // Check if recurrence // sequence exist if (s[i] == '(') { z = true; y = false; continue; } // Retrieve decimal part // and recurrence re sequence if (x) be_deci += s[i]; if (y) af_deci += s[i]; if (z) { // Traverse the string for (; i < s.size() && s[i] != ')'; ++i) reccu += s[i]; break; } } // Convert string to integer int num_be_deci = stoi(be_deci); int num_af_deci = 0; // If no recurrence sequence exist if (af_deci.size() != 0) num_af_deci = stoi(af_deci); // Initialize numerator & denominator int numr = num_be_deci * pow(10, af_deci.size()) + num_af_deci; int deno = pow(10, af_deci.size()); // No reccuring term if (reccu.size() == 0) { int gd = __gcd(numr, deno); // Print the result cout << numr / gd << " / " << deno / gd; } // If reccuring term exist else { // Convert reccuring term to integer int reccu_num = stoi(reccu); // reccu.size() is num of // digit in reccur term int numr1 = numr * pow(10, reccu.size()) + reccu_num; int deno1 = deno * pow(10, reccu.size()); // eq 2 - eq 1 int res_numr = numr1 - numr, res_deno = deno1 - deno; int gd = __gcd(res_numr, res_deno); // Print the result cout << res_numr / gd << " / " << res_deno / gd; }}// Driver Codeint main(){ // Given string str string str = "23.98(231)"; // Function Call findFraction(str); return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{ // Recursive function to return// gcd of a and b static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); }// Function to convert the floating// values into fractionstatic void findFraction(String s){ // Initialize variables String be_deci = "", af_deci = "", reccu = ""; boolean x = true, y = false, z = false; // Traverse the floating String for(int i = 0; i < s.length(); ++i) { // Check if decimal part exist if (s.charAt(i) == '.') { x = false; y = true; continue; } // Check if recurrence // sequence exist if (s.charAt(i) == '(') { z = true; y = false; continue; } // Retrieve decimal part // and recurrence resquence if (x) be_deci += s.charAt(i); if (y) af_deci += s.charAt(i); if (z) { // Traverse the String for(; i < s.length() && s.charAt(i) != ')'; ++i) reccu += s.charAt(i); break; } } // Convert String to integer int num_be_deci = Integer.valueOf(be_deci); int num_af_deci = 0; // If no recurrence sequence exist if (af_deci.length() != 0) num_af_deci = Integer.valueOf(af_deci); // Initialize numerator & denominator int numr = num_be_deci * (int)Math.pow(10, af_deci.length()) + num_af_deci; int deno = (int)Math.pow(10, af_deci.length()); // No reccuring term if (reccu.length() == 0) { int gd = __gcd(numr, deno); // Print the result System.out.print(numr / gd + " / " + deno / gd); } // If reccuring term exist else { // Convert reccuring term to integer int reccu_num = Integer.valueOf(reccu); // reccu.size() is num of // digit in reccur term int numr1 = numr * (int)Math.pow(10, reccu.length()) + reccu_num; int deno1 = deno * (int) Math.pow( 10, reccu.length()); // eq 2 - eq 1 int res_numr = numr1 - numr, res_deno = deno1 - deno; int gd = __gcd(res_numr, res_deno); // Print the result System.out.print(res_numr / gd + " / " + res_deno / gd); }}// Driver Codepublic static void main(String[] args){ // Given String str String str = "23.98(231)"; // Function Call findFraction(str);}}// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approachfrom math import gcd# Function to convert the floating# values into fractiondef findFraction(s): # Initialize variables be_deci = "" af_deci = "" reccu = "" x = True y = False z = False # Traverse the floating string for i in range(len(s)): # Check if decimal part exist if (s[i] == '.'): x = False y = True continue # Check if recurrence # sequence exist if (s[i] == '('): z = True y = False continue # Retrieve decimal part # and recurrence resquence if (x): be_deci += s[i] if (y): af_deci += s[i] if (z): # Traverse the string while i < len(s) and s[i] != ')': reccu += s[i] i += 1 break # Convert to integer num_be_deci = int(be_deci) num_af_deci = 0 # If no recurrence sequence exist if len(af_deci) != 0: num_af_deci = int(af_deci) # Initialize numerator & denominator numr = (num_be_deci * pow(10, len(af_deci)) + num_af_deci) deno = pow(10, len(af_deci)) # No reccuring term if len(reccu) == 0: gd = gcd(numr, deno) # Print the result print(numr // gd, "/", deno // gd) # If reccuring term exist else: # Convert reccuring term to integer reccu_num = int(reccu) # reccu.size() is num of # digit in reccur term numr1 = (numr * pow(10, len(reccu)) + reccu_num) deno1 = deno * pow(10, len(reccu)) # eq 2 - eq 1 res_numr = numr1 - numr res_deno = deno1 - deno gd = gcd(res_numr, res_deno) # Print the result print(res_numr // gd, " / ", res_deno // gd)# Driver Codeif __name__ == '__main__': # Given str str = "23.98(231)" # Function Call findFraction(str) # This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;class GFG{ // Recursive function to return// gcd of a and b static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); }// Function to convert the floating// values into fractionstatic void findFraction(String s){ // Initialize variables String be_deci = "", af_deci = "", reccu = ""; bool x = true, y = false, z = false; // Traverse the floating String for(int i = 0; i < s.Length; ++i) { // Check if decimal part exist if (s[i] == '.') { x = false; y = true; continue; } // Check if recurrence // sequence exist if (s[i] == '(') { z = true; y = false; continue; } // Retrieve decimal part // and recurrence resquence if (x) be_deci += s[i]; if (y) af_deci += s[i]; if (z) { // Traverse the String for(; i < s.Length && s[i] != ')'; ++i) reccu += s[i]; break; } } // Convert String to integer int num_be_deci = Int32.Parse(be_deci); int num_af_deci = 0; // If no recurrence sequence exist if (af_deci.Length != 0) num_af_deci = Int32.Parse(af_deci); // Initialize numerator & denominator int numr = num_be_deci * (int)Math.Pow(10, af_deci.Length) + num_af_deci; int deno = (int)Math.Pow(10, af_deci.Length); // No reccuring term if (reccu.Length == 0) { int gd = __gcd(numr, deno); // Print the result Console.Write(numr / gd + " / " + deno / gd); } // If reccuring term exist else { // Convert reccuring term to integer int reccu_num = Int32.Parse(reccu); // reccu.Count is num of // digit in reccur term int numr1 = numr * (int)Math.Pow(10, reccu.Length) + reccu_num; int deno1 = deno * (int)Math.Pow( 10, reccu.Length); // eq 2 - eq 1 int res_numr = numr1 - numr, res_deno = deno1 - deno; int gd = __gcd(res_numr, res_deno); // Print the result Console.Write(res_numr / gd + " / " + res_deno / gd); }}// Driver Codepublic static void Main(String[] args){ // Given String str String str = "23.98(231)"; // Function Call findFraction(str);}}// This code is contributed by Amit Katiyar |
Javascript
<script>// Javascript program for the above approach// Recursive function to return// gcd of a and bfunction __gcd(a,b){ return b == 0 ? a : __gcd(b, a % b); }// Function to convert the floating// values into fractionfunction findFraction(s){ // Initialize variables let be_deci = "", af_deci = "", reccu = ""; let x = true, y = false, z = false; // Traverse the floating String for(let i = 0; i < s.length; ++i) { // Check if decimal part exist if (s[i] == '.') { x = false; y = true; continue; } // Check if recurrence // sequence exist if (s[i] == '(') { z = true; y = false; continue; } // Retrieve decimal part // and recurrence resquence if (x) be_deci += s[i]; if (y) af_deci += s[i]; if (z) { // Traverse the String for(; i < s.length && s[i] != ')'; ++i) reccu += s[i]; break; } } // Convert String to integer let num_be_deci = parseInt(be_deci); let num_af_deci = 0; // If no recurrence sequence exist if (af_deci.length != 0) num_af_deci = parseInt(af_deci); // Initialize numerator & denominator let numr = num_be_deci * Math.pow(10, af_deci.length) + num_af_deci; let deno = Math.pow(10, af_deci.length); // No reccuring term if (reccu.length == 0) { let gd = __gcd(numr, deno); // Print the result document.write(numr / gd + " / " + deno / gd); } // If reccuring term exist else { // Convert reccuring term to integer let reccu_num = parseInt(reccu); // reccu.size() is num of // digit in reccur term let numr1 = numr * Math.pow(10, reccu.length) + reccu_num; let deno1 = deno * Math.pow( 10, reccu.length); // eq 2 - eq 1 let res_numr = numr1 - numr, res_deno = deno1 - deno; let gd = __gcd(res_numr, res_deno); // Print the result document.write(res_numr / gd + " / " + res_deno / gd); }}// Driver Code// Given String strlet str = "23.98(231)";// Function CallfindFraction(str);// This code is contributed by unknown2108</script> |
798611 / 33300
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



