Adsense 728 * 15

Search

Custom Search

Program to Check Perfect Number in Java

Write a java program to check whether a number is perfect or not. Take a input from user and print whether input number is perfect or not.

Program to check perfect number in C, C++

Program to print factors of a number in C, C++

Java Programs

Perfect Number Program in Java


package perfectnumber;

import java.util.*;

public class PerfectNumber {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

            int num, sum = 0;
            
            System.out.println("Enter a number to check whether it's perfect number 
                                or not");
            
            Scanner in = new Scanner(System.in);
            num = in.nextInt();
            
            /* If number is greater than zero */
            
            if (num > 0) {
            
                for (int i = 1; i < num; i++) {
            
                    /* sum of it's factors */
                    
                    if ( num % i == 0) {
                    
                        sum = sum + i;
                    
                    }
                }
    
                if ( sum == num) {
                
                    System.out.println(num + " is a perfect number ");
                
                } else {
                    
                    System.out.println (num + " is not a perfect number ");
                }
            
            }   else {
                
                System.out.println (" Please enter positive number ");
            }
    }
    
}




Output : 

Enter a number to check whether it's a perfect number or not  :    28

28 is a perfect number

No comments:

Post a Comment