問題
10以下の素数の和は2 + 3 + 5 + 7 = 17である.200万以下の全ての素数の和を計算しなさい.
問題を解いたプログラム
処理時間はものすごくかかります。(3分弱かな)import common.Prime
def prime = new Prime()
def sum = prime.primes(2000000).sum()
println "sum = ${sum}"
Primeクラスはのprimesはiteratorを返すようにしてます。
package common
class Prime {
def primes(int max) {
return new Iterator<Long>() {
def primes = []
boolean hasNext() {
def start = primes ? primes.max() + 1 : 2
def result = (start..max).findResult {
if (isPriem(it)) {
it
}
}
if (result) {
primes << result
primes.last() < max
} else {
false
}
}
Long next() {
primes.last()
}
void remove() {
throw new UnsupportedOperationException()
}
private def isPriem(int num) {
if (num == 2) {
true
} else if (num % 2 == 0) {
false
} else {
def sqrt = Math.sqrt(num).toInteger()
primes.findResult(true) {
if (it > sqrt) {
true
} else if (num % it == 0) {
false
}
}
}
}
};
}
}