Check if two given Rational Numbers are equal or not
Last Updated :
21 Oct, 2023
Given two strings S and T representing non-negative rational numbers, the task is to check if the values of S and T are equal or not. If found to be true, then print "YES". Otherwise, print "NO".
Note: Any rational number can be represented in one of the following three ways:
- <IntegerPart> (e.g. 0, 12, 123)
- <IntegerPart><.><NonRepeatingPart> (e.g. 0.5, 1., 2.12, 2.0001)
- <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> (e.g. 0.1(6), 0.9(9), 0.00(1212))
Examples:
Input: S = "0.(52)", T = "0.5(25)"
Output: YES
Explanation: The rational number "0.(52)" can be represented as 0.52525252... The rational number "0.5(25)" can be represented as 0.525252525.... Therefore, the required output is "YES".
Input: S = "0.9(9)", T = "1." Output: YES Explanation: The rational number "0.9(9)" can be represented as 0.999999999..., it is equal to 1. The rational number "1." can be represented as the number 1. Therefore, the required output is "YES".
Approach: The idea is to convert the rational numbers into fractions and then check if fractions of both the rational numbers are equal or not. If found to be true, then print "YES". Otherwise, print "NO". Following are the observations:
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets.
For example: 1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66) Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.
Any rational numbers can be converted into fractions based on the following observations:
Let x = 0.5(25) —> (1) Integer part = 0, Non-repeating part = 5, Repeating part = 25 Multiply both sides of equation (1) by 10 raised to the power of length of non-repeating part, i.e. 10 * x = 5.(25) —> (2) Multiply both sides of equation (1) by 10 raised to the power of (length of non-repeating part + length of repeating part), 1000 * x = 525.(25) —> (3) Subtract equation (2) from equation (3)
1000 * x - 10 * x = 525.(25)-5.(25)
990 * x = 520
? x = 520 / 990
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Fraction {
public:
long long p, q;
// Constructor function to initialize the object of the class
Fraction(long long p, long long q)
: p(p), q(q) {}
string ToString() {
return to_string(p) + "/" + to_string(q);
}
};
class Rational {
private:
string integer, nonRepeating, repeating;
// Constructor function to initialize the object of the class
Rational(string integer, string nonRepeating, string repeating)
: integer(integer), nonRepeating(nonRepeating), repeating(repeating) {}
public:
// Function to split the string into integer, repeating & non-repeating part
static Rational Parse(string s) {
// Split s into parts
vector<string> parts;
size_t startPos = 0;
size_t endPos = 0;
while ((endPos = s.find_first_of(".()]", startPos)) != string::npos) {
parts.push_back(s.substr(startPos, endPos - startPos));
startPos = endPos + 1;
}
if (startPos < s.length()) {
parts.push_back(s.substr(startPos, s.length() - startPos));
}
return Rational(
parts.size() >= 1 ? parts[0] : "",
parts.size() >= 2 ? parts[1] : "",
parts.size() >= 3 ? parts[2] : "");
}
// Function to convert the string into fraction
Fraction ToFraction() {
const long long a = TenPow(nonRepeating.length());
const long long i = stoll(integer + nonRepeating);
// If there is no repeating part, then form a new fraction of the form i/a
if (repeating.length() == 0) {
return Fraction(i, a);
} else {
// Otherwise
const long long b = TenPow(nonRepeating.length() + repeating.length());
const long long j = stoll(integer + nonRepeating + repeating);
return Fraction(j - i, b - a);
}
}
string ToString() {
return integer + "." + nonRepeating + "(" + repeating + ")";
}
static long long TenPow(int x) {
if (x < 0) {
throw invalid_argument("x must be non-negative");
}
long long r = 1;
while (--x >= 0) {
r *= 10;
}
return r;
}
};
class GFG {
public:
// Function to check if the string S and T are equal or not
static bool IsRationalEqual(string s, string t) {
// Stores the fractional part of s
const Fraction f1 = Rational::Parse(s).ToFraction();
// Stores the fractional part of t
const Fraction f2 = Rational::Parse(t).ToFraction();
// If the condition satisfies, return true; otherwise return false
return (f1.p * f2.q == f2.p * f1.q);
}
// Driver Code
static void Main() {
// Given S and T
const string S = "0.(52)";
const string T = "0.5(25)";
// Function Call
if (IsRationalEqual(S, T)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
};
int main() {
GFG::Main();
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to check if the string S and T
// are equal or not
public static boolean isRationalEqual(String s,
String t)
{
// Stores the fractional part of s
Fraction f1 = Rational.parse(s).toFraction();
// Stores the fractional part of t
Fraction f2 = Rational.parse(t).toFraction();
// If the condition satisfies, returns true
// otherwise return false
return f1.p * f2.q == f2.p * f1.q;
}
// Rational class having integer, non-repeating
// and repeating part of the number
public static class Rational {
private final String integer, nonRepeating,
repeating;
// Constructor function to initialize
// the object of the class
private Rational(String integer,
String nonRepeating,
String repeating)
{
// Stores integer part
this.integer = integer;
// Stores non repeating part
this.nonRepeating = nonRepeating;
// Stores repeating part
this.repeating = repeating;
}
// Function to split the string into
// integer, repeating & non-repeating part
public static Rational parse(String s)
{
// Split s into parts
String[] parts = s.split("[.()]");
return new Rational(
parts.length >= 1 ? parts[0] : "",
parts.length >= 2 ? parts[1] : "",
parts.length >= 3 ? parts[2] : "");
}
// Function to convert the string
// into fraction
public Fraction toFraction()
{
long a = tenpow(nonRepeating.length());
long i = Long.parseLong(integer + nonRepeating);
// If there is no repeating part, then
// form a new fraction of the form i/a
if (repeating.length() == 0) {
return new Fraction(i, a);
}
// Otherwise
else {
long b = tenpow(nonRepeating.length()
+ repeating.length());
long j = Long.parseLong(
integer + nonRepeating + repeating);
// Form the new Fraction and return
return new Fraction(j - i, b - a);
}
}
public String toString()
{
return String.format("%s.%s(%s)", integer,
nonRepeating, repeating);
}
}
// Fraction class having numerator as p
// and denominator as q
public static class Fraction {
private final long p, q;
// Constructor function to initialize
// the object of the class
private Fraction(long p, long q)
{
this.p = p;
this.q = q;
}
public String toString()
{
return String.format("%d/%d", p, q);
}
}
// Function to find 10 raised
// to power of x
public static long tenpow(int x)
{
assert x >= 0;
long r = 1;
while (--x >= 0) {
r *= 10;
}
return r;
}
// Driver Code
public static void main(String[] args)
{
// Given S and T
String S = "0.(52)", T = "0.5(25)";
// Function Call
if (isRationalEqual(S, T)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
// Print result
}
}
Python3
import re
class GFG:
# Function to check if the string S and T are equal or not
@staticmethod
def isRationalEqual(s, t):
# Stores the fractional part of s
f1 = Rational.parse(s).toFraction()
# Stores the fractional part of t
f2 = Rational.parse(t).toFraction()
# If the condition satisfies, returns true
# otherwise return false
return f1.p * f2.q == f2.p * f1.q
@staticmethod
def tenpow(x):
if x < 0:
return None
r = 1
while x >= 0:
r *= 10
x -= 1
return r
# Driver Code
@staticmethod
def main():
# Given S and T
S = '0.(52)'
T = '0.5(25)'
# Function Call
if GFG.isRationalEqual(S, T):
print('YES')
else:
print('NO')
# Rational class having integer, non-repeating
# and repeating part of the number
class Rational:
# Constructor function to initialize
# the object of the class
def __init__(self, integer, nonRepeating, repeating):
self.integer = integer
self.nonRepeating = nonRepeating
self.repeating = repeating
# Function to split the string into
# integer, repeating & non-repeating part
@staticmethod
def parse(s):
# Split s into parts
parts = re.split(r'[.()]', s)
return Rational(
parts[0] if len(parts) >= 1 else '',
parts[1] if len(parts) >= 2 else '',
parts[2] if len(parts) >= 3 else '',
)
# Function to convert the string into fraction
def toFraction(self):
a = GFG.tenpow(len(self.nonRepeating))
i = int(self.integer + self.nonRepeating)
# If there is no repeating part, then
# form a new fraction of the form i/a
if len(self.repeating) == 0:
return Fraction(i, a)
else:
# Otherwise
b = GFG.tenpow(len(self.nonRepeating) + len(self.repeating))
j = int(self.integer + self.nonRepeating + self.repeating)
return Fraction(j - i, b - a)
def __str__(self):
return f'{self.integer}.{self.nonRepeating}({self.repeating})'
# Fraction class having numerator as p
# and denominator as q
class Fraction:
# Constructor function to initialize
# the object of the class
def __init__(self, p, q):
self.p = p
self.q = q
def __str__(self):
return f'{self.p}/{self.q}'
GFG.main()
C#
using System;
class GFG
{
// Function to check if the string S and T
// are equal or not
public static bool IsRationalEqual(string s, string t)
{
// Stores the fractional part of s
Fraction f1 = Rational.Parse(s).ToFraction();
// Stores the fractional part of t
Fraction f2 = Rational.Parse(t).ToFraction();
// If the condition satisfies, returns true
// otherwise return false
return f1.p * f2.q == f2.p * f1.q;
}
// Rational class having integer, non-repeating
// and repeating part of the number
public class Rational
{
private readonly string integer, nonRepeating, repeating;
// Constructor function to initialize
// the object of the class
private Rational(string integer, string nonRepeating, string repeating)
{
// Stores integer part
this.integer = integer;
// Stores non-repeating part
this.nonRepeating = nonRepeating;
// Stores repeating part
this.repeating = repeating;
}
// Function to split the string into
// integer, repeating & non-repeating part
public static Rational Parse(string s)
{
// Split s into parts
string[] parts = s.Split(new char[] { '.', '(', ')' });
return new Rational(
parts.Length >= 1 ? parts[0] : "",
parts.Length >= 2 ? parts[1] : "",
parts.Length >= 3 ? parts[2] : "");
}
// Function to convert the string
// into fraction
public Fraction ToFraction()
{
long a = TenPow(nonRepeating.Length);
long i = long.Parse(integer + nonRepeating);
// If there is no repeating part, then
// form a new fraction of the form i/a
if (repeating.Length == 0)
{
return new Fraction(i, a);
}
// Otherwise
else
{
long b = TenPow(nonRepeating.Length + repeating.Length);
long j = long.Parse(integer + nonRepeating + repeating);
// Form the new Fraction and return
return new Fraction(j - i, b - a);
}
}
public override string ToString()
{
return $"{integer}.{nonRepeating}({repeating})";
}
}
// Fraction class having numerator as p
// and denominator as q
public class Fraction
{
public long p, q;
// Constructor function to initialize
// the object of the class
public Fraction(long p, long q)
{
this.p = p;
this.q = q;
}
public override string ToString()
{
return $"{p}/{q}";
}
}
// Function to find 10 raised
// to power of x
public static long TenPow(int x)
{
if (x < 0)
{
throw new ArgumentException("x must be non-negative");
}
long r = 1;
while (--x >= 0)
{
r *= 10;
}
return r;
}
// Driver Code
public static void Main(string[] args)
{
// Given S and T
string S = "0.(52)", T = "0.5(25)";
// Function Call
if (IsRationalEqual(S, T))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
// This code is contributed by Dwaipayan Bandyopadhyay
JavaScript
// JavaScript program to implement
// the above approach
class GFG {
// Function to check if the string S and T
// are equal or not
static isRationalEqual(s, t) {
// Stores the fractional part of s
const f1 = Rational.parse(s).toFraction();
// Stores the fractional part of t
const f2 = Rational.parse(t).toFraction();
// If the condition satisfies, returns true
// otherwise return false
return f1.p * f2.q === f2.p * f1.q;
}
static tenpow(x) {
if (x < 0) return undefined;
let r = 1;
while (--x >= 0) {
r *= 10;
}
return r;
}
// Driver Code
static main() {
// Given S and T
const S = '0.(52)';
const T = '0.5(25)';
// Function Call
if (GFG.isRationalEqual(S, T)) {
console.log('YES');
} else {
console.log('NO');
}
}
}
// Rational class having integer, non-repeating
// and repeating part of the number
class Rational {
// Constructor function to initialize
// the object of the class
constructor(integer, nonRepeating, repeating) {
this.integer = integer;
this.nonRepeating = nonRepeating;
this.repeating = repeating;
}
// Function to split the string into
// integer, repeating & non-repeating part
static parse(s) {
// Split s into parts
const parts = s.split(/[.()]/);
return new Rational(
parts.length >= 1 ? parts[0] : '',
parts.length >= 2 ? parts[1] : '',
parts.length >= 3 ? parts[2] : '',
);
}
// Function to convert the string
// into fraction
toFraction() {
const a = GFG.tenpow(this.nonRepeating.length);
const i = parseInt(this.integer + this.nonRepeating);
// If there is no repeating part, then
// form a new fraction of the form i/a
if (this.repeating.length === 0) {
return new Fraction(i, a);
} else {
// Otherwise
const b = GFG.tenpow(this.nonRepeating.length + this.repeating.length);
const j = parseInt(this.integer + this.nonRepeating + this.repeating);
return new Fraction(j - i, b - a);
}
}
toString() {
return `${this.integer}.${this.nonRepeating}(${this.repeating})`;
}
}
// Fraction class having numerator as p
// and denominator as q
class Fraction {
// Constructor function to initialize
// the object of the class
constructor(p, q) {
this.p = p;
this.q = q;
}
toString() {
return `${this.p}/${this.q}`;
}
}
GFG.main();
// Contributed by adityasha4x71
Time Complexity: O(N), where N is the maximum length of S and T Auxiliary Space: O(1)
Similar Reads
Check if two numbers have same number of digits Given two integers A and B, the task is to check whether both the numbers have an equal number of digits.Examples: Input: A = 12, B = 1 Output: NoInput: A = 20, B = 99 Output: Yes Approach: While both the numbers are > 0, keep dividing both the numbers by 10. Finally, check if both the numbers ar
3 min read
Check if two numbers are equal without using comparison operators The following are not allowed to use Comparison Operators String function Examples: Input : num1 = 1233, num2 =1233Output : Same Input : num1 = 223, num2 = 233Output : Not Same Method 1: The idea is to use the XOR operator. XOR of two numbers is 0 if the numbers are the same, otherwise non-zero. C++
5 min read
Check if it is possible to make given two numbers equal or not by changing 1 bit or 2 bits once Given two positive integers A and B, perform one of the following operations only once to make the numbers equal. Change the ith bit of a number to 0 or 1Change the ith bit to 0 or 1 in A and jth bit to 0 or 1 in B If itâs possible to make the numbers equal, then print "Yes". Otherwise, print "No".
9 min read
Division of Rational Numbers Rational numbers are numbers that can be expressed as a fraction of two integers, where the denominator is not zero. Some examples of rational numbers are 1/2, -3/2, 5, etc. 5 is whole number which can be written as 5/1 in the form of a fraction. Hence, we can say that a whole number is also a ratio
6 min read
Rational Numbers Between Two Rational Numbers | Class 8 Maths Real numbers are categorized into rational and irrational numbers respectively. Given two integers p and q, a rational number is of the form p/q, where q > 0. A special case arises when q=1 and the rational number simply becomes an integer. Hence, all integers are rational numbers, equal to p. Th
6 min read