1. Computing & Technology

Discuss in my forum

The Collatz Theory

By , About.com Guide

Level: Beginner

Focus: Loops, Methods

Collatz Theory Question

A previous programming exercise introduced Lothar Collatz's theory: for any number it's possible to make a sequence of numbers that will eventually end in one by following a simple rule; if the number is even halve it by two, if it's odd times it by three and add one (e.g., starting with the number 5 the sequence would be 5 16 8 4 2 1).

What I didn't mention is the theory is still unproven. I thought it might be interesting to expand the hailstone sequence generating program into one that could prove it for a certain set of numbers. Unfortunately we could never write a program that could prove the theorem completely because we would have to test all the numbers to infinity. However in terms of Java, it's a nice way to take a piece of code, move it into a method, and write some new code to call that method a number of times. Note, if you didn't do the previous exercise you could just use my solution.

Requirements:

  • take the code you wrote for the hailstone sequence exercise or my solution and move it into a method.
  • call the new method to calculate the hailstone sequence for the numbers 1 to 1000. Make sure you keep track of the number which produces the longest sequence.
  • only display the hailstone sequence for the number with the longest sequence.
  • display a sentence that tells the user how many numbers are in the sequence and the number the sequence belongs to.

The question is can your program find the number between 1 and 1000 that has the longest sequence of numbers (e.g., the number 125 has 109 numbers in its sequence) and display it to the screen?

To get the most out of this question try and figure out the answer before coming back to read the solution on the next page.

©2012 About.com. All rights reserved.

A part of The New York Times Company.