Created
February 14, 2011 13:08
-
-
Save Riduidel/825846 to your computer and use it in GitHub Desktop.
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
// courtesy of http://www.nearinfinity.com/blogs/seth_schroeder/project_euler_problem_10_meets.html and others | |
def primes(upto) { | |
def primes = [] | |
def range = 2..upto | |
for(i in range) { | |
primes[i] = true | |
} | |
primes.remove(0) | |
for(def index=2; index<upto; index++) { | |
if(primes[index]) { | |
def increment = 2 | |
def value | |
while((value = index*increment)<=upto) { | |
primes[value] = false | |
increment++ | |
} | |
} | |
} | |
def returned = [] | |
for(i in range) { | |
if(primes[i]) | |
returned << i | |
} | |
return returned | |
} | |
/** | |
* Small optimization : directly compute squares for easier formula writing | |
*/ | |
def squares(upto) { | |
returned = [] | |
for(i in 1..upto) { | |
returned[i]=i*i | |
} | |
return returned | |
} | |
def maxN = 1000 | |
def maxFactors = 1000 | |
long start = System.currentTimeMillis(); | |
def primes = primes(maxN) | |
println "primes computed" | |
def squares = squares(maxFactors) | |
println "squares computed" | |
def workingFactors = [:] | |
for(a in -1*maxFactors..maxFactors) { | |
for(b in -1*maxFactors..maxFactors) { | |
boolean isPrime = true | |
def matching = [] | |
for(def n=1; n<maxN && isPrime; n++) { | |
result = squares[n]+n*a+b; | |
isPrime=primes.contains(result) | |
if(isPrime) { | |
matching << result | |
} | |
} | |
if(matching.size()>0) { | |
workingFactors[[a,b]]=matching | |
} | |
} | |
if(a%100==0) | |
println "reached ${a}" | |
} | |
bestEntry = workingFactors.max { e -> | |
e.value.size() | |
} | |
println "best entry is ${bestEntry.key} product is ${bestEntry.key.inject(1, {result, entry -> result*entry})} and sequence length is ${bestEntry.value.size()}" | |
long end = System.currentTimeMillis(); | |
println "duration "+((end-start)/1000.0)+" s"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment