Project Euler Problem 10
10以下の素数の和は2 + 3 + 5 + 7 = 17である. 200万以下の全ての素数の和を計算しなさい.
これはエラトステネスの篩のおかげで瞬殺です.エラトステネス様様です.
eratosthenes <- function(x){ x_0 <- (x-1)/2 d <- rep(TRUE, x_0) l <- (sqrt(x) - 1) / 2 p <- 1 w <- 5 #which を行う範囲 while (p < l) { step <- p * 2 + 1 d[seq(p+step, x_0, step)] <- FALSE while(is.na(tmp <- which(d[(p+1):(p+w+1)])[1] + p)) { w <- w * 2 } p <- tmp } c(2,seq(3,x,2)[d]) } sum(eratosthenes(2000000))