Given a monotonically increasing function f(x) on positive numbers, find the lowest positive integer x where f(x) > 0. In other words, find a positive number x such that f(i) > 0 for any integer i greater than or equal to x.

A function is called monotonically increasing, if f(x) <= f(y) is true for all x and y such that x <= y. For example, f(x) = 3x - 100 is a monotonically increasing function. It becomes positive for the first time when x = 34, as shown below:

 
Monotonically increasing function

Practice this problem

A simple solution would be to consider all positive numbers starting from 0 and find the first number for which f(x) is positive. The time complexity of this solution is O(x).

 
We can solve this problem in O(log(x)) time with the help of a binary search algorithm. But we can’t apply standard binary search on an unbounded search space since the upper limit of the search space is not known.

The idea is to determine the range in which x resides using exponential search and perform a binary search within that range. The exponential search routine starts with i = 1 and keep on doubling i until f(i) becomes positive for the first time. When f(i) becomes positive, perform a binary search within the search space [i/2, i] and find the target value x in O(log(x)) time.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

f(x) becomes positive for the first time when x = 34

Java


Download  Run Code

Output:

f(x) becomes positive for the first time when x = 34

Python


Download  Run Code

Output:

f(x) becomes positive for the first time when x = 34