project euler - Problem 32

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

Very similar to what I implemented in Problem 41.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
vec2num <- function(vec) {
    m <- length(vec)
    n <-  sum(10^(m:1-1) * vec)
    return(n)
}
 
 
j <- 9
p <- allPerms(j, max=prod(1:j)*j)
s <- 0
for (i in 1:nrow(p)) {
    product <-  vec2num(p[i,6:9])
    if (vec2num(p[i,1:2]) * vec2num(p[i,3:5]) == product) {
        s <- c(s,product)
    }
    if (vec2num(p[i,1]) * vec2num(p[i,2:5]) == product) {
        s <- c(s,product)
    }
}
 
print(sum(unique(s)))
> system.time(source("Problem32.R"))
[1] 45228
   user  system elapsed 
  35.32    0.04   35.45 

Related Posts

  1. project euler-Problem1-50 | YGC United States Unknow Browser Unknow Os - pingback on November 9, 2011 at 3:48 pm
  2. Mathematica version:
    With[{id = IntegerDigits},
    Union @@Table[If[a*b <= 9876 && Union[id[a], id[b], id[a*b]] == Range[9], a*b, 0],
    {a, 123, 1987}, {b, 2, 98}] // Tr
    ]
    运行时间<0.1s

    Reply

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>