project euler-Problem 41

November 7, 2011
By

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

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

using gmp and permute package, this problem is very straightforward, and easy to solve.

?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
require(gmp)
require(permute)
maxP <- 0
 
vec2num <- function(vec) {
    m <- length(vec)
    n <-  sum(10^(m:1-1) * vec)
    return(n)
}
 
for (j in 9:4) {
    p <- allPerms(j, max=prod(1:j)*j)
    pn <- sapply(1:nrow(p), function(i) vec2num(p[i,]))
    idx <- isprime(pn) !=0
    if ( any(idx) ) {
        maxP <- max(pn[idx])
    }
    if (maxP != 0) {
        cat("The larget n-digit pandigital prime is ", maxP, "\n")
        break
    }
}
> system.time(source("problem41.R"))
The larget n-digit pandigital prime is  7652413 
   user  system elapsed 
  20.95    0.03   20.99 

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)