Playing Hacks and Stuffs!
We are given the description as:
Consider an algorithm that takes as input a positive integer n.
If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one.
The algorithm repeats this, until n is one.
For example, the sequence for n=3 is as follows:
3 → 10 → 5 → 16 → 8 → 4 → 2 → 1
The constraint is:
1 ≤ n ≤ 10^6
So we’re to create an algorithm that does this:
n
provided as the input, it will check this:
n
is 1Here’s my solve script:
def algo(n):
r = [n]
try:
while r[-1] != 1:
if n % 2 == 0:
n = n // 2
else:
n = (n * 3) + 1
r.append(n)
except Exception:
pass
return r
n = int(input())
sequence = algo(n)
print(" ".join(map(str, sequence)))
Basically what it does is this:
algo
which requires a number passed as the argument
r
with the number passed into this function1
map
I set it to the expected output required for this algorithm questionHere’s the result
Btw the failed attempt is when I was trying to upload an empty script :D