Friday, 17 June 2016

Program to know whether a number is Perfect Number or not.

Explanation :
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
The first perfect number is 6, because 1, 2 and 3 are its proper positive divisors, and 1 + 2 + 3 = 6.

Code:

import java.util.Scanner;
public class PerfectNumber
{
    static void calc(int n)
    {
     int a=0;
      for(int i=1;i<=n/2;i++)
      {
        if(n%i == 0)
        {
           a=a+i;
        }
      }
      if(a == n) System.out.println(n+" is a perfect number");
      else System.out.println(n+" is not a perfect number");
    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a Number:");
        int n=sc.nextInt();
        calc(n);
        sc.close();
    }
}

No comments:

Post a Comment