I am trying to run a Collatz conjecture sequence to see if it always ends at 1, but my number is stuck at 999. Why is this? [closed]

StackOverflow https://stackoverflow.com/questions/21594941

Question

Here is my code:

def isEven(number):
    return number % 2 == 0

def run(x):
    z = x
    while z != 1:
        if isEven(z) == True:
            z = z/2
            print z
        else:
            z = (3*z)+1
            print z
    else:
        print 'Got one!'
        #To see if the collatz does indeed always work
    x+=1

It works up until 999, at which it continues indefinitely, print Got one! 999, eventually raising a Segmentation Fault: 22. How do I fix this?

Was it helpful?

Solution 2

Use a sys.setrecursionlimit to stop the 999 from repeating forever. Here is an edited version of your code. I put a sys.argv[] as well, just for fun because I imported sys. The sys.argv[] gets the argument after you run your program like this: python myscript.py 13.5 In this, sys.argv[1] is 13.5. I set the recursion limit pretty high, but the downfall of this is that the Segmentation Fault: 22 still occurs, and I haven't found a way to get rid of that.

import time
import sys
while True:
    try:
        var = int(sys.argv[1])
        break
    except IndexError:
        print 'You have to enter a number!'
        var = int(raw_input('Enter a number: '))
        break

def check(x):
    z = x
    try:
        while z != 1:
            if isEven(z) == True:
                z = z/2
                print z
            else:
                z = (3*z)+1
                print z


        else:
            print 'Got one!'
            x = x+1
            print 'Trying for %d...' %(x)
            check(x)
    except:
        print 'You were at number %d' %(x)
        check(x)

def isEven(number):
        return number % 2 == 0

sys.setrecursionlimit(10000000)
check(var)

OTHER TIPS

Here's a cleaner version:

def collatz(x):
    yield x
    while x > 1:
        if x & 1:
            # x is odd
            x = 3*x + 1
            yield x
        # x is now even
        x //= 2
        yield x

def main():
    for x in xrange(2, 5000):
        print('-'*20)
        print(','.join(str(c) for c in collatz(x)))

if __name__=="__main__":
    main()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top