project euler - Problem 44

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 

Related Posts

  1. pentagonal = function(x) x*(3*x-1)/2
    is.whole <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
    is.pentagonal = function(x) is.whole(( sqrt(1 + 24*x) + 1 ) / 6)
    a = pentagonal(1000:2400)
    b = as.data.frame(t(combn(a,2)))
    b$V3 = b[2]-b[1]
    b$V4 = b[2]+b[1]
    b = b[is.pentagonal(b[3])&is.pentagonal(b[4]),][3]
    V2
    28957 5482660

    Reply

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>