C++: Programming Problem - Ulam Sequence
The Ulam Sequence
A mathematician named Ulam proposed generating a sequence of numbers from any
positive integer n (n > 0) as follows:
- If n is 1, stop.
- If n is even, the next number is n/2.
- If n is odd, the next number is 3*n + 1.
- Continue with this process until reaching 1.
Here are some examples for the first few integers.
2 -> 1
3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
4 -> 2 -> 1
5 -> 16 -> 8 -> 4 -> 2 -> 1
6 -> 3 -> etc as for 3 above.
7 -> 22 -> 11 -> 34 -> 17 -> 52 -> 26 -> 13 -> 40 -> 20 -> 10 -> 5 -> see 5 above.
Ulam hasn't been the only one to work on this problem.
See The 3x+1 problem and its generalizations
for more information.
Does every sequence stop?
It's unknown if all sequences end at 1.
Perhaps there are sequences that get into a loop, or
increase indefinitely.
Write a program that shows the sequence
Write a program that reads a number (in a while loop of course)
and prints the Ulam sequence for it.
Possible extensions
There are several ways to extend this program.
- Instead of reading input, write a
for loop that examines
the length of the Ulam sequence for the first 1,000
numbers. Which number produces the longest sequence, and how long is it?
Or do some sequences never terminate?
- Some intermediate numbers become quite large. What is the largest
number that is ever encountered in the Ulam sequences for the first
1,000 numbers?