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 

Related Posts

To leave a comment for the author, please follow the link and comment on their blog: YGC » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Mango solutions



RStudio homepage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



http://www.eoda.de







ODSC

ODSC

CRC R books series











Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)