project euler: problem 62

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 
zv7qrnb

Related Posts

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>