Created
August 31, 2017 05:14
-
-
Save jarhill0/925dcddcbec2bc1cef9368759e25caa4 to your computer and use it in GitHub Desktop.
not working (too slow!!)
This file contains hidden or 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
import java.util.HashMap; | |
public class Euler014 { | |
private HashMap<Integer, Integer> solvedCollatz = new HashMap<>(); | |
private Integer collatzLength(Integer start) { | |
Integer len = 1; | |
Integer num = start; | |
while (num != 1) { | |
if (solvedCollatz.containsKey(num)) { | |
Integer ans = len + solvedCollatz.get(num) - 1; | |
solvedCollatz.put(start, ans); | |
return ans; | |
} | |
if (num % 2 == 0) { | |
num /= 2; | |
} else { | |
num *= 3; | |
num++; | |
} | |
len++; | |
} | |
solvedCollatz.put(start, len); | |
return len; | |
} | |
public Integer calculate() { | |
Integer bestLen = 0; | |
Integer thisLen; | |
for (Integer n = 1; n < 1000000; n++) { | |
if (n % 10000 == 0) { | |
System.out.println(n); | |
} | |
thisLen = collatzLength(n); | |
bestLen = thisLen > bestLen ? thisLen : bestLen; | |
} | |
return bestLen; | |
} | |
public static void main(String[] args) { | |
System.out.println(new Euler014().calculate()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment