Sunday, July 16, 2017

Write a java program that accepts a number from the user and tells whether it is a perfect number or not.

/**
 * Created by Jo on 7/10/2017.
 * For more exercises and lessons, visit http://shegertech.blogspot.com/
 * Chapter 5, Exercise 1
 */

import java.util.Scanner;

public class Q1Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num1 = 0, sum=0;
        System.out.print("Enter the number : ");
        num1 = in.nextInt();

        for (int i=1; i<num1;i++){
            if (num1%i==0){
                sum+=i;
            }
        }
        if(sum==num1){
            System.out.println(num1+" is a perfect number");
        }
        else {
            System.out.println(num1+ " is not a perfect number");
        }
    }
}

Share: