Created
May 27, 2014 18:21
-
-
Save goyuninfo/f295932bab9f3c9f589b to your computer and use it in GitHub Desktop.
Project Euler 14: Longest Collatz Sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ca.i88.it.euler; | |
public class ProjectEuler14 { | |
public static void main(String[] args) { | |
long start = System.currentTimeMillis(); | |
final int number = 1000000; | |
int sequenceLength = 0; | |
int startingNumber = 0; | |
long sequence; | |
int[] cache = new int[number + 1]; | |
for (int i = 3; i <= number; i = i + 2) { | |
sequence = i; | |
int k = 0; | |
while (sequence != 1 && sequence >= i) { | |
k++; | |
if ((sequence % 2) == 0) { | |
sequence = sequence / 2; | |
} else { | |
sequence = sequence * 3 + 1; | |
} | |
} | |
// Store result in cache | |
cache[i] = k + cache[(int) sequence]; | |
// Check if sequence is the best solution | |
if (cache[i] > sequenceLength) { | |
sequenceLength = cache[i]; | |
startingNumber = i; | |
} | |
} | |
long end = System.currentTimeMillis(); | |
System.out.println(startingNumber); | |
System.out.println(end - start); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment