Go to Top

Thursday 8 December 2011

To check whether two numbers are amicable

Question 70 : Write a program in Java to check whether two numbers are amicable or not.

Amicable Number : If two numbers are such that the sum of the perfect divisors of one number is equal to the other number and the sum of the perfect divisors of  the other number is equal to the first number, then the numbers are called Amicable Numbers.

Example : 220 and 284.

Java Program :

class amicable
{
 static int a,b;
 static void input(int m,int n)
 {
     a=m;
     b=n;
     display();
    }
    static boolean check()
    {
        int s=0,i;
        for(i=1;i<a;i++)
        {
            if(a%i==0)
            {
                s=s+i;
            }
        }
        if(s==b)
        {
            s=0;
            for(i=1;i<b;i++)
            {
                if(b%i==0)
                {
                    s=s+i;
                }
            }
            if(s==a)
            return true;
            else
            return false;
        }
        return false;
    }
    static void display()
    {
        if(check())
        System.out.print("The numbers are amicable");
        else
        System.out.print("The numbers are not amicable");
}
}

33 comments:

  1. Thanks. really useful !!!

    ReplyDelete
  2. this is not totally correct, 6 and 6 are not amicable but your implementation doesnt satisfies this

    ReplyDelete
  3. 2 loops are not required. B thanks for this.

    ReplyDelete
  4. import java.util.Scanner;


    public class Amicable {
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in); //for accepting user input
    int num1=sc.nextInt();
    int num2=sc.nextInt();
    int a,b;
    a=d(num1);
    b=d(num2);
    if(a==num2 && b==num1)
    System.out.println("Amicable pair");
    else
    System.out.println("Not Amicable");

    }
    public static int d(int n){
    int i=1;
    int sum=0;
    while(i<=n/2){
    if(n%i==0)
    sum+=i;
    i++;
    }
    return sum;
    }
    }

    ReplyDelete
  5. Didn't understand its functioning!

    ReplyDelete
  6. try better not much correct

    ReplyDelete

ShareThis