0

Consider the following algorithm:

i := 1
t := 0
    while i ≤ n
       t := t + i
       i := 2i

I'm interested in finding out how many addition and multiplication operations this algorithm executes; however, I'm running into trouble. I understand that the value of i doubles after each iteration, but I don't know how to generalize the algorithm to give a correct number of operations up until the value of n. If anyone can shed some light on the issue, I'd greatly appreciate it.

Thank you!

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66

1 Answers1

1

Since the value of i doubles every loop and i <= n

i*2^x <= n

and maximizing x gives the number of loops. Since i = 1

2^x = n
x = floor log(n)

and we perform 1 addition and 1 multiplication per loop. I think you can take it from here :)

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134