Program to Check if Two Numbers are a Friendly Pair in Java

Friendly Pair

A friendly pair (also called an amicable pair) is a pair of numbers where the sum of their proper divisors divided by the number itself results in the same value for both numbers. For example, (220, 284) is a friendly pair.

We will explore a method to check if a given pair of numbers is a friendly pair using Java programming.

Method: Using a Function

We calculate the sum of proper divisors for both numbers and check if their ratios match.

import java.util.Scanner;

public class Main {
    public static int sumOfDivisors(int num) {
        int sum = 0;
        for (int i = 1; i <= num / 2; i++) {
            if (num % i == 0) {
                sum += i;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter two numbers: ");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();
        
        int sum1 = sumOfDivisors(num1);
        int sum2 = sumOfDivisors(num2);
        
        if ((double)sum1 / num1 == (double)sum2 / num2)
            System.out.println(num1 + " and " + num2 + " are a Friendly Pair");
        else
            System.out.println(num1 + " and " + num2 + " are not a Friendly Pair");
        
        scanner.close();
    }
}
            

Output:

Enter two numbers: 220 284
220 and 284 are a Friendly Pair
Easy aceess next quctions
Getting Started

Positive or Negative number: C C++ Java Python

Even or Odd number: C C++ Java Python

Sum of First N Natural numbers: C C++ Java Python

Sum of N natural numbers: C C++ Java Python

Sum of numbers in a given range: C C++ Java Python

Greatest of two numbers: C C++ Java Python

Greatest of the Three numbers: C C++ Java Python

Leap year or not: C C++ Java Python

Prime number: C C++ Java Python

Prime number within a given range: C C++ Java Python

Sum of digits of a number: C C++ Java Python

Reverse of a number: C C++ Java Python

Palindrome number: C C++ Java Python

Armstrong number: C C++ Java Python

Armstrong number in a given range: C C++ Java Python

Harshad number: C C++ Java Python

Abundant number: C C++ Java Python

Friendly pair: C C++ Java Python