-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path021.chpl
41 lines (33 loc) · 954 Bytes
/
021.chpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* Amicable numbers
*/
use MathFunctions;
config const maxNum = 10000,
printPairs = false;
proc main() {
var allSums: [{1..maxNum-1}] int,
sum: atomic int;
// Calculate all the sumDivisors first.
forall n in allSums.domain {
allSums[n] = sumDivisors(n);
}
// Iterate over all pairs where a < b. This ensures that duplicates are not
// added to sum. For example, without this, both 220,284 and 284,220 would be
// considered.
forall a in 1..maxNum-1 {
forall b in a+1..maxNum-1 {
if allSums[a] == b && allSums[b] == a {
sum.fetchAdd(a + b);
if printPairs {
writef("d(%n) = %n\nd(%n) = %n\n", a, b, b, a);
}
}
}
}
writeln(sum.read());
}
// Returns true if a and b are amicable numbers. If sumDivisors(a) == b,
// sumDivisors(b) == a, and a != b, then a and b are amicable.
proc amicable(a, b) {
return a != b && sumDivisors(a) == b && sumDivisors(b) == a;
}