Dremendo Tag Line

Input 2 integers and check amicable pair or not using while loop in Java

while Loop - Question 9

In this question, we will see how to input two integers and check if it forms an amicable pair or not in Java programming using while loop. To know more about while loop click on the while loop lesson.

Q9) Write a program in Java to input two integers and check if it forms an amicable pair or not using while loop.

An amicable pair is such that, the sum of the factors excluding itself of first number is equal to the second number and the sum of factors excluding itself of the second number is equal to the first number.

Example, (220, 284) is an amicable pair since, sum of factors excluding itself of: 220 = 1+2+4+5+10+11+20+22+44+55+110 = 284 and sum of factors excluding itself of: 284 = 1+2+4+71+142 = 220

Program

import java.util.Scanner;

public class Q9
{
    public static void main(String args[])
    {
        int i=1,n1,n2,sf1=0,sf2=0;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 numbers");
        n1=sc.nextInt();
        n2=sc.nextInt();

        while(i<n1)
        {
            if(n1%i==0)
            {
                sf1=sf1+i; 		// sum of factors of 1st number
            }
            i=i+1;
        }

        i=1;
        while(i<n2)
        {
            if(n2%i==0)
            {
                sf2=sf2+i; 		// sum of factors of 2nd number
            }
            i=i+1;
        }

        if(sf1==n2 && sf2==n1)
        {
            System.out.println("Amicable Pair");
        }
        else
        {
            System.out.println("Not Amicable Pair");
        }
    }
}

Output

Enter 2 numbers
220
284
Amicable Pair
video-poster