Write a Python program to check whether a number is perfect: the sum of its factors (excluding itself) equals the number, like 28 = 1 + 2 + 4 + 7 + 14.
Input
28, 12
Output
28 is perfect
12 is not perfect (factor sum 16)
Approach
Add every divisor smaller than n and compare.
Solution
Python
fornin[28,12]:total=0fordinrange(1,n):ifn%d==0:total+=dprint(n,"is perfect"iftotal==nelsef"is not perfect (factor sum {total})")
Output
28 is perfect
12 is not perfect (factor sum 16)
Line by line
Line 3
Divisors are tested up to n – 1, so the number itself is excluded.
Learn the concept
New to this topic? Read the lesson, then come back.
Write a Python program to check whether a number is prime using a loop.
Input
97, 91
Output
97 is prime
91 is not prime, divisible by 7
Approach
Use for ... else: the else runs only if no divisor was found.
Solution
Python
fornin[97,91]:ifn<2:print(n,"is not prime")continuefordinrange(2,int(n**0.5)+1):ifn%d==0:print(n,"is not prime, divisible by",d)breakelse:print(n,"is prime")
Output
97 is prime
91 is not prime, divisible by 7
Line by line
Lines 5-8
break stops the search at the first divisor.
Lines 9-10
The else belongs to the for; it runs only when the loop finished without break.
Learn the concept
New to this topic? Read the lesson, then come back.