Python完美数字

时间:2016-02-19 02:27:23

标签: python

所以我应该编写一个Python程序,在一些封闭的区间[2,n]中识别并打印所有完美的数字,每行一个。我们只需要使用嵌套的while循环/ if-else语句。我以某种方式使用for循环做了它,但是使用while循环无法弄清楚它。如果您能告诉我如何将我的代码翻译成while循环,我将非常感谢您的帮助。多谢你们。这就是我所拥有的:

limit = int(input("enter upper limit for perfect number search: "))

for n in range(2, limit + 1):
    sum = 0
    for divisor in range(1, n):
        if not n % divisor:
            sum += divisor
        if sum == n:
            print(n, "is a perfect number")

5 个答案:

答案 0 :(得分:5)

您可以使用以下内容替换for循环:

n = 2
while n < limit + 1:
   ...
   divisor = 1
   while divisor < n:
      ...
      divisor += 1
   ...
   n += 1

提示:您也可以使用n/2作为第二个循环的上限,因为n的任何除数不能大于n/2

答案 1 :(得分:4)

这是一个(更有效的)筛选版本:

# search all numbers in [2..limit] for perfect numbers
# (ones whose proper divisors sum to the number)
limit = int(input("enter upper limit for perfect number search: "))

# initialize - all entries are multiples of 1
#   (ignore sieve[0] and sieve[1])
sieve = [1] * (limit + 1)

n = 2
while n <= limit:
    # check n
    if sieve[n] == n:
        print(n, "is a perfect number")
    # add n to all k * n where k > 1
    kn = 2 * n
    while kn <= limit:
        sieve[kn] += n
        kn += n
    n += 1

将其运行到10000次

6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number

并将这些因素分解为一个有趣的模式:

6          3 * 2                         (  4 - 1) * (  4 / 2)
28         7 * 2 * 2                     (  8 - 1) * (  8 / 2)
496       31 * 2 * 2 * 2 * 2             ( 32 - 1) * ( 32 / 2)
8128     127 * 2 * 2 * 2 * 2 * 2 * 2     (128 - 1) * (128 / 2)

其中第一个因子(3,7,31,127)是一个小于2的幂的素数,它乘以2的相同幂的一半。此外,所涉及的权力是素数(2**22**32**52**7)。

事实上,Euclid证明(2**p - 1) * 2**(p - 1)是一个完美的数字,如果2**p - 1是素数,只有p是素数才有可能(虽然不能保证)。欧拉走得更远,证明所有即使是完美的数字也必须是这种形式。

这表明令人难以置信的更高效的版本 - 我将继续使用for循环,随意重写它。首先,我们需要一个素数源和一个is_prime测试:

def primes(known_primes=[7, 11, 13, 17, 19, 23, 29]):
    """
    Generate every prime number in ascending order
    """
    # 2, 3, 5 wheel
    yield from (2, 3, 5)
    yield from known_primes
    # The first time the generator runs, known_primes
    #   contains all primes such that  5 < p < 2 * 3 * 5
    # After each wheel cycle the list of known primes
    #   will be added to.
    # We need to figure out where to continue from,
    #   which is the next multiple of 30 higher than
    #   the last known_prime:
    base = 30 * (known_primes[-1] // 30 + 1)
    new_primes = []
    while True:
        # offs is chosen so  30*i + offs cannot be a multiple of 2, 3, or 5
        for offs in (1, 7, 11, 13, 17, 19, 23, 29):
            k = base + offs    # next prime candidate
            for p in known_primes:
                if not k % p:
                    # found a factor - not prime
                    break
                elif p*p > k:
                    # no smaller prime factors - found a new prime
                    new_primes.append(k)
                    break
        if new_primes:
            yield from new_primes
            known_primes.extend(new_primes)
            new_primes = []
        base += 30

def is_prime(n):
    for p in primes():
        if not n % p:
            # found a factor - not prime
            return False
        elif p * p > n:
            # no factors found - is prime
            return True

然后搜索看起来像

# search all numbers in [2..limit] for perfect numbers
# (ones whose proper divisors sum to the number)
limit = int(input("enter upper limit for perfect number search: "))

for p in primes():
    pp = 2**p
    perfect = (pp - 1) * (pp // 2)
    if perfect > limit:
        break
    elif is_prime(pp - 1):
        print(perfect, "is a perfect number")

找到

enter upper limit for perfect number search: 2500000000000000000
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
33550336 is a perfect number
8589869056 is a perfect number
137438691328 is a perfect number
2305843008139952128 is a perfect number

在一秒钟内; - )

答案 2 :(得分:3)

这应该有效:

limit = int(input("enter upper limit for perfect number search: "))

n = 1

while n <= limit:

    sum = 0
    divisor = 1
    while divisor < n:
        if not n % divisor:
            sum += divisor
        divisor = divisor + 1
    if sum == n:
        print(n, "is a perfect number")
    n = n + 1

答案 3 :(得分:0)

我正在共享此代码以供选择。完美数的形式为[2 ^ {n-1}(2 ^ {n} -1)],其中2 ^ {n} -1和n都是素数。

for num in range(2,101):
if all(num%i!=0 for i in range(2,num)):
    num_2=num*2-1
    for num_2 in range(2,101):
        if all(num_2%i!=0 for i in range(2,num_2)):
            MükemmelSayı=2**(num-1)*(2**num-1)
            print(MükemmelSayı)
            break
        break

答案 4 :(得分:-1)


    enter code here
T = int(input())
list1 = list()
for i in range(0,T):
    N = int(input())
    list1.append(N)
    list1 = [int(i) for i in list1]
sum = 0
for ele in list1:
    for j in range(1,ele):
        if ele % j == 0:
            sum = sum + j
    if sum==ele:
        print('True')
    else:
        print('false')