Skip to content

Commit aa884cd

Browse files
authored
Merge pull request darpanjbora#94 from naresh1406/master
Largest Power Of Two In Collatz Sequence
2 parents ad39683 + dfdf3de commit aa884cd

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import java.util.ArrayList;
2+
import java.util.Collections;
3+
4+
/**
5+
* Created with IntelliJ IDEA.
6+
* User: ngupta
7+
* Date: 27/10/19
8+
* Time: 12:00 PM
9+
*/
10+
11+
/**
12+
* To get a Collatz sequence from a number, if it's even, divide it by two, and if it's odd, multiply it by three and add one.
13+
* Continue the operation on the result of the previous operation until the number becomes 1.
14+
*/
15+
16+
public class LargestPowerOfTwoInCollatzSequence {
17+
public static void main(String[] args) {
18+
int num = 7;
19+
20+
ArrayList<Integer> sequence = collatzSequence(num);
21+
22+
System.out.println(sequence);
23+
24+
System.out.println(maxPowerOfTwo(sequence));
25+
26+
System.out.println(maxPowerOfTwoCleanApproach(num));
27+
}
28+
29+
public static int maxPowerOfTwo(ArrayList<Integer> list) {
30+
Collections.sort(list, Collections.reverseOrder());
31+
for (Integer i : list) {
32+
if (isPowerOfTwo(i))
33+
return i;
34+
}
35+
return 1;
36+
}
37+
38+
public static boolean isPowerOfTwo(int n) {
39+
if (n == 0)
40+
return false;
41+
42+
while (n != 1) {
43+
if (n % 2 != 0)
44+
return false;
45+
n = n / 2;
46+
}
47+
return true;
48+
}
49+
50+
public static int maxPowerOfTwoCleanApproach(int n) {
51+
if (n == 4 || n == 2 || n == 1)
52+
return 4;
53+
else if (n % 2 == 0)
54+
if (isPowerOfTwo(n))
55+
return n;
56+
return maxPowerOfTwoCleanApproach(nextCollatz(n));
57+
}
58+
59+
60+
public static int nextCollatz(int n) {
61+
return n % 2 == 0 ? n / 2 : 3 * n + 1;
62+
}
63+
64+
public static ArrayList<Integer> collatzSequence(int n) {
65+
66+
ArrayList<Integer> arrayList = new ArrayList();
67+
if (n == 4) {
68+
//list.add(4); list.add(2); list.add(1);
69+
arrayList.addAll(Arrays.asList(4, 2, 1));
70+
return arrayList;
71+
}
72+
73+
arrayList.add(n);
74+
arrayList.addAll(collatzSequence(nextCollatz(n)));
75+
return arrayList;
76+
}
77+
}

0 commit comments

Comments
 (0)