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 an Armstrong number (153 = 1³ + 5³ + 3³) using a loop.
Input
153, 154
Output
153 is an Armstrong number
154 is not an Armstrong number
Approach
Count the digits, then add each digit raised to that power.
Solution
Python
fornin[153,154]:power=len(str(n))total,temp=0,nwhiletemp>0:total+=(temp%10)**powertemp//=10print(n,"is an Armstrong number"iftotal==nelse"is not an Armstrong number")
Output
153 is an Armstrong number
154 is not an Armstrong number
Line by line
Line 2
The power equals the number of digits.
Lines 4-6
The loop peels off digits and adds their powers.
Learn the concept
New to this topic? Read the lesson, then come back.