➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Weird Algorithm

image

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:

Here’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:

Here’s the result image

Btw the failed attempt is when I was trying to upload an empty script :D