def classify(numb):
i=1
j=1
sum=0
for i in range(numb):
for j in range(numb):
if (i*j==numb):
sum=sum+i
sum=sum+j
if sum>numb:
print("The value",numb,"is an abundant number.")
elif sum<numb:
print("The value",numb,"is a deficient number.")
else:
print("The value",numb,"is a perfect number.")
break
return "perfect"
代码采用数字(麻木)并将其分类为丰富,不足或完美的数字。我的输出是搞砸的,只适用于某些数字。我认为它是缩进或我使用不正确的休息。非常感谢帮助。
答案 0 :(得分:2)
我强烈建议你创建一个函数来创建给定N的正确除数,然后,这项工作就很容易了。
def get_divs(n):
return [i for i in range(1, n) if n % i == 0]
def classify(num):
divs_sum = sum(get_divs(num))
if divs_sum > num:
print('{} is abundant number'.format(num))
elif divs_sum < num:
print('{} is deficient number'.format(num))
elif divs_sum == num:
print('{} is perfect number'.format(num))
答案 1 :(得分:0)
某处你误解了某些东西。就像你打印什么样的数字一样,多少是数字的值。无论如何,我可能会遗漏一些东西。
通过使用modulo
可以天真地找到适当除数的总和def classify1(num):
div_sum = sum(x for x in range(1, num) if num % x == 0)
kind = ""
if div_sum < num:
kind = "deficient"
elif div_sum > num:
kind = "abundant"
else:
kind = "perfect"
print("{} is a {} number".format(num, kind))
但对于大数字或数字,这将需要很长时间。所以我欢迎你接受除数功能。我只是抛弃它并解释它。
def mark(li: list, x: int):
for i in range(2*x, len(li), x):
li[i] = False
return li
def sieve(lim: int):
li = [True] * lim
li[0] = li[1] = 0
for x in range(2, int(lim ** 0.5) + 1):
if x:
li = mark(li, x)
return [2]+[x for x in range(3, lim, 2) if li[x]]
def factor(num):
divs = list()
for prime in primes:
if prime * prime > num:
if num > 1:
divs += [num]
return divs
while num % prime == 0:
num //= prime
divs += [prime]
else:
return divs
def divisors_sum(num):
"""
Function that implements a geometric series to generate the sum of the
divisors, but it is not the divisor function since removing original
number.
"""
divs = factor(num)
div_sum, s = 1, 0
for div in set(divs):
s = 0
for exponent in range(0, divs.count(div) + 1):
s += div ** exponent
div_sum *= s
else:
return div_sum - num
primes = sieve(limit)
但是..没有太多解释到期,第一个素数因子,并使用除数函数得到适当的除数和。这就对了。然而,加速速度非常快。这似乎可以解决问题,但它更酷,更快。