In this tutorial you will learn about the Program to check Perfect Number In Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Perfect Numbers in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Perfect Number.
A number is called Perfect number if Sum of factors (not include the number itself) is equal to the number is called a perfect number.
For example:=>
Number = 6.
Divisors of 6 are 1, 2 and 3.
Sum = 1+2+3 = 6 = 6
⇒ So 6 is a perfect number.
Program to check Perfect Number in Java
In this program we would find given number is a Perfect number or not .first of we would take a value from user and find the Perfect number.let have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// Java program to check given number is perfect or not import java.util.Scanner; class Perfect_number { // declaring a function to find perfect number static boolean Perfect(int number) { if (number == 1) return false; int sum = 1; for (int i = 2; i < number; i++) { if (number % i == 0) { sum += i; } } // If sum of divisors is equal to then it is Perfect nuumber if (sum == number) return true; return false; } public static void main(String[] args) { // declaring variable and taking value form user.. int number; Scanner sc=new Scanner(System.in); System.out.print("Enter any number: "); number=sc.nextInt(); // check if the number is perfect or not. if (Perfect(number)) System.out.println(number+ " is a perfect number"); else System.out.println(number + " is not a perfect number"); } } |
Output
Perfect Number.
In the above program, we have first declared and initialized a set variables required in the program.
- number= it will hold entered number.
- sum= it will hold sum of factors.
After that we take a number from user and find given number is a Perfect number or not
after taking value from user check condition for number is perfect or not.
where we first check that number must be grater than one,after that we find the factor of a number and add them and check if sum of factor equals to number then it is a perfect number.
if not not a perfect number.