How to Get Perfect Numbers in a Given Range with Python


Here this example introduces how to get perfect numbers in the range of 1-1000 using Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def Pnum(a):
    b = []
    for i in range(1,a):
        if a%i==0 and i!=a:
            b.append(i)
    if sum1(b)==a:
        c = []
        c.append(a)
        print(c)

def sum1(x):
    s = 0
    for i in range(0,len(x)):
        s =s + int(x[i])
    return s

print('Perfects numbers in the range of 1-1000:')

for i in range(1,1001):
    Pnum(i)

Output:

Perfects numbers in the range of 1-1001:
[6]
[28]
[496]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments