寻找完美数字的Python算法

时间:2018-10-24 13:17:58

标签: python python-3.x while-loop factors

请帮助您更正此代码!这是为了查找所有低于10,000的设置上限的理想数字,我已使用注释来解释我在做什么。谢谢!

#Stores list of factors and first perfect number
facs = []
x = 1

#Defines function for finding factors
def findfactors(num):

    #Creates for loop to find all factors of num
    for i in range(1, num + 1):
        if num % i == 0:

        #Stores factor in facs
        facs.append(i)


#Activates loop
while x < 10000:

    #Finds factors of x and appends them to list
    findfactors(x)

    #Finds sum of list
    facsum = sum(facs)

    #Makes decision based on  sum of factors and original number
    if facsum == x:

        #Ouputs and increases x
        print(x)
        x += 1

    else:

        #Increases x
        x += 1

4 个答案:

答案 0 :(得分:1)

  

在数论中,理想数是等于的正整数   与其适当的正除数之和,即   正除数,不包括数字本身(也称为   等分和)。第一个完美数字是6。下一个完美数字   是28。其后是完美数字496和8128。   (Wikipedia

您必须从因子列表中排除数字本身。

此外,对于每个facs,您都必须从空的x = 1 def findfactors(num): facs = [] for i in range(1, num): if num % i == 0: facs.append(i) return facs while x < 10000: facs = findfactors(x) facsum = sum(facs) if facsum == x: print(x) x += 1 else: x += 1 开始,然后追加到它后面。您不希望该列表中包含先前的数字因素。以下代码有效。

int ssum = 0;
int kount = 1;
int number = 11;
while (kount <= number) {
    ssum += kount;
    ++kount;

}
printf("Ssum is: %d \n", ssum);
printf("Kount is %d \n", kount);

答案 1 :(得分:0)

在def和return内部初始化列表,范围不应包含原始的num,因此范围应是从1到num的范围,包括1,但不包括原始的num,因此它将从{{ 1}}至1

num-1

比生成列表快得多 从What is the most efficient way of finding all the factors of a number in Python?

开始
#Stores list of factors and first perfect number
x = 1
#Defines function for finding factors
def findfactors(num):
    facs = []
    for i in range(1, num):
        if num % i == 0:
            #Stores factor in facs
            facs.append(i)

    return facs

#Activates loop
while x < 1000:

    #Finds factors of x and appends them to list
    facs=findfactors(x)

    #Finds sum of list
    facsum = sum(facs)

    #Makes decision based on  sum of factors and original number
    if facsum == x:
        #Ouputs and increases x
        print(x)
    x+= 1

答案 2 :(得分:0)

这是您逻辑的更简单实现。

x = 1

#Defines function for finding factors
def isperfectnum(num):
sum=0
    #Creates for loop to find all factors of num
    for i in range(1, num ):
        if num % i == 0:
           sum=sum+i
    if sum==num:
        return TRUE
    else 
        return FALSE

#Activates loop

while x < 10000:

    #Finds perfect numbers
    if isperfectnum(x):
       print(x)
    x=x+1

答案 3 :(得分:0)

发现问题了!

应该是:

for i in range(1, num - 1)

而不是:

for i in range(1, num + 1)

感谢所有贡献者!