Python programs to check if a number is a perfect number or not have been shown here. A perfect number is a positive integer that is equal to the sum of its proper divisors. For example 6 is a perfect number because if we add it's proper divisors (1, 2 and 3), we get 6 i.e. 1 + 2 + 3 = 6. Some of the other perfect numbers are 28, 496, 8128 etc.
Page content(s):
1. Algorithm to check if a number is a perfect number or not
1. Take a number n as input.
2. Set s = 0, x = 1
3. Check if n is divisible by x
4. If step 3 is true perform s = s + x
5. Set x = x + 1
6. Go step 3 until x > n/2
7. If s = n declare "n is a perfect number"
2. Pseudocode to check if a number is a perfect number or not
Input : A positive number n
Output : n is a perfect number or not
1. Procedure isPerfectNumber(n):
2.
3.
4.
5.
6.
7.
8.
9.
10.
11. End Procedure
3. Time complexity to check if a number is a perfect number or not
Time Complexity: O(n)
n is the input number
4. Program & Output to check if a number is a perfect number or not
4.1. Python Program & Output to check if a number is a perfect number or not using iteration
############################## # alphabetacoder.com # Python program to check if a # number is a perfect number ############################## # take input n = int(input("Enter the number: ")) # initialize s = 0 # add all the divisor upto n / 2 for i in range(1, (n // 2) + 1): if n % i == 0: s = s + i # check if the input number # is equal to the sum if n == s: print(n, "is a perfect number") else: print(n, "is not a perfect number")
Output
Case 1:
Enter the number: 6
6 is a perfect number
Case 2:
Enter the number: 50
50 is not a perfect number
Case 3:
Enter the number: 28
28 is a perfect number
4.2. Python Program & Output to check if a number is a perfect number or not using recursion
######################################### # alphabetacoder.com # Python program to check if a number is # a perfect number using recursion ######################################### # recursive function to check if input # number is a perfect number or not def isPerfect(n, i, s): if i > (n // 2): # exit condition return s == n # return true or false as per condition if n % i == 0: # check divisibility s += i # recursive call return isPerfect(n, i + 1, s) # main function def main(): # take input n = int(input("Enter the number: ")) # check if the input number is perfect # by calling function if isPerfect(n, 1, 0) == True: print(n, "is a perfect number") else: print(n, "is not a perfect number") # driver code main()
Output
Enter the number: 496
496 is a perfect number