Amicable Number in Java

Amicable numbers are two distinct natural numbers such that the sum of the proper divisors of each number is equal to the other number.

For example, the smallest pair of amicable numbers is 220 and 284.
The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110.
Their sum = 1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284.
The proper divisors of 284 are 1, 2, 4, 71, 142.
Their sum = 1 + 2 + 4 + 71 + 142 = 220.

Some more amicable number pairs are 1184 and 1210, 2620 and 2924, etc.

Write a Java program to input two integers and check whether they form amicable numbers or not.

import java.util.Scanner;
class Amicable{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("First number: ");
        int a = Math.abs(Integer.parseInt(in.nextLine()));
        System.out.print("Second number: ");
        int b = Math.abs(Integer.parseInt(in.nextLine()));
        if(a == b){
            System.out.println("They are NOT amicable numbers.");
            return;
        }
        if(sumOfProperFactors(a) == b && sumOfProperFactors(b) == a)
            System.out.println("They are amicable numbers!");
        else
            System.out.println("They are NOT amicable numbers.");
    }
    public static int sumOfProperFactors(int n){
        int sum = 0;
        for(int i = 1; i <= n / 2; i++){
            if(n % i == 0)
                sum += i;
        }
        return sum;
    }
}

2 thoughts on “Amicable Number in Java

Leave a Reply

Your email address will not be published. Required fields are marked *