The Artima Developer Community
Sponsored Link

Java Answers Forum
Amicable Numbers program

4 replies on 1 page. Most recent reply: Apr 25, 2003 10:26 AM by Senthoorkumaran Punniamoorthy

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 4 replies on 1 page
Al

Posts: 2
Nickname: bobo
Registered: Apr, 2003

Amicable Numbers program Posted: Apr 25, 2003 3:11 AM
Reply to this message Reply
Advertisement
I need to crate a program that will examine the integers from 1 to 1000 and print out those integers whose sums,are the same and write the results to a file,
Any body have any ideas??


Adam Duffy

Posts: 168
Nickname: adamduffy
Registered: Feb, 2003

Re: Amicable Numbers program Posted: Apr 25, 2003 6:39 AM
Reply to this message Reply
For anyone that might want to try and solve this problem, see the following link for details on Amicable Numbers.

http://primes.utm.edu/glossary/page.php?sort=AmicableNumber

Adam

Adam Duffy

Posts: 168
Nickname: adamduffy
Registered: Feb, 2003

Re: Amicable Numbers program Posted: Apr 25, 2003 6:40 AM
Reply to this message Reply
A better link might be...

http://www.artima.com/legacy/answers/Feb2002/messages/15.html

Adam

Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: Amicable Numbers program Posted: Apr 25, 2003 10:25 AM
Reply to this message Reply
public class Amicable {
 
  public Amicable() {
  }
  int duplicates = 0;
 
  public int findAddFactors(int num)
  {
    int factorSum = 1;
    for (int i=2; i<=(num /2); i++)
    {
      if ((num%i)==0)
	factorSum+=i;
    }
    return factorSum;
  }
  public String areAmicable(int num)
  {
    if (num!=duplicates)
    {
      int pair1 = findAddFactors(num);
      int pair2 = findAddFactors(pair1);
      if ((num==pair2) && (pair1!=pair2))
      {
	duplicates = pair1;
	return "("+pair2+","+pair1+")";
      }
      else
	return null;
    }
    else
      return null;
  }
 
  public static void main(String args[])
  {
  Amicable test = new Amicable();
  for (int i=1; i<=1000;i++)
  {
    String res = test.areAmicable(i);
    if (res!=null)
      System.out.println(res);
  }
  }
}


writing to the file part you have to do it.

Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: Amicable Numbers program Posted: Apr 25, 2003 10:26 AM
Reply to this message Reply
if anyone has any suggections on how to improve the code I have posted above plase go ahead...

Senthoor

Flat View: This topic has 4 replies on 1 page
Topic: Hell Mr  dhrubo Previous Topic   Next Topic Topic: java Lexical Scanners

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use