You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
In this core java programming tutorial we will Write a program to find out number is perfect or not in java.
Write a program to find number is perfect or not.
Q. What is perfect number?
A. Perfect number is a positive integer that is equal to the sum of its positive divisors excluding the number itself.
Example-
6= 1+2+3
28= 1+2+4+7+14
496= 1+2+4+8+16+31+62+124+248
Full Program/SourceCode / Example find out number is perfect or not in java >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class PerfectNumberExample {
public static void main(String a[]){
int n=28;
System.out.println(isPerfectNumber(n)==true ? n+" is perfect number." : n+" is not a perfect number.");
}
public static boolean isPerfectNumber(int n){
int sumOfDivisors = 1; //1 is divisor of all the numbers, so initially keep the sumOfDivisors=1 and start check divisors from 2.
for(int i=2;i<=n/2;i++)
if(n%i == 0)
sumOfDivisors += i;
if(sumOfDivisors == n)
return true;
else
return false;
}
}
/*OUTPUT
28 is perfect number.
*/
|
So, in this core java programming tutorial we wrote a program how to find out number is perfect or not in java.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
Related >>
>Pattern/Pyramid generating program in java
Labels:
Core Java
Level1 programs (beginners)