I'm getting an "Execution Timed Out" error?

Question:

I’m trying to improve my algorithm skills. When I run my code, I get an "Execution Timed Out" error.

Pseudocode

[This is writen in pseudocode]
if(number is even) number = number / 2
if(number is odd) number = 3*number + 1

My Code


def hotpo(n):
    calculator = 0
    while n >= 1:
        if n % 2 == 0:
            n = n / 2
        else:
            n = 3 * n + 1
        calculator = calculator + 1
    return calculator
Asked By: mustafaoguzbaran

||

Answers:

you are dividing number by 2 if number is even but multiplying it by 3 and adding 1 into it.

so for any number it will keep doing this
2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,…..

you just have to change condition to n>1 in while loop

because at last 2 will come and it got divided by 2, then n becomes 1 then again it will consider 1 as odd as per your condition then again 1*3+1=4 and again 4/2=2 and so on…

I hope you understood..

Answered By: Siddharth Asodariya
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.