Monday 3 December 2012

PROGRAM IN JAVA TO FIND PERFECT NUMBERS


import java.util.Scanner;

public class PerfectNumber {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        System.out.print("How many perfect numbers do you want to print = ");
        String str = sc.next();
        int limit = Integer.parseInt(str);
        int checkLimit = 1;
        
        for( int i = 2; i < Integer.MAX_VALUE; i++ )
        {
            boolean bool = perfectNumber(i);// passing value in function
            
            if(bool == true)
            {
                checkLimit++;
            }
            
            if(checkLimit > limit)
            {
                break;
            }
        }
    }
    
    public static boolean perfectNumber(int input){
        
        boolean bool= false;
        int size = 2000;
        int[] arr = new int[size];
        int counter = 0;
        int divisorSum = 1;
        
        for(int i = 2; i < input; i++)
        {
            if(input % i == 0)
            {
                arr[counter] = i;
                divisorSum += arr[counter];
                counter++;
            }
        }
        
        if(divisorSum == input)
        {
            System.out.print(input+" is a perfect number and divisors's sum = ");
            System.out.print("1");
            for(int i = 0; i < size; i++)
            {
                if( arr[i] == 0 )
                {
                    continue;
                }
                System.out.print("+"+arr[i]);
            }
            System.out.println("");
            bool = true;
        }
        return bool;
    }
}


  • The output of this progarm will be like shown in an image below.



1 comment:

  1. Casino-Casino.Com - Mapyro
    Casino-Casino.Com is a 30000 여주 출장안마 square 경산 출장샵 foot casino and hotel located in St. 거제 출장마사지 Louis, Missouri. 당진 출장마사지 Casino-Casino.Com features slot machines, table games, 이천 출장샵

    ReplyDelete