https://github.com/allaboutjst/airbnb/blob/master/src/main/java/collatz_conjecture/CollatzConjecture.java
http://buttercola.blogspot.com/2016/06/collatz-conjecture.html
public class Solution {
private int findSteps(int num) {
if (num <= 1) return 1;
if (num % 2 == 0) return 1 + findSteps(num / 2);
return 1 + findSteps(3 * num + 1);
}
public int findLongestSteps(int num) {
if (num < 1) return 0;
int res = 0;
for (int i = 1; i <= num; i++) {
int t = findSteps(i);
res = Math.max(res, t);
}
return res;
}
}
/*
Collatz Conjecture - Memorization
AirBnB Interview Question
https://en.wikipedia.org/wiki/Collatz_conjecture
*/
public class Solution_2 {
Map<Integer, Integer> map = new HashMap<>();
private int findSteps(int num) {
if (num <= 1) return 1;
if (map.containsKey(num)) return map.get(num);
if (num % 2 == 0) num = num / 2;
else num = 3 * num + 1;
if (map.containsKey(num)) return map.get(num) + 1;
int t = findSteps(num);
map.put(num, t);
return t + 1;
}
public int findLongestSteps(int num) {
if (num < 1) return 0;
int res = 0;
for (int i = 1; i <= num; i++) {
int t = findSteps(i);
map.put(i, t);
res = Math.max(res, t);
}
return res;
}
}
考拉茲猜想(英語:Collatz conjecture),又稱為奇偶歸一猜想、3n+1猜想、冰雹猜想、角谷猜想、哈塞猜想、烏拉姆猜想或敘拉古猜想,是指對於每一個正整數,如果它是奇數,則對它乘3再加1,如果它是偶數,則對它除以2,如此循環,最終都能夠得到1。
Given a positive number n >= 1, ask how many times the number, n, need to change in order to get to 1. e.g. n = 6, return 8, because there are 8 steps to transform 6 to 1.
public
int
collatzConjecture(
int
n) {
if
(n <
1
) {
throw
new
IllegalArgumentException(
"n must be greater or equal to 1"
);
}
int
count =
0
;
while
(n !=
1
) {
if
((n &
1
) ==
1
) {
n = n *
3
+
1
;
}
else
{
n /=
2
;
}
count++;
}
return
count;
}
public
int
collatzConjectureRecursive(
int
n) {
if
(n <
1
) {
throw
new
IllegalArgumentException(
"n must be greater or equal to 1"
);
}
if
(n ==
1
) {
return
0
;
}
if
(n %
2
==
0
) {
return
1
+ collatzConjectureRecursive(n /
2
);
}
else
{
return
1
+ collatzConjectureRecursive(n *
3
+
1
);
}
}
1. Be very careful about the integer overflow problem. For large integers, where n is odd, 3 * n + 1 can easily get overflow. Clarify this problem with the interviewer. We may also use long instead of int to expand the size of n.
Follow-up: What if we call the function with different n many times. Can we do it faster?
The answer is yes. Implementing a recursive algorithm is probably the simplest way to calculate the length, but seemed to me like an unnecessary waste of calculation time. Many sequences overlap; take for example 3's Hailstone sequence:
3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
This has length 7; more specifically, it takes 7 operations to get to 1. If we then take 6:
6 -> 3 -> ...
I tried to implement this in Java using a HashMap (seemed appropriate given O(1) probabilistic get/put complexity).
private
static
Map<Integer, Integer> map;
public
Solution() {
map =
new
HashMap<>();
map.put(
1
,
0
);
// NOTE that we need to put 1 into the cache as the base case
}
public
int
collatzConjectureCached(
int
n) {
if
(n <
1
) {
throw
new
IllegalArgumentException(
"n must be greater or equal to 1"
);
}
if
(n ==
1
) {
return
0
;
}
int
count =
0
;
int
m = n;
while
(
true
) {
if
(map.containsKey(n)) {
count += map.get(n);
map.put(m, count);
return
count;
}
else
if
(n %
2
==
0
) {
n /=
2
;
}
else
{
n = n *
3
+
1
;
}
count++;
}
}
what if we call this function many times with different n, then it could consume lots of memory to save the HashMap. What if the memory is not largely enough to hold the entire HashMap, what can we do?
- One possible solution is instead of building an unlimited sized cache(implemented as a HashMap), we can build a fixed sized cache. For example, a LRU cache with a fixed capacity. The capacity is less than the memory size of the machine. We can maintain such a LRU cache in memory. In this case, some numbers which are not frequently used might be evicted from the cache. This is a trade-off between time and space
Test the Collatz conjecture
CollatzConjecture.java
public static boolean testCollatzConjecture(int n) {
// Stores the odd number that converges to 1.
Set<Long> table = new HashSet<>();
// Starts from 2 since we don't need to test 1.
for (int i = 2; i <= n; ++i) {
Set<Long> sequence = new HashSet<>();
long testI = i;
while (testI >= i) {
// We met some number encountered before.
if (!sequence.add(testI)) {
return false;
}
if ((testI & 1) != 0) { // Odd number
if (!table.add(testI)) {
break; // This number have already be proven to converge to 1.
}
long nextTestI = 3 * testI + 1; // 3n + 1.
if (nextTestI <= testI) {
throw new RuntimeException("test process overflow");
}
testI = nextTestI;
} else { // Even number.
testI >>= 1; // n / 2.
}
}
table.remove((long) i);
}
return true;
}