Perfect Number

Easy
0/40
Average time to solve is 10m
profile
Contributed by
5 upvotes
Asked in companies
IntuitDefine Next

Problem statement

You are given a positive integer K. Your task is to find out whether K is a perfect number or not.

Note :
Perfect numbers are those numbers that are equal to the sum of all its proper divisors. 

Proper divisors are all the divisors of a number excluding the number itself. 
For example :
For K = 6, the proper divisors of 6 are 1, 2, 3 and its sum is 6 so 6 is a perfect number. For K = 8, the proper divisors of 8 are 1, 2,4 and its sum is 7 so 8 is not a perfect number.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains a single integer T, representing the number of test cases. 

The first and the only line of each test case contains a single positive integer K, as described in the problem statement.
Output Format :
For each test case, return true if K is a perfect number or else return false.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraint :
1 <= T <= 100
2 <= K <= 10^8

Time Limit: 1 sec
Follow Up :
Can you do this in O(sqrt(N)) time and constant space?
Sample input 1 :
3
2
6
8
Sample output 1 :
False
True
False
Explanation For Sample Input 1 :
In the first test case, the only proper divisor of 2 is 1 so 2 is not a perfect number.

The test cases 2 and 3 are already explained above.
Sample input 2 :
3
10
28
12
Sample output 2 :
False
True
False
Hint

Can you think of iterating through all numbers?

Approaches (2)
Simple approach
  • Iterate through all the numbers from 1 to n-1 and if the number divides k then add it to the sum.
  • If the sum is equal to k then it is a perfect number.
Time Complexity

O(N), where N is the given number.

 

As we iterate through all numbers from 1 to n - 1.

Space Complexity

O(1)

 

Since we are using constant extra memory.

Code Solution
(100% EXP penalty)
Perfect Number
Full screen
Console