cs175:loops_lab_-_ulam_sequence
Ulam Sequence
Write and save a program Ulam.java.
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 sequences for the starting integers 2-7:
2 -> 1 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 4 -> 2 -> 1 5 -> 16 -> 8 -> 4 -> 2 -> 1 6 -> 3 -> <repeat Ulam sequence for 3> 7 -> 22 -> 11 -> 34 -> 17 -> 52 -> 26 -> 13 -> 40 -> 20 -> 10 -> 5 -> <repeat Ulam sequence for 5>
Write Ulam.java so that it inputs a number from the user and prints the Ulam sequence for it, using a while loop. Here are some example user dialogs:
Enter a positive integer to show its Ulam sequence: 2 The Ulam sequence is: 2 -> 1 Enter a positive integer to show its Ulam sequence: 3 The Ulam sequence is: 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Here is an algorithm for this program:
Read n Compute and print the Ulam sequence for n: While n is greater than 1 Print 'n ->' If n is even n = n/2 Else // n is odd n = n*3 + 1 End While Print n // Final value of n is 1
cs175/loops_lab_-_ulam_sequence.txt · Last modified: 2015/11/24 19:26 by jchung