What is the following algorithm doing?

163 Views Asked by At

What is the purpose of following algorithm? Is it a known algorithm? Image1

1: function Q1(X (any number from 1 to 3n), n)
2:  for i ← 0 to n − 1 do
3:    if X ≤ 2n then
4:         for k ← 0 to n − 1 do
5:            y ← y + 1

6:         end for
7:     else if X ≤ 3n − 1 then
8:         for j ← 0 to n − 1 do
9:             for m ← n downto 1 by  do
10:                y ← y + 1

11:            end for
12:         end for
13:     else
14:         for l ← 0 to i − 1 do
15:             for p ← 0 to i − 1 do
16:                 y ← y + 1

17:              end for
18:          end for
19:       end if
20:     end for
21:    return (y)
22: end function
2

There are 2 best solutions below

0
On BEST ANSWER

I wrote a C++ code for this as follows

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int m=100; int n=100; int X=3*n+2;
int i,j,k,l,p,y,count,condition;
for (i = 0; i<= n-1; i++)
{
    if (X <= 2*n)
    {
        condition=1;
         for (k = 0 ; k <= n - 1; k++) 
          {
             count=count+1;
             y = y + 1;
          }    
    }
    else if (X <= 3*n - 1 )
    {
        condition=2;
        for (j = 0 ; j <= n - 1; j++) 
        {
            m=n;
            while (m>=1)    //  for (m = n ;m<=1; m=m/2)
            {               //  printf("\n\n m: %d",m);
                 count=count+1;
                 y = y + 1;
                 m=(int) m/2;
            }
        }
    }
    else
    {
        condition=3;
            for (l = 0 ; l <= i - 1; l++)
            {
                for (p = 0 ; p <= i - 1; p++)
                {
                    count=count+1;
                    y = y + 1;
                }
            }
    }
}
    printf("\n\n n : %d", n);
    printf("\n\n X : %d", X);    
    printf("\n\n Condition : %d", condition);    
    printf("\n\n count : %d", count);
    return 0;
}

n=100 if X=2n-2 count=10000 if X=2n+2 count=70000 if X=3n+2 count=328350

3
On

This is a toy program, probably meant to exercise you in the evaluation of complexities.

It increments $y$ either $n^2$, $n^2\lfloor\lg n\rfloor$ or $\dfrac{(n-1)n(2n-1)}6$ times, depending on the value of $n$.

$y$ must be a global variable not shown.

The worst-case complexity is $O(n^3)$, achieved when $x=n$.

If I am right, with equiprobable values of $x$, the expected complexity is $O(n^2\lg n)$.