Reputation: 25
I have this code I wrote, where I want to find out how many iterations n are needed to reach x[n]=1 for a given input integer, and print that amount. (btw it is the collatz count). The code is:
x0 = int(input('Enter number:'))
while x0 > 1:
print(x0, end=' ')
if (x0 % 2):
x0 = 3*x0 + 1
else:
x0 = x0//2
print(1, end=' ')
I want to know how many numbers are in the answer, but with this code I got all the answers. (Enter number:3 gives
3 10 5 16 8 4 2 1
but I want my answer to look like this:
8
I thought putting len()
after the print
would work, but it didn't. How can I do this?
Upvotes: 1
Views: 713
Reputation: 51683
Simply add a counter to your while loop:
x0 = int(input('Enter number:'))
counter = 1 # start at 1 b/c adding 1 after the loop
while x0 > 1:
# increment so you count how often it loops
counter += 1
print(x0, end=' ')
if (x0 % 2):
x0 = 3*x0 + 1
else:
x0 = x0//2
print(1) # print the 1 and newline
# and print the count as well
print(counter)
Output:
Enter number:20
20 10 5 16 8 4 2 1
8
You could also collect all numbers in a list:
nums = []
while x0 > 1:
nums.append(x0)
if (x0 % 2):
x0 = 3*x0 + 1
else:
x0 = x0//2
nums.append(1)
print(*nums) # print the whole list here
print(len(nums)) # and it's length
Trivia: the longest collatz below 1,000,000 is 837799 with 525 steps to 1 && xkcd.com take on Collatz Conjecture - you find other limits at wikipedia
Upvotes: 1