I was given an assignment writing a Collatz Conjecture program, modified like so:
- We know the program ALWAYS divides by 4 on even numbers, even ones not divisible by 4, so the next step after 6 would be 6/4 == 1.
- We know the program always reached a stop condition even with the alternative behavior, not sure if there was another change in the code...
and it need to
- count the number of steps from n until we reach a stop condition
- return the sum of all the steps in Shortz(n) including n itself
as a final answer, I need to return (the sum of all steps of 737458374680773)*(the number of steps of 98325112)
The problem is when I calculate this one: 737458374680773 it goes into infinite loop.
As for this hint:
not sure if there was another change in the code...
I don't think I need to change anything with the odd numbers formula because it would be too far fetched in my opinion (but hey I don't know much, enlighten me :) ).
Any ideas as to what's the problem with my code or what I didn't get regarding the assignment?
This is my code:
import math
def shortz(num):
iterations = 0
stepsSum = 0
while( math.isnan(num) or num<0):
num = int(input("Please supply a non-negative number ==> "))
print("")
while(num !=1):
if (num%2==0):
num /= 4
stepsSum += num
print (str(iterations+1) + ") " + str(num))
else:
num = (num*3) -1
print (str(iterations+1) + ") "+ str(num))
iterations += 1
stepsSum += num
print ("the number of iterations is " + str(iterations))
print ("the sum of all steps is " + str(stepsSum))
q=0
while (q<1):
x = int(input("Input positive number: "))
shortz(x)
z = str(input("Again?")).lower()
if z[0]=='n':
q=2
Thanks a lot!
Your logic mishandles '2' and goes into an infinite loop:
2/4 is 0.5 -> (0.5 * 3) - 1 -> 0.5 -> (0.5 * 3) - 1 -> 0.5, etc.
Input positive number: 2
1) 0.5
2) 0.5
3) 0.5
4) 0.5
5) 0.5
6) 0.5
7) 0.5
...
You may need to use num //= 4
instead of num /= 4
to get rid of the fractional part. But that doesn't fix this glitch, just changes the repeating result from 0.5 to 0.
not sure if there was another change in the code...
Likely refers to how to handle zero. It's not a positive integer, so not a valid input to shortz()
but it still comes up as an internal result (if you use //
) and so has to be dealt with specially. (Ditto for 0.5 if you continue to use /
)
Perhaps something as simple as changing:
while(num !=1):
to instead be:
while num > 1:
This (along with using //
) allows both your example numbers to resolve.