1,105,633 Community Members

Amicable numbers

Member Avatar
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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");
         }
}
Member Avatar
cms271828
Junior Poster
124 posts since Oct 2006
Reputation Points: 2 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

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");
    }
}
Member Avatar
cms271828
Junior Poster
124 posts since Oct 2006
Reputation Points: 2 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

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

You
Post:
Start New Discussion
View similar articles that have also been tagged: