The best algorithm for converting a real number from 0 to 1 to the index

Suppose x is a real number between 0 and 1

If n = 2, there are two fractions from 0 to 0.5 and from 0.5 to 1

If n = 3, then there are three fractions from 0 to 0.33, from 0.33 to 0.66 and from 0.66 to 1

I want to know the most efficient algorithm that tells which part of x belongs.

If x = 0.2 and n = 3, x belongs to the first fraction, so the index is 0

If x = 0.4 and n = 3, x belongs to the second part, so the index is 1

Here is python 3 code that 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 constant time algorithm?

Edit: I haven't explicitly said before, but both 0 and 1 are a valid value for x, and the result should be n - 1 when x = 1

+4
source share
3

:

def index(x, n):
    return int(x*n)

- O (1)

+7

:

def index(x,n):
    return (10*x // n)
+1

Just do the following:

import math

def index(x, n):
    return math.ceil(x*n)
0
source

Source: https://habr.com/ru/post/1694870/


All Articles