119k views
3 votes
Myvar = 0;

For (i=1, 30, i++)

myvar = myvar+Module(i,2)*i;

End

a) What does this algorithm do?

b) What is it's cost?

c) Is there a function that exists that could express the same result as this algorithm?

User Beardo
by
4.5k points

1 Answer

6 votes

Answer:

#part (a):

Here Module(a,b) refers to modulo function.

It calculate remainder when

"a" is divided by "b".it will return 0, if a number

is completely divided by another number, otherwise

it will return the remainder.

In for loop , first iteration

myvar = myvar+Module(i,2)*i

myvar = 0+Module(1,2)*1 (i=1,myvar=0)

myvar = 0+1*1

myvar=1

Then the value of "myvar=1" after the first iteration.

In for loop , second iteration

myvar = myvar+Module(i,2)*i

myvar = 1+Module(2,2)*2 (i=2,myvar=1)

myvar = 1+0*2

myvar=1

Similarly it will iterate 30 times,

and at the end of for loop "myvar" will become 225.

which is equal to square of 15.

The above algorithm calculate the square of (i/2) if it odd otherwise

value of "myvar" doesn't change.

#part (b):

Here for loop runs for 30 times, so the complexity will be O(1) because

30 is a scaler number.

#part (c):

There is a function "square(n)"which gives the equivalent value of "myvar".

i.e

myvar=square(i/2).

User Ionut Bajescu
by
4.8k points