# project euler: problem 62

December 3, 2012
By

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

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"))
user  system elapsed
0.414   0.001   0.416
```

#### Related Posts

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.