Header Ads

How to calculate perfect number in java :: how I coded it



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 (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.

Read more here

Logic

The logic is pretty much same. 
The condition is to add up the factors and check if that is equal to the given number.
and change the last part of the code...


        if(pos==a)
        {
            System.out.println("this is  a perfect Number no"+a);
        }


So the final code will look like-

public class Abundant {
    public Abundant() {
        for (int i=1 ;i<=100;i++)
        {
        factorcal(i);
    }
    }
    public static void main (String[] args) {
       new Abundant();
       
    }
   
    public void factorcal(int a) {
        int pos=0;
        for (int i=1;i<a;i++) {
           
            if((i!=0) && (a%i)==0) {
                if(i>0)
                {
               pos=pos+i;
                }
               
            }
        }
       
         
        if(pos==a)
        {
            System.out.println("this is  a perfect Number no"+a);
        }
     
       
    }
}

Powered by Blogger.