Open In App

Binary Search for Rational Numbers without using floating point arithmetic

Last Updated : 21 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A rational is represented as p/qb, for example 2/3. Given a sorted array of rational numbers, how to search an element using Binary Search. Use of floating-point arithmetic is not allowed.

Example:  

Input:  arr[] = {1/5, 2/3, 3/2, 13/2}
        x = 3/2
Output: Found at index 2

We strongly recommend you to minimize your browser and try this yourself first.
To compare two rational numbers p/q and r/s, we can compare p*s with q*r. 

C++




// C++ program for Binary Search for
// Rational Numbers without using
// floating point arithmetic
#include <iostream>
using namespace std;
 
struct Rational
{
    int p;
    int q;
};
 
// Utility function to compare two
// Rational numbers 'a' and 'b'.
// It returns
// 0 --> When 'a' and 'b' are same
// 1 --> When 'a' is greater
//-1 --> When 'b' is greater
int compare(struct Rational a, struct Rational b)
{
     
    // If a/b == c/d then a*d = b*c:
    // method to ignore division
    if (a.p * b.q == a.q * b.p)
        return 0;
    if (a.p * b.q > a.q * b.p)
        return 1;
         
    return -1;
}
 
// Returns index of x in arr[l..r] if
// it is present, else returns -1. It
// mainly uses Binary Search.
int binarySearch(struct Rational arr[], int l, int r,
                 struct Rational x)
{
    if (r >= l)
    {
        int mid = l + (r - l) / 2;
         
        // If the element is present at the middle itself
        if (compare(arr[mid], x) == 0)
            return mid;
         
        // If element is smaller than mid, then it can
        // only be present in left subarray
        if (compare(arr[mid], x) > 0)
            return binarySearch(arr, l, mid - 1, x);
         
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
    return -1;
}
 
// Driver code
int main()
{
    struct Rational arr[] = { { 1, 5 }, { 2, 3 },
                              { 3, 2 }, { 13, 2 } };
    struct Rational x = { 3, 2 };
     
    int n = sizeof(arr) / sizeof(arr[0]);
     
    cout << "Element found at index "
         << binarySearch(arr, 0, n - 1, x);
}
 
// This code is contributed by shivanisinghss2110


C




// C program for Binary Search for Rational Numbers
// without using floating point arithmetic
#include <stdio.h>
 
struct Rational
{
    int p;
    int q;
};
 
// Utility function to compare two Rational numbers
// 'a' and 'b'. It returns
// 0 --> When 'a' and 'b' are same
// 1 --> When 'a' is greater
//-1 --> When 'b' is greater
int compare(struct Rational a, struct Rational b)
{
    // If a/b == c/d  then  a*d = b*c:
    // method to ignore division
    if (a.p * b.q == a.q * b.p)
        return 0;
    if (a.p * b.q > a.q * b.p)
        return 1;
    return -1;
}
 
// Returns index of x in arr[l..r] if it is present, else
// returns -1. It mainly uses Binary Search.
int binarySearch(struct Rational arr[], int l, int r,
                 struct Rational x)
{
   if (r >= l)
   {
        int mid = l + (r - l)/2;
 
        // If the element is present at the middle itself
        if (compare(arr[mid], x) == 0)  return mid;
 
        // If element is smaller than mid, then it can
        // only be present in left subarray
        if (compare(arr[mid], x) > 0)
            return binarySearch(arr, l, mid-1, x);
 
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid+1, r, x);
   }
 
   return -1;
}
 
// Driver method
int main()
{
    struct Rational arr[] = {{1, 5}, {2, 3}, {3, 2}, {13, 2}};
    struct Rational x = {3, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("Element found at index %d",
            binarySearch(arr, 0, n-1, x));
}


Java




// Java program for Binary Search for Rational Numbers
// without using floating point arithmetic
class GFG
{
 
static class Rational
{
    int p;
    int q;
 
    public Rational(int p, int q)
    {
        this.p = p;
        this.q = q;
    }
     
};
 
// Utility function to compare two Rational numbers
// 'a' and 'b'. It returns
// 0 -. When 'a' and 'b' are same
// 1 -. When 'a' is greater
//-1 -. When 'b' is greater
static int compare(Rational a, Rational b)
{
    // If a/b == c/d then a*d = b*c:
    // method to ignore division
    if (a.p * b.q == a.q * b.p)
        return 0;
    if (a.p * b.q > a.q * b.p)
        return 1;
    return -1;
}
 
// Returns index of x in arr[l..r] if it is present, else
// returns -1. It mainly uses Binary Search.
static int binarySearch(Rational arr[], int l, int r,
                Rational x)
{
     
    if (r >= l)
    {
        int mid = l + (r - l)/2;
 
        // If the element is present at the middle itself
        if (compare(arr[mid], x) == 0) return mid;
 
        // If element is smaller than mid, then it can
        // only be present in left subarray
        if (compare(arr[mid], x) > 0)
            return binarySearch(arr, l, mid - 1, x);
 
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
 
return -1;
}
 
// Driver method
public static void main(String[] args)
{
    Rational arr[] = {new Rational(1, 5),
                        new Rational(2, 3),
                        new Rational(3, 2),
                        new Rational(13, 2)};
    Rational x = new Rational(3, 2);
    int n = arr.length;
    System.out.printf("Element found at index %d",
            binarySearch(arr, 0, n - 1, x));
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program for Binary Search
# for Rational Numbers without
# using floating point arithmetic
class Rational:
     
    def __init__(self, a = 0, b = 0):
         
        self.p = a
        self.q = b
 
# Utility function to compare two
# Rational numbers 'a' and 'b'.
# It returns
# 0 --> When 'a' and 'b' are same
# 1 --> When 'a' is greater
#-1 --> When 'b' is greater
def compare(a: Rational, b: Rational) -> int:
 
    # If a/b == c/d  then  a*d = b*c:
    # method to ignore division
    if (a.p * b.q == a.q * b.p):
        return 0
    if (a.p * b.q > a.q * b.p):
        return 1
         
    return -1
 
# Returns index of x in arr[l..r] if
# it is present, else returns -1. It
# mainly uses Binary Search.
def binarySearch(arr: list, l: int,
                   r: int, x: Rational) -> int:
 
    if (r >= l):
 
        mid = l + (r - l) // 2
 
        # If the element is present at the
        # middle itself
        if (compare(arr[mid], x) == 0):
            return mid
 
        # If element is smaller than mid, then
        # it can only be present in left subarray
        if (compare(arr[mid], x) > 0):
            return binarySearch(arr, l, mid - 1, x)
 
        # Else the element can only be present
        # in right subarray
        return binarySearch(arr, mid + 1, r, x)
 
    return -1
 
# Driver code
if __name__ == "__main__":
     
    arr = [ Rational(1, 5), Rational(2, 3),
            Rational(3, 2), Rational(13, 2) ]
    x = Rational(3, 2)
    n = len(arr)
     
    print("Element found at index %d" % (
        binarySearch(arr, 0, n - 1, x)))
 
# This code is contributed by sanjeev2552


C#




// C# program for Binary Search for Rational Numbers
// without using floating point arithmetic
using System;
 
class GFG
{
 
class Rational
{
    public int p;
    public int q;
 
    public Rational(int p, int q)
    {
        this.p = p;
        this.q = q;
    }
     
};
 
// Utility function to compare two Rational numbers
// 'a' and 'b'. It returns
// 0 -. When 'a' and 'b' are same
// 1 -. When 'a' is greater
//-1 -. When 'b' is greater
static int compare(Rational a, Rational b)
{
    // If a/b == c/d then a*d = b*c:
    // method to ignore division
    if (a.p * b.q == a.q * b.p)
        return 0;
    if (a.p * b.q > a.q * b.p)
        return 1;
    return -1;
}
 
// Returns index of x in arr[l..r] if it is present, else
// returns -1. It mainly uses Binary Search.
static int binarySearch(Rational []arr, int l, int r,
                Rational x)
{
    if (r >= l)
    {
        int mid = l + (r - l)/2;
 
        // If the element is present at the middle itself
        if (compare(arr[mid], x) == 0) return mid;
 
        // If element is smaller than mid, then it can
        // only be present in left subarray
        if (compare(arr[mid], x) > 0)
            return binarySearch(arr, l, mid - 1, x);
 
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
return -1;
}
 
// Driver method
public static void Main(String[] args)
{
    Rational []arr = {new Rational(1, 5),
                        new Rational(2, 3),
                        new Rational(3, 2),
                        new Rational(13, 2)};
    Rational x = new Rational(3, 2);
    int n = arr.Length;
    Console.Write("Element found at index {0}",
            binarySearch(arr, 0, n - 1, x));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// Javascript program for Binary Search for Rational Numbers
// without using floating point arithmetic
class Rational
{
    constructor(p, q)
    {
        this.p = p;
        this.q = q;
    }
}
 
// Utility function to compare two Rational numbers
// 'a' and 'b'. It returns
// 0 -. When 'a' and 'b' are same
// 1 -. When 'a' is greater
//-1 -. When 'b' is greater
function compare(a,b)
{
    // If a/b == c/d then a*d = b*c:
    // method to ignore division
    if (a.p * b.q == a.q * b.p)
        return 0;
    if (a.p * b.q > a.q * b.p)
        return 1;
    return -1;
}
 
// Returns index of x in arr[l..r] if it is present, else
// returns -1. It mainly uses Binary Search.
function binarySearch(arr,l,r,x)
{
    if (r >= l)
    {
        let mid = l + Math.floor((r - l)/2);
  
        // If the element is present at the middle itself
        if (compare(arr[mid], x) == 0) return mid;
  
        // If element is smaller than mid, then it can
        // only be present in left subarray
        if (compare(arr[mid], x) > 0)
            return binarySearch(arr, l, mid - 1, x);
  
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
  
return -1;
}
 
// Driver method
let arr=[new Rational(1, 5),
                        new Rational(2, 3),
                        new Rational(3, 2),
                        new Rational(13, 2)];
let x = new Rational(3, 2);
let n = arr.length;
document.write("Element found at index ",
            binarySearch(arr, 0, n - 1, x));
 
// This code is contributed by rag2127
</script>


Output: 

Element found at index 2

Time Complexity: O(log n)

Auxiliary Space: O(1),  since no extra space has been taken.

Thanks to Utkarsh Trivedi for suggesting above solution.
 



Previous Article
Next Article

Similar Reads

Draw a circle without floating point arithmetic
Given a radius of a circle, draw the circle without using floating point arithmetic.Following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every point (x,y), if (x, y) lies inside the circle (or x2+ y2 &lt;
5 min read
Draw a circle without floating point arithmetic
Given a radius of a circle, draw the circle without using floating point arithmetic.The following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every point (x,y), if (x, y) lies inside the circle (or x^2+ y^
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 &gt; 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. The number p/q reflects the ratio p:q. Some examples
5 min read
C Program to Multiply two Floating Point Numbers
Floating point numbers are a way to represent real numbers with both whole parts and fractional parts. In this article, we will learn how to write a C program to find the product of two floating-point numbers. The below image shows an example of floating point multiplication in C: C Program To Multiply Two Floating-Point Numbers The below C program
1 min read
Sum of two large Floating-point numbers
Given two very large floating-point numbers in form of large strings str1 and str2, the task is to add the given two numbers. Example: Input: str1 = "584506134.87368350839565308", str2 = "30598657.0330473560587475634983" Output: 615104791.9067308644544006434983 Input: str1 = "38.30", str2 = "37.0983" Output: 75.3983 Approach: To find the addition o
14 min read
Compare two floating-point numbers given in Scientific Notations
Given two strings N and M in the form of a * 10 b. The task is to compare given two floating-point numbers and print the smaller number and if both the numbers are equal then print Equal. 0&lt;|a|&lt;10^9 and -10^9&lt;b&lt;10^9. Example: N and M are two numbers with two parts: a1 is mantissa of N and a2 is mantissa of M.b1 is exponent of N and b2 i
11 min read
Program to find GCD of floating point numbers
The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9 Output : 0.3 Input : 0.48, 0.108 Output : 0.012 The simplest approach to solve this problem is :a=1.20 b=22.5 Expressing each of the numbers without decimals as the product of p
4 min read
Check whether the given floating point number is a palindrome
Given a floating-point number N, the task is to check whether it is palindrome or not. Input: N = 123.321 Output: YesInput: N = 122.1 Output: No Approach: First, convert the given floating-point number into a character array.Initialize the low to first index and high to the last index.While low &lt; high: If the character at low is not equal to the
4 min read
Check whether given floating point number is even or odd
Given a floating-point number, check whether it is even or odd. We can check whether a integer is even or odd by dividing its last digit by 2. But in case of floating point number we can't check a given number is even or odd by just dividing its last digit by 2. For example, 100.70 is an odd number but its last digit is divisible by 2. Examples : I
6 min read
Fast method to calculate inverse square root of a floating point number in IEEE 754 format
Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.A simple solution is to do floating point arithmetic. Following is an example function. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; float InverseSquareRoot(float x) { return 1/sqrt(x); } int main() { cou
4 min read