Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Monday, 25 December 2017

Java program to check if a number is perfect or not

What is a Perfect number :

A number whose sum of all divisors is equal to the number is called a perfect number . For example, the divisors of 6 is 1,2 and 3. The sum of these divisors is (1 + 2 + 3) = 6. So, it is a perfect number. But 5 or 7 is not.


Java program :


import java.util.Scanner;
public class Perfect
{
 public static void main(String[] args) throws Exception
 {
 Scanner sc = new  Scanner(System.in);
 int no; 
int sum = 0; 
print("Enter the number : "); 
no = sc.nextInt(); 
for (int i = 1; i <= no / 2; i++) 
if (no % i == 0) 
sum = sum + i;
 }
 } 
if (sum == no)
 { 
println(no + " is a Perfect number"); 
}
 else 
println(no + " is not a Perfect number"); 
}
}

No comments:

Post a Comment