Anonymous user
Weird numbers: Difference between revisions
→{{header|D}}
(→{{header|Mathematica}} / {{header|Wolfram Language}}: on second thought accumulating results in a list is better) |
|||
Line 772:
=={{header|D}}==
{{trans|Kotlin}} Adding efficient "cut" condition in semiperfect recursive algorithm
<lang d>import std.algorithm;
import std.array;
Line 798:
bool semiperfect(int n, int[] divs) {
// Comparing with (divs.sum < n) instead (divs.length==0) removes unnecessary
// recursive binary tree branches.
auto s = divs.sum;
if(s == n)
else if ( s<n )
return false;
else {
auto h = divs[0];
auto t = divs[1..$];
Line 805 ⟶ 813:
} else {
return n == h
// Supossin h is part of the sum
|| semiperfect(n - h, t)
// Supossin h is not part of the sum
|| semiperfect(n, t);
}
}
▲ return false;
}
|