Suppose x is a real number between 0 and 1
If n = 2 there are two fractions ranges 0 to 0.5 and 0.5 to 1
If n = 3 there are three fractions ranges 0 to 0.33, 0.33 to 0.66 and 0.66 to 1
I want to know the most efficient algorithm that tells which fraction x belongs to.
If x = 0.2 and n = 3, x belongs to first fraction so index is 0
If x = 0.4 and n = 3, x belongs to second fraction so index is 1
Here's the python 3 code which has O(N) complexity.
def index(x, n):
for i in range(0, n):
if i/n <= x and x <= (i + 1)/n:
return i
I want to know if there is a better algorithm may be with constant time?
Edit: I did not explicitly said before but both 0 and 1 is a legit value for x and result should be n - 1 when x = 1
Just multiply both numbers and cut the decimal place:
def index(x, n):
return int(x*n)
Complexity is O(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With