Once the task of finding sum of all divisors was taken care of, this problem held little challenge. I have mentioned how to compute the sum of all the divisors in an earlier post:
Take a number, find the sum of its divisors. If the sum is greater than the number itself, then find the sum of divisors of this sum. If the two sums are equal, then the two are amicable numbers.
Pair class:
package pba.common.tools;
/**
* A data object to manage pair of objects
*
* @author AnuvratSingh
* @param <A>
* @param <B>
*/
public class Pair<A, B> {
private A m_first;
private B m_second;
public Pair(A first, B second) {
m_first = first;
m_second = second;
}
public A getFirst() {
return m_first;
}
public B getSecond() {
return m_second;
}
@SuppressWarnings("unchecked")
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || o.getClass() != this.getClass())
return false;
Pair<Integer, Integer> test = (Pair<Integer, Integer>) o;
return this.getFirst() == test.getFirst() && this.getSecond() == test.getSecond();
}
}
Amicable Number class:
package pba.common.number;
import java.util.ArrayList;
import java.util.List;
import pba.common.tools.Pair;
public class AmicableNumber {
/**
* Does an exhaustive search for all the pairs of amicable numbers
*
* @param startIndex The first number from which the search commences
* @param endIndex The number up to which the search needs to be performed
* @return A list of all pairs of amicable numbers
*/
public static List<Pair<Integer, Integer>> getAmicableNumbers(int startIndex, int endIndex) {
List<Pair<Integer, Integer>> amicableNumbers = new ArrayList<Pair<Integer, Integer>>();
PrimeNumber p = new PrimeNumber(2 * endIndex);
for (int i = startIndex; i <= endIndex; i++) {
int sumOfFactors = p.getSumOfDivisors(i) - i;
if (sumOfFactors <= i)
continue;
if (p.getSumOfDivisors(sumOfFactors) - sumOfFactors == i)
amicableNumbers.add(new Pair<Integer, Integer>(i, sumOfFactors));
}
return amicableNumbers;
}
}
Popularity: 14% [?]
Related posts:
0 Responses to “Project Euler : Evaluate Sum Of All Amicable Pairs”