Weird numbers: Difference between revisions

(→‎{{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
{{trans|Kotlin}}
<lang d>import std.algorithm;
import std.array;
Line 798:
 
bool semiperfect(int n, int[] divs) {
if// This algorithm is O(2^N) for N == divs.length >when 0)number {is not semiperfect.
// Comparing with (divs.sum < n) instead (divs.length==0) removes unnecessary
// recursive binary tree branches.
auto s = divs.sum;
if(s == n)
return falsetrue;
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);
}
} else {
return false;
}
}
 
Anonymous user