I hope some kindly monk or three can give me some guidance. I'm trying to decompose an arbitrary sum into a set of summands (or addends or terms, whatever you like to call them), such that there are always at least two summands in the set, and every summand is greater than or equal to 2.
Example; the sum 7 should be broken down into the sets (and only the sets) {5,2}, {4,3} and [3,2,2}. I don't need the permutations i.e. {2,2,3} or {2,3,2} since that would stiffle the speed of another calculation where if one works, all will work. And this needs to be very fast since in use it's going to have to handle sums of up to 10^6.
This is as far as I've gotten, but I just can't seem to get the looping to work quite right:
#!/usr/bin/perl -w # decompose sums to sets of summands use strict; use warnings; use vars qw($sum $size @temp @summands $prev $next); $sum = 10; $prev = 2; $next = $sum - $prev; while ($prev <= $next) { break(); } $size += scalar(@summands); for (my $i = 0 ; $i < $size ; $i++) { @temp = split(",",$summands[$i]); $sum = pop(@temp); $prev = 2; $next = $sum - $prev; while ($prev <= $next) { break(); } } for (@summands) { print "$_\n"; } sub break { push(@temp, $prev); push(@temp, $next); push(@summands, join(",",@temp)); @temp = (); $prev++; $next = $sum - $prev; }
In reply to Decomposing sum to unique sets of summands by blackmanao
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |