123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import java.util.ArrayList;
- public class LongestCollatzSequence {
- private long longestStartingNumber = this.findLongestCollatzSequence();
- public long getLongestStartingNumber() {
- return this.longestStartingNumber;
- }
- private ArrayList<Long> findCollatzSequenceForNum(long num) {
-
- ArrayList<Long> sequence = new ArrayList<Long>();
-
- sequence.add(num);
- while (num != 1) {
-
- if (num % 2 == 0) {
- num = num / 2;
- sequence.add(num);
- }
-
- else {
- num = 3 * num + 1;
- sequence.add(num);
- }
- }
-
- return sequence;
- }
- private long findLongestCollatzSequence() {
- long largestStartingNumber = 0;
- long longestLength = 0;
- for (long i = 2; i <= 1000000; i++) {
- long collatzLength = this.findCollatzSequenceForNum(i).size();
- if (collatzLength > longestLength) {
- longestLength = collatzLength;
- largestStartingNumber = i;
- }
- else
- continue;
- }
- return largestStartingNumber;
- }
- }
|