We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,534 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Amicable numbers

0
By raj26061990 on Aug 16th, 2010 2:11 am

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");
    }
}
cms271828
Junior Poster
124 posts since Oct 2006
Reputation Points: 20
Solved Threads: 4
Skill Endorsements: 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

cms271828
Junior Poster
124 posts since Oct 2006
Reputation Points: 20
Solved Threads: 4
Skill Endorsements: 0

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0589 seconds using 2.68MB