Amicable chains题号：95 难度： 30 中英对照

The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.

Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair.

Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:

12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...)

Since this chain returns to its starting point, it is called an amicable chain.

Find the smallest member of the longest amicable chain with no element exceeding one million.

Code

public final class p95 {
private static final int LIMIT=(int)Math.pow(10, 6);
//private static final int LIMIT=16000;
public static void main(String[] args){
long start=System.nanoTime();
long result = run();
long end=System.nanoTime();
System.out.println(result);
System.out.println( (end-start)/1000000 + "ms" );
}
public static long run(){
int[] divisorSum = new int[LIMIT + 1];	//divisorSum[n]用来计算n的所有因子之和
for (int i = 1; i <= LIMIT; i++) {
for (int j = i * 2; j <= LIMIT; j += i)
divisorSum[j] += i;
}
int maxChainLen = 0;
long minChainElem = -1;
for (int i = 0; i <= LIMIT; i++) {
Set<Integer> visited = new HashSet<>();	//set中元素不可以重复
int cur=i;
for (int count = 1; ; count++) {
int next = divisorSum[cur];

if (next == i) {
if (count > maxChainLen) {
minChainElem = i;
maxChainLen = count;
}

break;
}
else if (next > LIMIT || visited.contains(next))
break;
else
cur = next;
}
}
return minChainElem;
}

}

14316
1318ms