CS 1063, Fall 2005
|
Continue indefinitely. Note that if the game reaches 1, then 1 is replaced by 2 and then by 1, so the sequence would just continue ..., 2, 1, 2, 1, .... For this reason, we stop the sequence if it ever reaches 1.
7: 7, 11, 17, 26, 13, 20, 10, 5, 8, 4, 2, 1
15: 15, 23, 35, 53, 80, 40, 20, 10, 5, 8, 4, 2, 1
16: 16, 8, 4, 1
// ThreeHalves.java: do 3/2 calculation
public class ThreeHalves {
private int n; // starting value
public ThreeHalves (int nInput) {
n = nInput;
}
public void calculateThreeHalves() {
// do the ThreeHalves calculation
System.out.print(n + ":\t");
while (n != 1) {
System.out.print(n + ", ");
if ((n%2) == 0)
n = n/2;
else
n = (3*n + 1)/2;
}
System.out.println(n); // final 1
}
}
| // ThreeHalvesTest.java: 3/2 calculation
import java.util.Scanner;
public class ThreeHalvesTest {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = in.nextInt(); // starting value
ThreeHalves th = new ThreeHalves(n);
th.calculateThreeHalves();
}
} |
// ThreeHalves.java: carry out the 3/2 calculation on a positive int.
public class ThreeHalves {
private int n; // starting value
public ThreeHalves (int nInput) {
n = nInput;
}
public void calculateThreeHalves() {
// Carry out the ThreeHalves calculation
int countItems = 0; // used to print on several lines
System.out.print(n + ":\t");
while (n != 1) {
System.out.print(n + ", ");
if ((n%2) == 0)
n = n/2;
else
n = (3*n + 1)/2;
// skip to next line every 10 items
countItems++;
if (countItems%10 == 0) {
System.out.println();
System.out.print(" \t");
}
}
System.out.println(n); // final 1
}
}
|
Type an integer for n: 27
27: 27, 41, 62, 31, 47, 71, 107, 161, 242, 121,
182, 91, 137, 206, 103, 155, 233, 350, 175, 263,
395, 593, 890, 445, 668, 334, 167, 251, 377, 566,
283, 425, 638, 319, 479, 719, 1079, 1619, 2429, 3644,
1822, 911, 1367, 2051, 3077, 4616, 2308, 1154, 577, 866,
433, 650, 325, 488, 244, 122, 61, 92, 46, 23,
35, 53, 80, 40, 20, 10, 5, 8, 4, 2,
1
Try to find the longest run of any number <= 10000000.
[Answer: 8400511 has run length of 430.]