How to calculate perfect number in java

    0
    46
    Spread the love
    • 2
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      2
      Shares

    How to calculate perfect number in java
    How to calculate perfect number in java

    What is a Perfect Number:

    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.

    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 HelloWorld{
    
         public static void main(String []args){
           new Abundant();
         }
    }
        class Abundant {
        public Abundant() {
            for (int i=1 ;i<=100;i++)
            {
            factorcal(i);
        }
        }
         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);
            }
         
         }
    }
    
     

    The output of the code:
    $javac HelloWorld.java
    $java -Xmx128M -Xms16M HelloWorld
    this is a perfect Number no6
    this is a perfect Number no28

    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 2
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      2
      Shares

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here