project euler – Problem 44

November 8, 2011
By

(This article was first published on YGC » R, and kindly contributed to R-bloggers)

Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:

1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk − Pj| is minimised; what is the value of D?


Calculate differences directly and test the differences to be pentagonal, if so test the sum to be pentagonal.
Use a while loop for have no idea the upper limit should be.

is.pent <- function(x) {
n <- (1 + sqrt(24*x+1))/6
if (n == floor(n)) {
return(TRUE)
} else {
return(FALSE)
}
}

n <- 2
flag <- TRUE
pent <- 1
while(flag) {
p <- n*(3*n-1)/2
diff <- p-pent
for (i in 1:length(diff)) {
if(is.pent(diff[i])) {
s <- p+pent[i]
if (is.pent(s)) {
print(diff[i])
flag <- FALSE
}
}
}
pent <- c(pent,p)
n <- n+1
}

> system.time(source("Problem44.R"))
[1] 5482660
user  system elapsed
12.64    0.00   12.67