# project euler: problem 62

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

The cube, 41063625 (345

^{3}), can be permuted to produce two other cubes: 56623104 (384^{3}) and 66430125 (405^{3}). 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

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.