How to check Perfect number in java

Checking perfect number 

 Steps to do this:-

1. take sum value one is for user input .take i and initialize this by i=1 and take sum and initialize it by sum=0.

2.Start while loop where(i<n) and check if(n%i==0) then do sum=sum+i and close the if block and write i++ for incrementing i's value inside while loop.

3.Then check if(sum==n) then print "this is a perfect number"

else

print "this is not a perfect number". 

4.save and run

The Source Code

import java.util.Scanner;
class perf
{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int i=1,n,sum=0;
        System.out.println("enter the number");
        n=s.nextInt();
        while(i<n)
        {
            if(n%i==0)
            {
                sum=sum+i;
            }
            i++;
        }
        if(sum==n)
        {
            System.out.println("this is a perfect number");
        }
        else
        {
            System.out.println("this not a perfect number");
        }
    }
}

OUTPUT

  WATCH MY VIDEO

 

Comments

Popular Posts