Amicable Pair || for loop || Java programs || Java


In this, we are going to write a simple program for finding an Amicable pair in Java.

Amicable numbers are two different numbers related in such a way that the sum of the proper divisors of each is equal to the other number.

The smallest pair of amicable numbers is (220, 284). They are amicable because the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.)


import java.util.*;

class Amicable 
{
    public static void main(String[] args) 
    {
        int a, b, sa = 0, sb = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter 2 integers:");
        a = sc.nextInt();
        b = sc.nextInt();
        for (int i = 1; i < a; i++) 
        {
            if (a % i == 0) 
            {
                sa += i;
            }
        }

        for (int i = 1; i < b; i++) 
        {
            if (b % i == 0) 
            {
                sb += i;
            }
        }

        if (sa == b && sb == a) 
        {
            System.out.println("It is an Amicable Pair");
        }

        else 
        {
            System.out.println("It is not an Amicable Pair");
        }

    }
}

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post