Jump to content

User:Kithira/Course Pages/CSCI 12/Assignment 2/Group 4/Homework 2

From Wikipedia, the free encyclopedia

"Infinite Hailstone Sequences" from Lab 2

[edit]

Math

[edit]

See Collatz Conjecture for more information.

Code

[edit]

An example of code to find the Syracuse number of a given n. (In python)

def syracuse(n):
  # Returns the Syracuse number of the given n
  if n%2 = 1:
    return (3*n) + 1
  else:
    return n/2

An example of code (using the above syracuse code) to find a hailstone sequence of a given n. (In python)

def hailstone(n):
  # Returns the hailstone sequence of the given n
  sequence = [n]
  while n > 1:
    n = syracuse(n)
    sequence.append(n)

  return sequence

The number n is the input value into the function. For each while loop iteration, the Syracuse number is found for the value n. The list "sequence" is given the most recent Syracuse number and appends that value to itself. Afterwards, the n value is updated with the Syracuse number, and the process begins again until n = 1.

An example of code to test how long the computer will go until it is unable to find the hailstone sequence of a number. (Using above Hailstone code. In python)

def hStoneInfinite():
  # Loops infinitely, tracking the number that has the longest hailstone sequence before failure.
  maxNum = 0
  maxLength = 0
  temp = 2
  while True:
    s = hailstone(temp)
    if len(s) > maxLength:
      maxNum = temp
      maxLength = len(s)
      print "The number with the longest sequence is currently", maxNum
      print "The length of the sequence is", maxLength 
    temp += 1

This function utilizes an infinite loop to find numbers that have the longest hailstone sequence. For variable s (incremented by 1 for each iteration through the loop), its hailstone sequence is calculated and compared to the previously stored maxLength. If the length of the current sequence is greater than the old maxLength, the length of the current sequence is assigned to maxLength and the current s is assigned to maxNum. Additionally, if a new max is found, the function will print both the current maxNum and maxLength.

Comments

[edit]

This code is quite clever in several ways. First of all, the hailstone def cleverly calculates the syracuse number of n and updates its value, then appends it. By doing this in this order, one line of code to temporarily store a value of n is saved, which is nice. The infinite loop also is an elegant way of utilizing an infinite loop, while still keeping the user involved in roughly where the computer is in the process, which is quite nice. One improvement that could be made would be to let the initial value of the variable temp be input by the user, so you could start the loop anywhere you wanted.

Overall, group 5 thinks that this code is quite elegant and clever, and provides a great solution to the problem presented in lab 2, and the article is clear and explains well what the code is doing.