Input two numbers and check if they form an amicable pair or not using a function in Java
Function - Question 7
In this question, we will see how to input two numbers and check if they form an amicable pair or not in Java programming using a function. To know more about function click on the function lesson.
Q7) Write a program in Java to input two numbers and check if they form an amicable pair or not using a function. The function should return 1 if the numbers form an amicable pair else return 0.
An amicable pair is such that, the sum of the factors excluding itself of first number is equal to the second number and sum of factors excluding itself of the second number is equal to the first number. Example, (220, 284) are amicable pair since sum of factors excluding itself of first number is 284 and sum of factors excluding itself of second number is 220:
220=1+2+4+5+10+11+20+22+44+55+110=284 284=1+2+4+71+142=220
Program
import java.util.Scanner;
public class Q7
{
public static int amicable(int a,int b)
{
int fs1=0; // factor sum of first number
int fs2=0; // factor sum of second number
int i;
for(i=1; i<a; i++)
{
if(a%i==0)
{
fs1=fs1+i;
}
}
for(i=1; i<b; i++)
{
if(b%i==0)
{
fs2=fs2+i;
}
}
if(fs1==b && fs2==a)
{
return 1;
}
return 0;
}
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 numbers");
a=sc.nextInt();
b=sc.nextInt();
if(amicable(a,b)==1)
{
System.out.print("Amicable Pair");
}
else
{
System.out.print("Not Amicable Pair");
}
}
}
Output
Enter 2 numbers 220 284 Amicable Pair