tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Core > Special Numbers > Perfect Number

Perfect Number 

A perfect number is a number for which the sum of its divisors, except itself equals the number.

File Name  :  
com/bethecoder/tutorials/core/special_numbers/PerfectNumber.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.core.special_numbers;

import java.util.ArrayList;
import java.util.List;

/**
 * A perfect number equals the sum of its divisors, except itself
 
 @author Sudhakar KV.
 *
 */
public class PerfectNumber {

  /**
   @param args
   */
  public static void main(String[] args) {
    isPerfectNumber(4);
    isPerfectNumber(6);
    isPerfectNumber(24);
    isPerfectNumber(28);
    isPerfectNumber(496);
  }

  private static boolean isPerfectNumber(int number) {
    
    int sumOfDevisors = 0;
    List<Integer> devisors = new ArrayList<Integer>();
    for (int i = ; i <= number / ; i ++) {
      
      if (number % i == 0) {
        sumOfDevisors += i;
        devisors.add(i);
      }
    }
    
    boolean perfect = (sumOfDevisors == number);
    System.err.println(number + " is " 
        (perfect ? "a perfect number" "not a perfect number"
        " " + getSum(devisors, sumOfDevisors));
    return perfect;
  }
  
  private static String getSum(List<Integer> devisors, int sumOfDevisors) {
    
    StringBuilder sb = new StringBuilder("[ ");
    
    for (int i = ; i < devisors.size(); i ++) {
      
      if (i > 0) {
        sb.append(" + ");
      }
      
      sb.append(devisors.get(i));
    }
    
    sb.append(" = ").append(sumOfDevisors).append(" ]");
    return sb.toString();
  }
}
   

It gives the following output,
4 is not a perfect number [ 1 + 2 = 3 ]
6 is a perfect number [ 1 + 2 + 3 = 6 ]
24 is not a perfect number [ 1 + 2 + 3 + 4 + 6 + 8 + 12 = 36 ]
28 is a perfect number [ 1 + 2 + 4 + 7 + 14 = 28 ]
496 is a perfect number [ 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 = 496 ]



 
  


  
bl  br