Suppose to have n
(integer) contiguous segments of length l
(floating point). That is:
Segment 0 = [0, l)
Segment 1 = [l, 2*l)
Segment 2 = [2*l, 3*l)
...
Segment (n-1) = [(n-1)*l, n*l)
Given a number x
(floating point), I want to write a function
int getSegmentId(double x, double l, int n)
which returns the id of the segment where x
lies.
I would like to do this in O(1), not O(log(n)) by checking if x
lies in each interval.
I think this is a very general and common problem and I guess there is one solution for this. Have you any hint for me?
Addendum
The question is not about a particular implementation of this algorithm like in the previous question based on floating point operations. I'm just asking which is the best a good and robust way to implement this.