Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nprimes <- function(n) {
res <- numeric(n)
cnt <- 1
x <- 2
while(cnt <= n) {
good <- TRUE
for(i in seq(2, sqrt(x))) {
if(x != i && x %% i == 0) {
good <- FALSE
break
}
}
if(good) {
res[cnt] <- x
cnt <- cnt + 1
}
x <- x + 1
}
res
}
p <- nprimes(250)
isprime <- function(x) {
x %in% p
}
valid <- function(x) {
for(i in seq_along(x[-1])) {
if(! isprime(x[i] + x[i+1])) return(FALSE)
}
return(TRUE)
}
solve <- function(stop=50) {
vals <- 1
iter <- 1
while(TRUE) {
if(valid(vals)) {
iter <- iter + 1
if(iter > stop) break
vals <- c(vals, iter)
} else {
change <- FALSE
if(isprime(vals[1] + iter)) {
vals <- c(iter, vals[-length(vals)])
change <- TRUE
} else {
for(i in seq(length(vals)-1,1)) {
if(isprime(vals[i] + iter)) {
if(isprime(vals[1] + vals[i+1])) {
vals <- c(vals[seq(length(vals)-1, i+1)], vals[seq(1, i)], iter)
change <- TRUE
break
} else if(isprime(vals[1] + vals[length(vals)-1])) {
vals <- c(vals[seq(i+1, length(vals)-1)], vals[seq(1, i)], iter)
change <- TRUE
break
}
}
}
}
if(!change) {
for(i in seq(1, length(vals)-1)) {
if(isprime(vals[i] + iter) && isprime(vals[i+1] + vals[length(vals)-1])) {
for(j in seq(i+1, length(vals)-1)) {
if(isprime(vals[j] + iter)) {
vals <- c(vals[seq(1,i)], iter, vals[seq(j, length(vals)-1)], vals[seq(i+1,j-1)])
change <- TRUE
break
}
}
}
}
}
if(!change) {
return('failed')
}
}
}
vals
}
solve(750)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment