-9
def findMax(f,c):
    n=1
    while f(n) <= c:
        n += 1
   return n

This is a higher-order python function that given function f and a maximal count, c returns the largest n such that f(n) ≤ c. This works but not when n gets too large for e.g f(10**6). How can I make this algorithm run O(log n) time so it can facilitate f(10**6) using the function below?

def f(n):
    return math.log(n, 2)
Rahul
  • 18,271
  • 7
  • 41
  • 60

2 Answers2

0

Change n += 1 to n *= 2 for logarithmic outcome.

Logarithmic sequences increment in multiples of 2, and are non-linear, thus logarithmic sequences don't increment by 1.

God Bennett
  • 301
  • 3
  • 8
0

Use a search algorithm to find the solution faster. This is an implementation using jpe.math.framework.algorythems.brent which is an implementation of the brent search algorithm.

import math
import jpe

import jpe.math.framework.algorythems

def f(x):
    return math.log(x, 2)

value = 9E2
startVal = 1E300

val = int(jpe.math.framework.algorythems.brent(f, a=0, b=startVal, val=value, mode=jpe.math.framework.algorythems.modes.equalVal)[0])#takes 37 iters

print(val)

Alternatively in this scenario with this f:

the result is within 1 of 2**c (c as passedto findMax)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Julian wandhoven
  • 268
  • 2
  • 11