-2

I have been trying to find a tight bound time complexity for this function with respect to just one of the arguments. I thought it was O(p^2) (or rather big theta) but I am not sure anymore.

(define (acc p n)
  (define (iter p n result)
    (if (< p 1) 
        result
        (iter (/ p 2) (- n 1) (+ result n))))
  (iter p n 1))
dyoo
  • 11,795
  • 1
  • 34
  • 44

2 Answers2

2

@sarahamedani, why would this be O(p^2)? It looks like O(log p) to me. The runtime should be insensitive to the value of n.

You are summing a series of numbers, counting down from n. The number of times iter will iterate depends on how many times p can be halved without becoming less than 1. In other words, the position of the leftmost '1' bit in p, minus one, is the number of times iter will iterate. That means the number of times iter runs is proportional to log p.

Bart
  • 19,692
  • 7
  • 68
  • 77
Alex D
  • 29,755
  • 7
  • 80
  • 126
  • Just to be pedantic, it is in the set of programs O(p^2), speaking purely from the technical definition. It's just that it belongs also to a much smaller set, and we're trying to convince the OP that O(p^2) is way, way too loose of an upper bound. – dyoo Feb 14 '12 at 16:59
0

You might try to eyeball it, or go from it more systematically. Assuming we're doing this from scratch, we should try build a recurrence relation from the function definition.

We can assume, for the moment, a very simple machine model where arithmetic operations and variable lookups are constant time.

Let iter-cost be the name of the function that counts how many steps it takes to compute iter, and let it be a function of p, since iter's termination depends only on p. Then you should be able to write expressions for iter-cost(0). Can you do that for iter-cost(1), iter-cost(2), iter-cost(3), and iter-cost(4)?

More generally, given an p greater than zero, can you express iter-cost(p)? It will be in terms of constants and a recurrent call to iter-cost. If you can express it as a recurrence, then you're in a better position to express it in a closed form.

dyoo
  • 11,795
  • 1
  • 34
  • 44