Non-abundant sums

来源:互联网 发布:杭州龙翔桥到淘宝城 编辑:程序博客网 时间:2024/05/22 18:35

问题:
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
译文:
28的因数为1,2,4,7,14。1+2+4+7+14=28,称28为完美数。
已知n,其因数和sum大于n,称n为多余数。12是最小的多余数,24是最小得可以有两个多余数相加。超过28123的任何数都可以写成两个多余数相加。
那么找出所有的无法由两个多余数组成的正整数之和。
思路:1、先求的多余数的函数,求出所有的多余数,然后,将遍历两位多余数相加,与1-28123对比,然后再去除可以表示成多余数的值,剩下的相加。
关于消除多余项有两种方法:
一、利用set()函数消除。二、利用新建一个0-28123的列表,然后对比,是的b[temp]=0,箱剩余的相加。

#查找所有的剩余数def abundant(n):    for i in range(n,0,-1):        sum1=0        if(i>=1):            for d in range(1,i//2+1):                if(i%d==0):                   sum1+=d            if (sum1>i):                yield i#生成器#求前n项和def Sum(n):    sum1=0    for i in range(n+1):        sum1+=i    return sum1#方法一a=[];b=[];sum1=0for i in abundant(28123):    a.append(i)for m in range(len(a)):    for n in range(m,len(a)):        if (a[m]+a[n]<=28123):            b.append(a[m]+a[n])b1=set(b)#生成集合,消除重复项print(Sum(28123)-sum(b1))#方法二:b=[i for i in range(28124)]for m in range(len(a)):    for n in range(m,len(a)):        if (a[m]+a[n]<=28123):            b[a[m]+a[n]]=0print(sum(b))

优化后得:

def abun(N):    Q = dict.fromkeys(range(1,N+1), 0)#生成字典[1-N]     for q in Q:#q=字典的键        for k in [q*n for n in range(1,N//q+1) ]:            if q!=k: Q[k] += q    return [ q  for q in Q if Q[q]>q]N = 20161; A = abun(N); possible = set() for a in A:    for b in A:        if a+b < N: possible.add( a+b )        else: breakprint (sum([p for p in range(N) if p not in possible]))

#声明优化后的代码是借鉴别人的不是原创
第三种方法:

from math import sqrtdef sumProperDivisors(num):    sum = 1    for i in range(2, int(sqrt(num))+ 1):        if num % i == 0:            sum += i            if i != num / i:                sum += num / i    return sumdef abundantNumber(num):    if sumProperDivisors(num) > num:        return True    else:        return Falsedef abundantSum(num, lst):    for x in lst:        if x > (num / 2):#24之前的所有数字都是False            return False        if num - x in lst:#求出所有的可以由多余数字组成的数            return True    return False    abs = []    #多余数的列表abs    for i in range(1,28124):        if abundantNumber(i):            abs.append(i)    total = 0    for i in range(1,28124):        if not abundantSum(i, abs):            total += i    print (total)

总结了两位大神的代码,深感自己的python编程能力有限,还要多多努力啊!

0 0
原创粉丝点击