Skip to content

Instantly share code, notes, and snippets.

@Koitaro
Created August 17, 2012 19:09
Show Gist options
  • Select an option

  • Save Koitaro/3381683 to your computer and use it in GitHub Desktop.

Select an option

Save Koitaro/3381683 to your computer and use it in GitHub Desktop.
R: Project Euler 50-59
library(pracma)
library(gmp)
p <- primes(1e6%/%21)
answer <- 0
maxLength <- 0
while (length(p) > 0) {
x <- rev((x <- cumsum(p))[x < 1e6])
while (length(x) > 0) {
if (length(x) <= maxLength) break
if (isprime(x[1]) > 0) {
if (length(x) > maxLength) {
answer <- x[1]
maxLength <- length(x)
}
break
}
x <- x[-1]
}
p <- p[-1]
}
answer
nextNum <- function(n) {
x <- 6*(n+3); y <- floor(log10(x))
if (y == floor(log10(n))) return(n+3) else 10^y+2
}
digits <- function(n) n %/% 10^(floor(log10(n)):0) %% 10
answer <- function(n) {
d <- digits(n)
setequal(d, digits(2*n)) &&
setequal(d, digits(3*n)) &&
setequal(d, digits(4*n)) &&
setequal(d, digits(5*n)) &&
setequal(d, digits(6*n))
}
n <- 1e5+2
repeat {if (answer(n)) break; n <- nextNum(n)}
n
answer <- 0
for (n in 1:100) {
x <- choose(n, 1:n)
answer <- answer + length(x[x > 1e6])
}
answer
library(gmp)
digits <- function(n) strsplit(as.character(n), "")[[1]]
addrev <- function(n) {
m <- rev(digits(n))
while (m[1] == "0") m <- m[-1]
n + as.bigz(paste(m, collapse=""))
}
palindrome <- function(n) {d <- digits(n); all(d == rev(d))}
Lychrel <- function(n) {
iterations <- 0
repeat {
if (iterations >= 50) return(TRUE)
iterations <- iterations + 1
n <- addrev(n)
if (palindrome(n)) return(FALSE)
}
}
length(Filter(Lychrel, 1:10000))
library(gmp)
f <- function (x, y) {
n <- pow.bigz(x, y)
sum(as.numeric(strsplit(as.character(n), "")[[1]]))
}
answer <- 0
for (x in 2:99) for (y in 2:99) {
n <- f(x, y)
if (n > answer) answer <- n
}
answer
library(gmp)
side <- 7
primes <- 8
total <- 13
repeat {
if (primes/total < 0.1) break
side <- side + 2
a <- side^2 - side + 1
b <- a - side + 1
c <- b - side + 1
primes <- primes + length((p <- sapply(c(a,b,c), isprime))[p > 0])
total <- total + 4
}
side
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment