- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
77 lines (59 loc) · 2.04 KB
/
Copy pathMain.java
File metadata and controls
77 lines (59 loc) · 2.04 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
75
76
77
importjava.util.HashMap;
importjava.util.Map;
/*
@author: mc-es
Problem 14
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
Answer: 837799
*/
publicclassMain {
// The cache stores the lengths of previously calculated Collatz sequences.
privatestaticMap<Long, Integer> cache = newHashMap<>();
publicstaticvoidmain(String[] args) {
intcounter = 0;
longmaxLength = 0;
longstartTime = System.nanoTime();
// We loop through all numbers from 1 to 1 million to find the longest sequence
for (longi = 1; i < 1000000; i++) {
intlength = collatzSequence(i);
if (length > counter) {
counter = length;
maxLength = i;
}
}
longendTime = System.nanoTime();
System.out.println(maxLength);
System.out.println("Time taken: " + (endTime - startTime) / 1_000_000_000.0);
}
// This function calculates the length of a number's Collatz sequence
privatestaticintcollatzSequence(longn) {
// If we have a result in the cache, we return the value from the cache.
if (cache.containsKey(n)) {
returncache.get(n);
}
// Otherwise, we calculate the length of the Collatz sequence using a loop
intlength = 1;
longoriginalN = n; // Store the original value of n
while (n != 1) {
if (n % 2 == 0) {
n /= 2;
} else {
n = 3 * n + 1;
}
if (cache.containsKey(n)) {
length += cache.get(n);
break;
}
length++;
}
cache.put(originalN, length);
returnlength;
}
}