Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Check if a Given Integer is Positive or Negative
Next article icon

Java Program to Check if a Given Number is Perfect Number

Last Updated : 30 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

A number is said to be a perfect number if the sum of its proper divisors ( i.e. all positive divisors excluding the number itself )is equal to that number itself. Aliquot sum is the sum of divisors of a number, excluding the number itself. Hence, a number is a perfect number only if it is equal to its aliquot sum. All known perfect numbers are even. In this article, we will learn how to Check Perfect Numbers in Java.

Example 1:

n = 9
Proper Divisors of 9 are 1 and 3.
Sum = 1+3 = 4 ≠ 9
⇒ 9 is not a perfect number.

Example 2:

n = 6
Proper Divisors of 6 are 1, 2 and 3.
Sum = 1+2+3 = 6 = 6
⇒ 6 is a perfect number

So, we basically have to find the sum of the proper divisors of a number.

1. Using Loop to Check Perfect Number in Java

A Simple Solution is to go through every number from 1 to n-1 and check if it is a divisor and if it is, then add it in the sum variable and at the end check if the sum is equal to the number itself, then it is a perfect number otherwise not.

Below is the implementation of the above method:

Java
// Java program to check if a given // number is perfect or not  class GFG {      // Returns true if n is perfect     static boolean isPerfect(int n)     {         // 1 is not a perfect number         if (n == 1)             return false;          // sum will store the sum of proper divisors         // As 1 is a proper divisor for all numbers         // initialised sum with 1         int sum = 1;          // Looping through the numbers to check if they are         // divisors or not         for (int i = 2; i < n; i++) {              if (n % i == 0) {                 sum += i;             }         }          // If sum of divisors is equal to         // n, then n is a perfect number         if (sum == n)             return true;          return false;     }      // Driver program     public static void main(String[] args)     {         int n = 6;          // Call isPerfect function to         // check if the number is perfect or not.         if (isPerfect(n))             System.out.println(n + " is a perfect number");         else             System.out.println(                 n + " is not a perfect number");     } } 

Output
6 is a perfect number 

The complexity of the above method

  • Time Complexity: O(n)

2. Using Square root to Check Perfect Number in Java

An Efficient Solution is to go through numbers till the square root of n. 

If i is a divisor then n/i is also a divisor. 

Java
// Java program to check if a given // number is perfect or not  class GFG {      // Returns true if n is perfect     static boolean isPerfect(int n)     {         // 1 is not a perfect number         if (n == 1)             return false;          // sum will store the sum of proper divisors         // As 1 is a proper divisor for all numbers         // initialised sum with 1         int sum = 1;          // Looping through the numbers to check if they are         // divisors or not         for (int i = 2; i * i <= n; i++) {              if (n % i == 0) {                  // n is a perfect square                 // let's take 25                 // we need to add 5 only once                 // sum += i + n / i will add it twice                  if (i * i == n)                     sum += i;                 else                     sum += i + (n / i);             }         }          // If sum of divisors is equal to         // n, then n is a perfect number          if (sum == n)              return true;          return false;     }      // Driver program     public static void main(String[] args)     {         int n = 6;          // Call isPerfect function to         // check if the number is perfect or not.         if (isPerfect(n))              System.out.println(n + " is a perfect number");          else             System.out.println(                 n + " is not a perfect number");     } } 

Output
6 is a perfect number 

The complexity of the above method

Time Complexity: O(√n)

3. Recursive Approach to Check Perfect Number in Java

Below is the implement the above method:

Java
// Java Program to implement Perfect // Number using Recursion import java.util.*;  // Driver Class public class GFG {     static long sum = 0;      static long isPerfect(long num, int i)     {         // Base Condition         if (i <= num / 2) {             if (num % i == 0) {                 sum = sum + i;             }              // after each iteration, increments the value of             // variable i by 1             i++;              // recursive call             isPerfect(num, i);         }         // returns the sum of factors         return sum;     }      // main function     public static void main(String args[])     {         long number = 28, s;         int i = 1;          s = isPerfect(number, i);          // compares sum with the number         if (s == number)             // prints if the s and number are equal             System.out.println(number                                + " is a perfect number");         else             // prints if s and number are not equal             System.out.println(                 number + " is not a perfect number");     } } 

Output
28 is a perfect number 

The complexity of the above method

Time Complexity: O(n)


Next Article
Java Program to Check if a Given Integer is Positive or Negative

R

rathoreatul27
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Java Programs
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • Java Program to Check If a Number is Neon Number or Not
    A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range. Illustration: Case 1: Input : 9 Output : Given number 9 is Neon number Explanation : square of 9=9*9=81; sum of digit of square : 8+1=9(which
    4 min read
  • Java Program to Check if all digits of a number divide it
    Given a number n, find whether all digits of n divide it or not.Examples: Input : 128 Output : Yes 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130 Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128
    2 min read
  • Java Program to Check if a Given Integer is Positive or Negative
    Here, the task is to check whether the given integer number is positive or negative. Below are some basic properties of a number. If the Integer is greater than zero then it is a positive integer.If the number is less than zero then it is a negative integer.If the number is equal to zero then it is
    4 min read
  • Java Program to Check Whether Number is Divisible by 5
    Generic rules in mathematics to test divisibility by 5 in a number system is followed as numbers that end in 5 or 0 are divisible by 5. It doesn't matter how big the number is. Modulo operator will be used most frequently in programming when it comes down to divisibility. Knowledge of the range of n
    4 min read
  • Java Program to check Armstrong Number
    Given a number x. Write a Java Program to determine whether the given number is Armstrong's number or not. In this article, we will learn how to check Armstrong Numbers in Java. What is Armstrong's Number?In a mathematical number system, the Armstrong number is the number in any given number base, w
    4 min read
  • Java Program to Check if count of divisors is even or odd
    Given a number "n", find its total number of divisors is even or odd. Examples: Input: n = 10 Output: EvenInput: n = 100Output: OddInput: n = 125Output: EvenA naive approach would be to find all the divisors and then see if the total number of divisors is even or odd. The time complexity for such a
    4 min read
  • Check if a number is binary or not in Java
    Given a number N, the task is to check first whether the given number is binary or not and its value should be greater than 1. print true if N is the binary representation else print false. Examples: Input: N = 1010 Output: true Explanation: Given number is greater than 1 and none of its digits is g
    3 min read
  • Check if a number is Prime, Semi-Prime or Composite for very large numbers
    Given a very large number N (> 150), the task is to check whether this number is Prime, Semi-Prime or Composite.Example: Input: N = 90000000 Output: Not Prime Explanation: we have (N-1)%6 = 89999999%6 = 1 and (N+1)%6 = 90000001%6 = 5 Since n-1 and n+1 is not divisible by 6 Therefore N = 90000000
    8 min read
  • Perfect Number Program in Java Using While Loop
    The number which is equal to the sum of its divisors is called a perfect number. Read the entered long number, assigned to the long variable n. While loop iterates until the condition (i<=n/2) is false. If the remainder of n/i=0 then add i value to the sum and increase the i value. After all the
    2 min read
  • Prime Number Program in Java
    A prime number is a natural number greater than 1, divisible only by 1 and itself. Examples include 2, 3, 5, 7, and 11. These numbers have no other factors besides themselves and one. In this article, we will learn how to write a prime number program in Java when the input given is a Positive number
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences