Attempt - 1 of the weird algorithm. Upon looking at it, it seems simple.
- if the num is odd, do num*3 + 1
- if it is even, divide by 2
keep doing this until your num is 1.
One thing I did struggle a bit was with the output formatting. At this point I'm so used to leetcode style that input-output formatting goes over my head.
Code:
n = int(input())
''' the logic: to see odd or even, we check the lsb. that way it is faster than the % function '''
import timeit # this will help in checking for time in local env.
def func(x):
while x!=1:
print(x, end= " ")
if x&1==1:
x = (x*3) + 1
else:
x//=2
else:
print(1)
'''else:
print("done")'''
start = timeit.default_timer()
func(n)
stop = timeit.default_timer()
#print("time taken: ",stop-start)
With this, I'd like to say, Hello, dev world!
Top comments (0)