Q. Predict the output of following code.

 

def express(x, n):

    if n== 0:

        return 1

    elif n%2 == 0:

        return express(x*x, n/2)

    else:

        return x * express (x, n-1)

express (2,5)

 

Output :-


If we print express (2,5) statement.
32
>>>


Explanation :-


Now, let's analyze the expression express(2, 5) using the corrected code:


Since n is not 0, it moves to the else block.

It calls express(2, 4) because 5 is odd, reducing the exponent by 1.

In the next recursive call, express(2, 4) evaluates if 4 is even.

It calls express(2 * 2, 4 / 2) which is equivalent to express(4, 2).

The next recursive call, express(4, 2), evaluates if 2 is even.

It calls express(4 * 4, 2 / 2) which is equivalent to express(16, 1).

The next recursive call, express(16, 1), is not 0 and not even, so it moves to the else block.

It calls express(16, 0).

This time, n is 0, so it returns 1.

The previous recursive call express(16, 1) multiplies 16 by 1, resulting in 16.

The initial recursive call express(2, 4) receives the result of 16.

Since n is still not 0, it moves to the else block.

It calls express(2, 3) because 4 is odd, reducing the exponent by 1.

The process continues similarly until it reaches the base case.

The final result returned by the initial call express(2, 5) is 32.

2 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

  1. It will be syntax error, because there is an extra bracket, so can you please explain how it became 32???

    ReplyDelete

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post