Tuesday, May 21, 2013

Program to check whether two numbers are Amicable Numbers

/**
 * class amicablenum checks whether a number is Amicable Number or not.
 * "Amicable numbers are a pair of numbers with the following property: the sum of all of the proper divisors of the first number (not including itself) 
 * exactly equals the second number while the sum of all of the proper divisors of the second number (not including itself) likewise equals the first number."
 * Ex: 220,284. proper divisors of 220:
 *1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110(sum=284)
 *proper divisors of 284:
 *1, 2, 4, 71, 142(sum=220)
 * @auther:Nitendra Kumar
 * @version: May 21/2013
 */
import java.util.Scanner;
public class amicablenum

 int checkamicable(int num1, int num2)
 {
     int sum1=0,sum2=0;
     System.out.println("Proper divisors of "+num1 +" are:");
     for(int i=1;i<=num1/2;i++)
     {
         if(num1%i==0)
         {
            System.out.print(" "+i);
            sum1+=i;
        }
    }

    System.out.println("\nProper divisors of "+num2 +" are:");
     for(int i=1;i<=num2/2;i++)
     {
         if(num2%i==0)
         {
            System.out.print(" "+i);
            sum2+=i;
        }
    }
    
    if(sum1==num2 && sum2==num1)
      return 1;
    else
      return 0;

}

 public static void main()
 {
     Scanner in=new Scanner(System.in);
     amicablenum ob=new amicablenum();
     int num1,num2;
     System.out.println("Enter 2 numbers to be checked for Amicable numbers");
     num1=in.nextInt();
     num2=in.nextInt();
     int flg=ob.checkamicable(num1,num2);
     if(flg==1)
        System.out.println("\nNumbers are Amicable numbers");
     else
        System.out.println("\nNumbers are not Amicable numbers");     
    }
}

Output:


Enter 2 numbers to be checked for Amicable numbers
220
284
Proper divisors of 220 are:
 1 2 4 5 10 11 20 22 44 55 110
Proper divisors of 284 are:
 1 2 4 71 142
Numbers are Amicable numbers



/*---------------Program developed by: Nitendra Kumar---------------*/
//For more details visit http://javawithnitendra.blogspot.in

1 comment:

Ur comments r most welcome...