Chinaunix首页 | 论坛 | 博客
  • 博客访问: 86577
  • 博文数量: 47
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 625
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-11 12:11
文章分类

全部博文(47)

文章存档

2008年(47)

我的朋友

分类:

2008-11-14 11:53:45

Problem 32

06 December 2002

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.
    
def fun32():
    s = range(1, 10)
    result = []
    for i in permutation(s, 9):
        t = "".join(map(str, i))
        (a, b, c) = map(int, [t[0], t[1:5], t[5:]])
        if b < c and a*b == c:
            print a, b, c
            result.append(c)
        (a, b, c) = map(int, [t[0:2], t[2:5], t[5:]])
        if a*b == c:
            print a, b, c
            result.append(c)
    return reduce(add, set(result))

直接遍历所有的1-9的排列进行判断,获取排列函数permutation为    
def permutation(s, n):
    #从s中选取n进行排列
    if (n > len(s)) or (n <= 0) or (len(s) == 0):
        return
       
    if n == 1:
        for i in range(len(s)):
            yield [s[i]]
    else:
        for i in s:
            #print i, len(s), r
            st = list(s)
            st.remove(i)
            for j in permutation(st, n-1):
                yield [i] + j

  
answer is 45228
time:13.6879999638, 花费时间太长了

我们可以判断出a*b=c的c只能是4或5位数,这样我们只遍历[1-9]组成的4或5位数,可以减少计算量。
阅读(349) | 评论(0) | 转发(0) |
0

上一篇:排列组合

下一篇:Problem 35

给主人留下些什么吧!~~