-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathperfect_number.py
More file actions
38 lines (31 loc) · 848 Bytes
/
Copy pathperfect_number.py
File metadata and controls
38 lines (31 loc) · 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from math import isqrt
def is_perfect(num):
"""
This function checks if num is a perfect number.
Note that a number is said to be perfect if it
matches the sum of all of its divisors, excluding
itself.
For example: 6 = 1 + 2 + 3, 28 = 1 + 2 + 4 + 7 + 14,
and 496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248,
are all perfect numbers.
Time complexity: O(sqrt(n)), with sqrt being square root
Space complexity: O(1)
"""
if num <= 5:
return False
sum = 1
for div in range(2, isqrt(num) + 1):
if num % div == 0:
sum += div + num // div
if sum > num:
return False
return (num == sum)
print("All perfect numbers below 100: ")
for n in range(100):
"""
The below prints:
6
28
"""
if is_perfect(n):
print(n)