A number is a perfect number if is equal to sum of its proper divisors, that is, sum of its positive divisors excluding the number itself. Write a function to check if a given number is perfect or not.
Input: n = 15 Output: false Divisors of 15 are 1, 3 and 5. Sum of divisors is 9 which is not equal to 15. Input: n = 6 Output: true Divisors of 6 are 1, 2 and 3. Sum of divisors is 6.
A Simple Solution is to go through every number from 1 to n-1 and check if it is a divisor. Maintain sum of all divisors. If sum becomes equal to n, then return true, else return false.
An Efficient Solution is to go through numbers till square root of n. If a number ‘i’ divides n, then add both ‘i’ and n/i to sum.
Below is the implementation of efficient solution.
Below are all perfect numbers til 10000 6 is a perfect number 28 is a perfect number 496 is a perfect number 8128 is a perfect number
Time Complexity: √n
Below are some interesting facts about Perfect Numbers:
1) Every even perfect number is of the form 2p?1(2p ? 1) where 2p ? 1 is prime.
2) It is unknown whether there are any odd perfect numbers.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find smallest perfect square number A such that N + A is also a perfect square number
- Find minimum number to be divided to make a number a perfect square
- Minimum divisor of a number to make the number perfect cube
- Number of times the largest perfect square number can be subtracted from N
- Previous perfect square and cube number smaller than number N
- Count numbers upto N which are both perfect square and perfect cube
- Anti-perfect Number
- Perfect totient number
- Multiply perfect number
- Check if given number is perfect square
- Number of perfect cubes between two given numbers
- Perfect cube greater than a given number
- Program to check Plus Perfect Number
- Count all perfect divisors of a number
- Largest number that is not a perfect square
- Perfect Digital Invariants number
- Number of perfect squares between two given numbers
- Count number less than N which are product of perfect squares
- Largest number in an array that is not a perfect cube
- Largest factor of a given number which is a perfect square