-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeNPlusOne.java
More file actions
74 lines (62 loc) · 1.52 KB
/
Copy pathThreeNPlusOne.java
File metadata and controls
74 lines (62 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.Scanner;
/**
* Problem statement can be viewed at:
* http://www.programming-challenges.com/pg.php
* ?page=downloadproblem&probid=110101&format=html
*
* The following is a solution for the above problem.
*
* @author Quinn Liu (quinnliu@vt.edu)
* @author Jason Riddle (jr1285@vt.edu)
* @version Sept 2, 2013
*/
public class ThreeNPlusOne {
public static void main(String[] args) {
runProblem();
}
// Now we're non-static
public static void runProblem() {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
runOne(in.nextInt(), in.nextInt());
}
in.close();
}
public static void runOne(long i_short, long j_short) {
// ---------------------------Solution--------------------------------
long maximumCycleLength = 0;
long from = 0;
long to = 0;
if (i_short < j_short) {
from = i_short;
to = j_short;
} else {
from = j_short;
to = i_short;
}
for (long k = from; k <= to; k++) {
long currentCycleLength = calculateCycleLength(k);
if (currentCycleLength > maximumCycleLength) {
maximumCycleLength = currentCycleLength;
}
}
// 1 2
if (j_short < i_short) {
from = i_short;
to = j_short;
}
System.out.println(from + " " + to + " " + maximumCycleLength);
}
static long calculateCycleLength(long number) {
long cycleLength = 1;
while (number != 1) {
cycleLength++;
if (number % 2 == 0) {
number = number / 2;
} else {
number = number * 3 + 1;
}
}
return cycleLength;
}
}