(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.
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 his blog: YGC » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series,ecdf, trading) and more...

Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).