# Amicable numbers

eg. 14 and 15
Find all the factors of 14 and 15.
1,2,7,14 are factors of 14
1,3,5,15 are factors of 15
Sum all the factors of two numbers and
if sum of factors of two numbers taken are respectively equal they are Amicable numbers.

``````class Amicable
{
public static void main(String[] args)
{
int num1=Integer.parseInt(args[0]);
int num2=Integer.parseInt(args[1]);
int sum1=0,sum2=0;
for(int i=1;i<=num1;i++)
{
if(num1%i==0)
sum1+=i;
}
for(int i=1;i<=num2;i++)
{
if(num2%i==0)
sum2+=i;
}
if(sum1==sum2)
System.out.println(num1+" and "+num2+" are Amicable numbers");
else
System.out.println(num1+" and "+num2+" are not Amicable numbers");
}
}``````

Hi

But this looks totally wrong, consider 220 and 284

220: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110,[sum of 284]
284: 1, 2, 4, 71, 142 [sum of 220]

So the code should be..

``````class Amicable
{
public static void main(String[] args)
{
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum1 = 0;
int sum2 = 0;

for(int i=1;i<num1;i++)
{
if(num1%i == 0) sum1 += i;
}
for(int i=1;i<num2;i++)
{
if(num2%i == 0) sum2 += i;
}

if(sum1 == num2 && sum2 == num1)
System.out.println(num1+" and "+num2+" are Amicable numbers");
else
System.out.println(num1+" and "+num2+" are not Amicable numbers");
}
}``````

Actually I was wrong, the above first code would still work.
Sum of divisors of 220 exculuding 220 is 284, then add 220, you get 284+220
Similarly for 284, you get 220+284

But my code is slightly more efficient, and probably clearer so I would still use what I wrote

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.