# project euler – Problem 44

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**YGC » R**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.