-1

I have the following simple algorithm:

int i = 2;
int n = {Domain is all integers >= 2}

while (I < N)
I = I * I;
execute(command);
end-while

I understand how many time the command with execute(ex. n=16 will execute 3 times, n=256, 4 times, etc.)
I would like to know the best way to express the number of executes in terms of N.

Lrrr
  • 4,755
  • 5
  • 41
  • 63
user1726845
  • 109
  • 3
  • 10

3 Answers3

0

You just need to know simple concept of logarithm.

But it is not just a simple one level logarithm, a simple logarithm could solve issue like this :

2k = n ==> log2(n) = k

but you have :

22k = n ==> log2(log2(n)) = k

so your answer is : log2(log2(n))

Proof of your iteration is 22k:

for first iteration you have 221 = 4 suppose for k'th iteration you have 22k now for k+1 iteration you have:

22k * 22k = 22k + 2k = 22k+1 and it is proven by induction :)

Lrrr
  • 4,755
  • 5
  • 41
  • 63
0

If you just need the formula, then it's simple. You need to count how many iterations there will be... Just analyze how I will grow in each iteration.

  1. I = i^2 = i^(2^1)
  2. I = i^2^2 = i^(2^2)
  3. I = i^2^2^2 = i^(2^3)
  4. I = i^2^2^2^2 = i^(2^4)

etc. k-th is i^(2^k)

Now you need to get k from I.

log i (I) = log i (i^(2^k)) => (2^k)

log 2 (2^k) => k

k = log i (log 2 (I))

Now, you can apply that I is always lower than N, thus number of iterations is bound by log i (log 2 (N)). The exact number needs to be adjusted to your bounduary conditions. You do no initialize I nowhere, so there is an assumption that I=i before 1st iteration. Also I <= N and I < N will make a difference on exact powers.

luk32
  • 15,812
  • 38
  • 62
-1

There is no formula for this calculation as per my knowledge. Since the number of executions duplicates with a set of number. I have done a simulation on this upto 2 power 20 numbers. Below is the python code

1.for n= 2 Count is  0
2.for n= 4 Count is  1
3.for n= 8 Count is  2
4.for n= 16 Count is  2
5.for n= 32 Count is  3
6.for n= 64 Count is  3
7.for n= 128 Count is  3
8.for n= 256 Count is  3
9.for n= 512 Count is  4
10.for n= 1024 Count is  4
11.for n= 2048 Count is  4
12.for n= 4096 Count is  4
13.for n= 8192 Count is  4
14.for n= 16384 Count is  4
15.for n= 32768 Count is  4
16.for n= 65536 Count is  4
17.for n= 131072 Count is  5
18.for n= 262144 Count is  5
19.for n= 524288 Count is  5

Code

__author__ = 'Abhilash'
import math
i = 2;
n = 2048
k=[2,4,8,16,32,64,128,256,512,1024,2048,4096, 8192 , 16384 , 32768 , 65536 , 131072 , 262144 , 524288 ]
for b in range(0,20):
    print int(math.pow(2,b)),",",
x=0
for b in range(0,len(k)):
    n=k[b]
    x=0
    i=2
    while i < n:
        i=i*i
        x=x+1
    print "for n=",n,"
  • Could you clarify? when n=3 the command executes once, (first iteration i = 2, second iteration i = 4, third i = 16), so if n=3.. 2(3^2) = 18 and 3^2 * 3^2 = 81... am i missing something? – user1726845 Feb 03 '15 at 05:30