Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Program to find common fraction between min and max using given constraint in Python
Suppose we have two long integer values maximum and minimum. We have to find a common fraction n/d such that min
So, if the input is like minimum = 1 maximum = 10, then the output will be 22/7.
To solve this, we will follow these steps −
- P := a fraction (5706674932067741 / 1816491048114374) - 3
- a := 0, b := 1, c := 1, d := 1
- farey := an array of pairs, it has two pairs initially (a, b) and (c, d)
- Loop through the following unconditionally -
- f := b + d
- if f > maximum - minimum, then
- come out from the loop
- e := a + c
- insert pair (e, f) at the end of farey
- if P
- c := e and d := f
- therwise,
- a := e and b := f
- if minimum + b > maximum, then
- come out from the loop
- if |(p_min + a)/ (minimum + b) - P|
- c := a, d := b
- come out from the loop
- come out from the loop
Example
Let us see the following implementation to get better understanding −
from fractions import Fraction def solve(minimum, maximum): P = Fraction(5706674932067741, 1816491048114374) - 3 a, b, c, d = 0, 1, 1, 1 farey = [(a,b),(c,d)] while True: f = b + d if f > maximum - minimum: break e = a + c farey.append((e, f)) if P maximum: break if abs(Fraction(p_min + a, minimum + b).real - P)Input
4, 27Output
22/7
Advertisements
