Reputation: 1
This is what I have so far. It basically generate the arithmetic sequence for the Collatz Conjecture. What I need now is for it count the number of values in that arithmetic sequence in real time when the code is being processed.
n = 31415
print(n)
while n > 1:
if n % 2 == 0 :
n = n//2
print (n)
else:
n = 3*n+1
print (n)
Upvotes: 0
Views: 315
Reputation: 1
I did something similar. I wanted the user entered number to display in the results and be counted. I also wanted the user to be able to enter the number 1. This is what I came up with.
def collatz(num):
count = 0
print (num) #Returns user entered value in the result
count = count + 1 #Counts the user entered value.
while True:
if (num % 2) == 0: #Evaluates if num is even number
num = num // 2 #Performs calc for even number and assigns to num
print(num)
elif num % 2 == 1: #Evaluates if num is odd number
num = 3 * num + 1 #Performs calc for odd number and assigns to num
print(num)
count = count + 1 #Adds one to the count
if num == 1: #Evalutes if num is = to 1.
print('It took', count,'iterations to complete the sequence.')
sys.exit()
Upvotes: 0
Reputation: 11
I think you just need to add a counter variable that increment each time a loop is made
n = 31415
counter = 0
print(n)
while n > 1:
if n % 2 == 0 :
n = n//2
print (n)
else:
n = 3*n+1
print (n)
counter += 1
print(counter)
Upvotes: 1