Program opened below. You can scroll through the algorithm, Java code and output.

Amicable Number

Download .java

Question

Accept two positive integers and determine whether they are amicable numbers.

Step 1: Start the program and accept two positive integers. Step 2: Define a method to calculate the sum of proper divisors of an integer. Step 3: Initialise the divisor sum to zero. Step 4: Test every integer from one up to half of the given number. Step 5: If the number is exactly divisible by the tested integer, add that divisor to the sum. Step 6: Return the sum of proper divisors. Step 7: Calculate the divisor sum for the first input number. Step 8: Calculate the divisor sum for the second input number. Step 9: Compare the first sum with the second number. Step 10: Compare the second sum with the first number. Step 11: If both comparisons are equal, report that the numbers are amicable. Step 12: Otherwise report that the numbers are not amicable, then stop.
Java
import java.util.*;
class AmicableNumbers
{
    static int divisorSum(int n)
    {
        int sum = 0;
        for (int i = 1; i <= n / 2; i++)
        {
            if (n % i == 0)
            {
                sum += i;
            }
        }
        return sum;
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter two positive integers: ");
        int a = sc.nextInt(), b = sc.nextInt();
        if (divisorSum(a) == b && divisorSum(b) == a)
        {
            System.out.println("Amicable numbers");
        }
        else
        {
            System.out.println("Not amicable numbers");
        }
    }
}
Input: Input: 220 284 Output: Amicable numbers
← Previous Program 49 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.