Home > Blockchain >  Printing the largest number from the outputs (collatz conjecture-python)
Printing the largest number from the outputs (collatz conjecture-python)

Time:10-30

I need help for printing the largest number from the multiple outputs. How can I modify this code to do so?

x = int(input("Enter a number : "))
while(x!=1):
    if(x%2==0):
        x  = x/2
        print("\n",x)
    else:
        x = 3*x 1
        print("\n",x)

When I typed "20" as the input, I get a list of numbers and I can easily say that 16 is the largest out of the outputs. But it is really hard when the input is big. I need a code to print out the largest number from the outputs

CodePudding user response:

You could create a generator that generates the Collatz sequence and then use the max() function to find the largest number:

def collatz_sequence(x):
    yield x

    while x > 1:
        x = x // 2 if x % 2 == 0 else 3 * x   1
        yield x

print(max(collatz_sequence(5)))   # Output: 16
  • Related