0

所以我的任务是: 如果一个数字 n 的所有因子之和为 n + 1,则称为瘦。如果其所有因子之和大于 3*n,则将一个数字 n 称为胖。一个数字 n 被称为 Jack Sprat,如果它既是瘦的,而下一个数字 n + 1 是胖的。

我必须让用户输入一个数字,我必须说出它是瘦的、胖的还是 Jack Sprat。我还必须在 1 秒内打印出从 1 到 10000 的所有千斤顶数字。

这个程序大约需要 10 秒来完成

这是代码:

def isLean(n, t):
if t == n + 1:
    return True
else:
    return False

def isFat(n, t):
    if t > 3*num:
        return True
    else:
        return False

def isJackSprat(n, t, t2):
    if t == n+1 and t2 > 3*(n+1):
        return True
    else:
        return False

num = int(input("Please enter a number: "))

total = 0
total2 = 0
total3 = 0
total4 = 0
prime = ""

for factor in range(1,num+1):
    if num % factor == 0:
        total += factor

for factor in range(1,num+2):
    if (num+1) % factor == 0:
        total2 += factor

if isLean(num,total) == True:
    print ("Lean: Yes")
elif isLean(num,total) == False:
    print ("Lean: No")

if isFat(num,total) == True:
    print ("Fat: Yes")
elif isFat(num,total) == False:
    print ("Fat: No")

if isJackSprat(num, total, total2) == True:
    print ("Jack Sprat: Yes")
elif isJackSprat(num, total, total2) == False:
    print ("Jack Sprat: No")


print ("These are the Jack Sprat Numbers from 1 - 1000")

for count in range (1,10000):
    if count % 2 != 0:
        for factor in range (1,count+ 1):
            if factor %  2 != 0:
                if count % factor == 0:
                    total3 += factor
        for factor in range (1,count+2):
            if (count+1) % factor == 0:
                total4 += factor 
        if total3 == (count + 1) and total4 > 3*(count + 1):
            prime = prime + str(count) + ", "
        total3 = 0
        total4 = 0

print (prime[0:len(prime)-2])

如果我能得到一些帮助,我将不胜感激

4

2 回答 2

2

你可以通过让你的 for 循环只上升到数字的平方根来获得很大的速度。每个小于平方根的因子都会有一对大于平方根的因子,因此您只需迭代到平方根即可找到所有因子。

于 2017-05-09T00:46:00.870 回答
0

像 Eratosthenes 的筛子一样尝试它,但不是布尔数组和划掉,而是有一个 int 数组,它为每个索引建立其因子的总和。我只是这样做了,大约需要 0.05 秒才能找到所有 Jack Sprat 数字,最多 10000(与您的代码找到的相同)。

于 2017-05-09T01:16:28.873 回答