Problem 14: Find the longest sequence using a starting number under one million. (via Collatz conjecture)
I used a cache to improve my execution time… my PC takes about 5seconds.
import java.util.HashMap;
import java.util.Map;
class runner
{
static HashMap cache = new HashMap();
public static void mergeCache(HashMap minicache){
cache.putAll(minicache);
}
public static long calc(long n){
if(n%2 == 0)
return n/2;
else
return 3*n+1;
}
public static void main (String[] args) throws java.lang.Exception
{
long time = System.currentTimeMillis();
long lrgLen = 0, lrgNum = 0;
for(int i=1; i<1000000; i++){
HashMap minicache = new HashMap();
long val = i, counter = 1;
while(val != 1){
//Check cache
if(cache.containsKey(val)){
Integer cachedVal = cache.get(val);
//update all values in minicache
for (Map.Entry entry : minicache.entrySet()){
entry.setValue(entry.getValue()+cachedVal);
}
counter += cachedVal;
break;
}
val = calc(val);
//update all values in minicache
for (Map.Entry entry : minicache.entrySet()){
entry.setValue(entry.getValue()+1);
}
minicache.put(val, 1);
counter ++;
}
mergeCache(minicache);
if(counter > lrgLen){
lrgLen = counter; lrgNum = i;
}
//System.out.println("cachesize: "+cache.size());
}
System.out.println("i: "+lrgNum+" len: "+lrgLen+" time: "+(System.currentTimeMillis() - time));
}
}