Jump to content

Recommended Posts

Posted

So I have been having some fun messing around with the 3x+1 problem, also called the Collatz Conjecture. What I have been able to do is create a program in Python that given an integer will print each step of function until it becomes 1. The code I wrote for this was:

 

from __future__ import division
from visual import *
from visual.graph import *

n=

while n!=1:
   if n%2==0:
       n=n/2
   if n%2!=0 and n!=1:
       n=3*n+1
   print n

 

 

What I would like to do is to modify this so that I can have the program run for a large number of numbers, and return the number of steps it took to get to 1 for each number. Sadly I really have no idea how to approach doing this as my programing is minimal. Could anyone give me some suggestions and/or pointers for how to go about doing this?

Posted (edited)

You already did the hard part, which was formulating an algorithm for 'Half Or Triple Plus One' using modulus! To keep count of the steps well, declare a variable before the while loop and set it equal to zero. Each time you enter the while loop increment the variable by one. Habitually I name a variable like this i, for index although this can be considered bad practice as the name should be more descriptive and be such that it is not readily confused with another i.

 

When you have reached the desired value of 1 use a break statement.

 


while true:
   if n==1:
       break


 

For your condition of having an 'array' of numbers simply declare the array and inside the while wrap your algorithm in a 'for loop' like so:

 


for index in range( 0, size_array )
   place algorithm here...


 

I think this is all you are asking ....

 

Oh and for an array you will only want to break when they all reach 1 .... which should be pretty simple for you Bruce :)

Edited by Xittenn

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.