The Wayback Machine - https://web.archive.org/web/20240914014508/https://www.geeksforgeeks.org/perfect-number/
Open In App

Perfect Number

Last Updated : 25 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
17.21%
1.8L

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. 
Examples: 

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.

 

Recommended Practice

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. 
 

C++




// C++ program to check if a given number is perfect
// or not
#include<iostream>
using namespace std;
 
// Returns true if n is perfect
bool isPerfect(long long int n)
{
    // To store sum of divisors
    long long int sum = 1;
  
    // Find all divisors and add them
    for (long long int i=2; i*i<=n; i++)
    {
        if (n%i==0)
        {
            if(i*i!=n)
                sum = sum + i + n/i;
            else
                sum=sum+i;
        }
    }
     // If sum of divisors is equal to
     // n, then n is a perfect number
     if (sum == n && n != 1)
          return true;
  
     return false;
}
  
// Driver program
int main()
{
    cout << "Below are all perfect numbers till 10000\n";
    for (int n =2; n<10000; n++)
        if (isPerfect(n))
            cout << n << " is a perfect number\n";
  
    return 0;
}


Java




// Java program to check if a given
// number is perfect or not
import java.io.*;
public class GFG
{
     
// Returns true if n is perfect
static boolean isPerfect(int n)
{
    // To store sum of divisors
    int sum = 1;
 
    // Find all divisors and add them
    for (int i = 2; i * i <= n; i++)
    {
        if (n % i==0)
        {
            if(i * i != n)
                sum = sum + i + n / i;
            else
                sum = sum + i;
        }
    }
    // If sum of divisors is equal to
    // n, then n is a perfect number
    if (sum == n && n != 1)
        return true;
 
    return false;
}
 
// Driver program
public static void main (String[] args)
{
    System.out.println("Below are all perfect" +
                                "numbers till 10000");
    for (int n = 2; n < 10000; n++)
        if (isPerfect(n))
            System.out.println( n +
                    " is a perfect number");
}
}
 
// This code is contributed by mits


Python3




# Python3 code to check if a given
# number is perfect or not
 
# Returns true if n is perfect
def isPerfect( n ):
     
    # To store sum of divisors
    sum = 1
     
    # Find all divisors and add them
    i = 2
    while i * i <= n:
        if n % i == 0:
            sum = sum + i + n/i
        i += 1
     
    # If sum of divisors is equal to
    # n, then n is a perfect number
     
    return (True if sum == n and n!=1 else False)
 
# Driver program
print("Below are all perfect numbers till 10000")
n = 2
for n in range (10000):
    if isPerfect (n):
        print(n , " is a perfect number")
         
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# program to check if a given
// number is perfect or not
 
class GFG
{
     
// Returns true if n is perfect
static bool isPerfect(int n)
{
    // To store sum of divisors
    int sum = 1;
 
    // Find all divisors and add them
    for (int i = 2; i * i <= n; i++)
    {
        if (n % i==0)
        {
            if(i * i != n)
                sum = sum + i + n / i;
            else
                sum = sum + i;
        }
    }
    // If sum of divisors is equal to
    // n, then n is a perfect number
    if (sum == n && n != 1)
        return true;
 
    return false;
}
 
// Driver program
static void Main()
{
    System.Console.WriteLine("Below are all perfect" +
                                "numbers till 10000");
    for (int n = 2; n < 10000; n++)
        if (isPerfect(n))
            System.Console.WriteLine( n +
                    " is a perfect number");
}
}
 
// This code is contributed by chandan_jnu


Javascript




<script>
 
// Javascript program to check if a given number is perfect
// or not
 
// Returns true if n is perfect
function isPerfect(n)
{
    // To store sum of divisors
    sum = 1;
 
    // Find all divisors and add them
    for (let i=2; i*i<=n; i++)
    {
        if (n%i==0)
        {
            if(i*i!=n)
                sum = sum + i + n/i;
            else
                sum=sum+i;
        }
    }
    // If sum of divisors is equal to
    // n, then n is a perfect number
    if (sum == n && n != 1)
        return true;
 
    return false;
}
 
// Driver program
  
    document.write("Below are all perfect numbers till 10000" + "<br>");
    for (let n =2; n<10000; n++)
        if (isPerfect(n))
            document.write(n + " is a perfect number" + "<br>");
 
// This code is contributed by Mayank Tyagi
 
</script>


PHP




<?php
// PHP program to check if a given number
// is perfect or not
 
// Returns true if n is perfect
function isPerfect($n)
{
    // To store sum of divisors
    $sum = 1;
 
    // Find all divisors and add them
    for ($i = 2; $i * $i <= $n; $i++)
    {
        if ($n % $i == 0)
        {
            if($i * $i != $n)
                $sum = $sum + $i + (int)($n / $i);
            else
                $sum = $sum + $i;
        }
    }
    // If sum of divisors is equal to
    // n, then n is a perfect number
    if ($sum == $n && $n != 1)
        return true;
 
    return false;
}
 
// Driver Code
echo "Below are all perfect numbers till 10000\n";
for ($n = 2; $n < 10000; $n++)
    if (isPerfect($n))
        echo "$n is a perfect number\n";
 
// This code is contributed by mits
?>


Output

Below are all perfect numbers till 10000
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number


Time Complexity: O(?n)
Auxiliary Space: O(1), since no extra space has been taken.
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.
 



Similar Reads

Find smallest perfect square number A such that N + A is also a perfect square number
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.Examples: Input: N = 3 Output: 1 Explanation: As 1 + 3 = 4 = 22 Input: N=1 Output: -1 Naive Approach: Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
9 min read
Check if a number is a perfect square having all its digits as a perfect square
Given an integer N, the task is to check if the given number is a perfect square having all its digits as a perfect square or not. If found to be true, then print “Yes”. Otherwise, print “No”.Examples: Input: N = 144 Output: Yes Explanation: The number 144 is a perfect square and also the digits of the number {1(= 12, 4(= 22} is also a perfect squa
11 min read
Print all Perfect Numbers from an array whose sum of digits is also a Perfect Number
Given an array arr[] of size N, the task is to print all the perfect numbers from an array whose sum of digits is also a perfect number. Examples: Input: arr[] = { 3, 8, 12, 28, 6 }Output: 6Explanation: The array element arr[4] (= 6) is a perfect number. The array element arr[3] (= 28) is a perfect number but its sum of digits (= 10) is not a perfe
8 min read
Count numbers upto N which are both perfect square and perfect cube
Given a number N. The task is to count total numbers under N which are both perfect square and cube of some integers.Examples: Input: N = 100Output: 2They are 1 and 64.Input: N = 100000Output: 6Naive Approach: The idea is to use the power, square_root and cube_root functions from the math library. C/C++ Code // C++ program for the above approach #i
5 min read
Number of times the largest perfect square number can be subtracted from N
Given a number N. At every step, subtract the largest perfect square( ? N) from N. Repeat this step while N &gt; 0. The task is to count the number of steps that can be performed. Examples: Input: N = 85 Output: 2 First step, 85 - (9 * 9) = 4 Second step 4 - (2 * 2) = 0 Input: N = 114 Output: 4 First step, 114 - (10 * 10) = 14 Second step 14 - (3 *
7 min read
Minimum divisor of a number to make the number perfect cube
Given a positive integer N, the task is to find the minimum divisor by which it shall be divided to make it a perfect cube. If N is already a perfect cube, then print 1.Examples: Input : N = 128 Output : 2 By Dividing N by 2, we get 64 which is a perfect cube. Input : n = 6 Output : 6 By Dividing N by 6, we get 1 which is a perfect cube. Input : n
6 min read
Previous perfect square and cube number smaller than number N
Given an integer N, the task is to find the previous perfect square or perfect cube smaller than the number N.Examples: Input: N = 6 Output: Perfect Square = 4 Perfect Cube = 1 Input: N = 30 Output: Perfect Square = 25 Perfect Cube = 27 Approach: Previous perfect square number less than N can be computed as follows: Find the square root of given nu
5 min read
Find minimum number to be divided to make a number a perfect square
Given a positive integer n. Find the minimum number which divide n to make it a perfect square.Examples: Input : n = 50 Output : 2 By Dividing n by 2, we get which is a perfect square. Input : n = 6 Output : 6 By Dividing n by 6, we get which is a perfect square. Input : n = 36 Output : 1 A number is perfect square if all prime factors appear even
7 min read
Minimum digits to remove to make a number Perfect Square
Given an integer n, we need to find how many digits remove from the number to make it a perfect square. Examples : Input : 8314 Output: 81 2 Explanation: If we remove 3 and 4 number becomes 81 which is a perfect square. Input : 57 Output : -1 The idea is to generate all possible subsequences and return the optimal string using set bits. Let's suppo
9 min read
Check whether the number formed by concatenating two numbers is a perfect square or not
Given two numbers a and b and the task is to check whether the concatenation of a and b is a perfect square or not.Examples: Input: a = 1, b = 21 Output: Yes 121 = 11 × 11, is a perfect square. Input: a = 100, b = 100 Output: No 100100 is not a perfect square. Approach: Initialize the number as strings initially and concatenate them. Convert the st
4 min read
Perfect cube greater than a given number
Given a number N, the task is to find the next perfect cube greater than N.Examples: Input: N = 6 Output: 8 8 is a greater number than 6 and is also a perfect cube Input: N = 9 Output: 27 Approach: Find the cube root of given N.Calculate its floor value using floor function in C++.Then add 1 to it.Print cube of that number. Below is the implementat
3 min read
Count number less than N which are product of perfect squares
Given an Integer N. The task is to count numbers P less than N such that P is a product of two distinct perfect squares. Examples: Input : N = 36 Output : 5 Numbers are 4 = 12 * 22, 9 = 12 * 32, 16 = 12 * 42, 25 = 12 * 52, 36 = 12 * 62Input : N = 1000000 Output : 999 Approach: Let us consider a number P = (a2 * b2) such that P &lt;= N. So we have (
3 min read
Largest perfect square number in an Array
Given an array of n integers. The task is to find the largest number which is a perfect square. Print -1 if there is no number that is perfect square.Examples: Input : arr[] = {16, 20, 25, 2, 3, 10} Output : 25 Explanation: 25 is the largest number that is a perfect square. Input : arr[] = {36, 64, 10, 16, 29, 25| Output : 64 A Simple Solution is t
8 min read
Largest number in an array that is not a perfect cube
Given an array of n integers. The task is to find the largest number which is not a perfect cube. Print -1 if there is no number that is a perfect cube. Examples: Input: arr[] = {16, 8, 25, 2, 3, 10} Output: 25 25 is the largest number that is not a perfect cube. Input: arr[] = {36, 64, 10, 16, 29, 25} Output: 36 A Simple Solution is to sort the el
8 min read
Largest perfect cube number in an Array
Given an array of N integers. The task is to find the largest number which is a perfect cube. Print -1 if there is no number that is perfect cube. Examples: Input : arr[] = {16, 8, 25, 2, 3, 10} Output : 25 Explanation: 25 is the largest number that is a perfect cube. Input : arr[] = {36, 64, 10, 16, 29, 25| Output : 64 A Simple Solution is to sort
7 min read
Largest Divisor of a Number not divisible by a perfect square
Given a positive integer, N. Find the largest divisor of the given number that is not divisible by a perfect square greater than 1. Examples: Input : 12 Output : 6 Explanation : Divisors of 12 are 1, 2, 3, 4, 6 and 12. Since 12 is divisible by 4 (a perfect square), it can't be required divisor. 6 is not divisible by any perfect square. Input :97 Ou
12 min read
Smallest N digit number which is a perfect fourth power
Given an integer N, the task is to find the smallest N-digit number which is a perfect fourth power.Examples: Input: N = 2 Output: 16 Only valid numbers are 24 = 16 and 34 = 81 but 16 is the minimum.Input: N = 3 Output: 256 44 = 256 Approach: Find the starting and ending numbers for the 4th power, which are calculated as start = 10^((n-1)/4) and en
5 min read
Number of edges in a perfect binary tree with N levels
Given a positive integer N, the task is to find the count of edges of a perfect binary tree with N levels.Examples: Input: N = 2 Output: 2 1 / \ 2 3 Input: N = 3 Output: 6 1 / \ 2 3 / \ / \ 4 5 6 7 Approach: It can be observed that for the values of N = 1, 2, 3, ..., a series will be formed as 0, 2, 6, 14, 30, 62, ... whose Nth term is 2N - 2.Below
2 min read
Find all Factors of Large Perfect Square Natural Number in O(sqrt(sqrt(N))
Given a perfect square natural number N. The task is to find all the factors of N. Examples Input: N = 100 Output: 1 2 4 5 10 20 25 50 100 Input: N = 900 Output: 1 2 4 3 6 12 9 18 36 5 10 20 15 30 60 45 90 180 25 50 100 75 150 300 225 450 900 Approach: Find the square root of N in temp.Find all the prime factors of temp in O(sqrt(temp)) using the a
15+ min read
Number of times the largest Perfect Cube can be subtracted from N
Given a number N, at every step, subtract the largest perfect cube( ? N) from N. Repeat this step while N &gt; 0. The task is to count the number of steps that can be performed. Examples: Input: N = 100 Output: 4 First step, 100 - (4 * 4 * 4) = 100 - 64 = 36 Second step, 36 - (3 * 3 * 3) = 36 - 27 = 9 Third step, 9 - (2 * 2 * 2) = 9 - 8 = 1 Fourth
5 min read
Number of perfect cubes between two given numbers
Given two given numbers a and b where 1&lt;=a&lt;=b, find the number of perfect cubes between a and b (a and b inclusive).Examples: Input : a = 3, b = 16 Output : 1 The only perfect cube in given range is 8. Input : a = 7, b = 30 Output : 2 The two cubes in given range are 8, and 27 Method 1 : One naive approach is to check all the numbers between
6 min read
Least number to be added to or subtracted from N to make it a Perfect Square
Given a number N, find the minimum number that needs to be added to or subtracted from N, to make it a perfect square. If the number is to be added, print it with a + sign, else if the number is to be subtracted, print it with a - sign. Examples: Input: N = 14 Output: 2 Nearest perfect square before 14 = 9 Nearest perfect square after 14 = 16 There
5 min read
Check whether the number can be made perfect square after adding K
Given two numbers N and K, the task is to check whether the given number N can be made a perfect square after adding K to it.Examples: Input: N = 7, K = 2 Output: Yes Explanation: 7 + 2 = 9 which is a perfect square. Input: N = 5, K = 3 Output: No Explanation: 5 + 3 = 8 which is not a perfect square. Approach: The idea is to compute the value of N
4 min read
Check if number formed by joining two Numbers is Perfect Cube
Given two numbers a and b, the task is to check whether the concatenation of a and b is a perfect cube or not.Examples: Input: a = 6, b = 4 Output: Yes Concatenating 6 and 4 = 64. Since 64 (= 4 x 4 x 4) is a perfect cube, the output is Yes.Input: a = 100, b = 1 Output: No Concatenating 100 and 1 = 1001. Since 1001 is not a perfect cube, the output
5 min read
Smallest N digit number whose sum of square of digits is a Perfect Square
Given an integer N, find the smallest N digit number such that the sum of the square of digits (in decimal representation) of the number is also a perfect square. If no such number exists, print -1.Examples: Input : N = 2 Output : 34 Explanation: The smallest possible 2 digit number whose sum of square of digits is a perfect square is 34 because 32
15+ min read
Probability of getting a perfect square when a random number is chosen in a given range
Given two integers L and R that denote a range, the task is to find the probability of getting a perfect square number when a random number is chosen in the range L to R. Examples: Input: L = 6, R = 20 Output: 0.133333 Explanation: Perfect squares in range [6, 20] = {9, 16} =&gt; 2 perfect squares Total numbers in range [6, 20] = 15 Probability = 2
4 min read
Count the nodes in the given Tree whose weight is a Perfect Number
Given a tree, and the weights of all the nodes, the task is to count the number of nodes whose weight is a Perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors. Examples: Input: Output: 0 Explanation: There is no node with a weight that is a perfect number. Approach: In order to solve this problem,
8 min read
Length of largest subarray whose all elements are Perfect Number
Given an array arr[] of integer elements, the task is to find the length of the largest sub-array of arr[] such that all the elements of the sub-array are Perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors. Examples: Input: arr[] = {1, 7, 36, 4, 6, 28, 4} Output: 2 Explanation: Maximum length sub-
7 min read
Length of Longest Perfect number Subsequence in an Array
Given an array arr[] containing non-negative integers of length N, the task is to print the length of the longest subsequence of the Perfect number in the array. A number is a perfect number if it is equal to the sum of its proper divisors, that is, the sum of its positive divisors excluding the number itself. Examples: Input: arr[] = { 3, 6, 11, 2
7 min read
Array range queries to find the number of perfect square elements with updates
Given an array arr[] of N integers, the task is to perform the following two queries: query(start, end): Print the number of perfect square numbers in the sub-array from start to endupdate(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x Note: 0 based indexing is followed in the below example. Example: Input: arr =
15+ min read
Article Tags :
Practice Tags :