A perfect number in Java is a positive integer that is equal to the sum of its proper positive divisors excluding the number itself. For example, the divisors of 6 are 1, 2 and 3. The sum of the proper divisors of 6 is 1 + 2 + 3 = 6, which is a perfect number. The sum of the proper divisors of 28 is 1 + 2 + 4 + 7 + 14 = 28, which is also a perfect number.
Write a Java Program that will ask the user for a number and then check whether the number is a perfect number or not.
1. Take the number as input and store the number in a variable.
2. Loop through all the numbers from 1 to the number and check whether the number is a divisor of the number.
3. If the number is a divisor of the number, add it to the sum.
4. If the sum is equal to the number, print “The number is a perfect number”.
5. If the sum is not equal to the number, print “The number is not a perfect number”.
Here is the source code of the Java Program to Check if a given Number is Perfect Number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Perfect
{
public static void main(String[] args)
{
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number: ");
n = s.nextInt();
for(int i = 1; i < n; i++)
{
if(n % i == 0)
{
sum = sum + i;
}
}
if(sum == n)
{
System.out.println("Given number is a perfect number");
}
else
{
System.out.println("Given number is not a perfect number");
}
}
int divisor(int x)
{
return x;
}
}
1. Take the number as input and store the number in a variable n.
2. Loop through all the numbers from 1 to the number and check whether the number is a divisor of the number.
3. If the number is a divisor of the number, add it to the sum.
4. If a condition is true, print “The number is a perfect number,” otherwise print “The number is not a perfect number.”
Time Complexity: O(n)
The above program for checking whether a number is perfect or not has a time complexity of O(n), where n is the number given as input.
Space Complexity: O(1)
In this program we are not initializing any array or other data types that takes lot of storage. We are just initializing the variable. Therefore, our space complexity is constant, i.e. O(1).
Testcase 1: In this case, we enter the number “6” as input to determine whether it is a perfect number or not.
Enter the number: 6 Given number is a perfect number
Testcase 2: In this case, we enter the number “34” as input to determine whether it is a perfect number or not.
Enter the number: 34 Given number is not a perfect number
To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.
- Check Programming Books
- Practice Information Technology MCQs
- Apply for Java Internship
- Practice Programming MCQs
- Practice BCA MCQs