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

全部博文(47)

文章存档

2008年(47)

我的朋友

分类:

2008-11-14 18:23:13

Problem 43

09 May 2003

The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.

Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:

  • d2d3d4=406 is divisible by 2
  • d3d4d5=063 is divisible by 3
  • d4d5d6=635 is divisible by 5
  • d5d6d7=357 is divisible by 7
  • d6d7d8=572 is divisible by 11
  • d7d8d9=728 is divisible by 13
  • d8d9d10=289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.

1.最后三位能被17整除

2.第6位只能是0或5

3.第4位只能是偶数

def isOk43(num):
    primes = [2,3,5,7,11,13,17]
    if (num[5] != '0') and (num[5] != '5'):
        return False
    for i in range(1, 8):
        t = int(num[i:i+3])
        if (t%primes[i-1]) != 0:
            return False
    return True
   

def fun43():
    result = 0
    for i in permutation(range(10), 10):
        i = "".join(map(str, i))
        if isOk43(i):
            result += int(i)
            print i
    return result
       
def isUnique(n):
    #判断n中是否有重复的字母
    n = str(n)
    b = set(n)
    return len(b) == len(n)
   
def fun43Quick():
    i      = 6
    result = 0
    h      = {}
    while 1:
        t = 17*i
        if t>100 and t<1000:
            if isUnique(t):
                if h.has_key(t):
                    i += 1
                    continue
                else:
                    h[t] = True
                #print t
                   
                l = range(10)
               
                for j in map(int, str(t)):
                    l.remove(j)
                for k in permutation(l, len(l)):
                    num = "".join(map(str, k))+str(t)
                    if isOk43(num):
                        print num
                        result += int(num)
            else:
                i += 1
                continue
        elif t >= 1000:
                break
    return result

程序中只用到了前两个条件,在fun43()中,我们遍历所有的组合,消耗时间过长141.657000065
在加上前两个条件后,可以将时间缩短为6.1099998951
answer is 16695334890,
符合条件的数有1406357289, 460357289, 4106357289, 4160357289, 1430952867, 4130952867
阅读(488) | 评论(0) | 转发(0) |
0

上一篇:Problem 42

下一篇:Problem 44

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