# project euler: problem 62

December 3, 2012
By

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

The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.Find the smallest cube for which exactly five permutations of its digits are cube.

I tried to generate all the cubic number with specific length, and iterate until exactly five numbers have the same digits.

?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 23 24 25 26 27 28 29 ``` ```getCubicNumber <- function(ndigit) { lower <- floor(10^((ndigit-1)/3)) upper <- floor(10^(ndigit/3)) cube <- (lower:upper)^3 return(cube) }   cubicPermutation <- function(nperm) { ndigit <- 1 flag <- TRUE while(flag) { ndigit <- ndigit+1 cubeNumber <- getCubicNumber(ndigit) cube <- sapply(as.character(cubeNumber), function(i) paste(sort(unlist(strsplit(i, split=""))), collapse=""))   cnt <- table(cube)   d <- names(cnt[cnt == nperm]) if (length(d)) { permDigits <- lapply(d, function(i) names(cube[cube==i])) res <- min(sapply(permDigits, min)) flag <- FALSE } } return(res) }   cat("Answer of PE 62: ", cubicPermutation(5), "\n")```

This code runs in half a second.

```> system.time(source("problem62.R"))
Answer of PE 62:  127035954683
user  system elapsed
0.414   0.001   0.416
```

#### Related Posts

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...

## Recent popular posts

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)