Hi, I see you've attempted to generalize the problem by passing the moduli along as arguments. However, this complicates the matters considerably. Numbers multiple of some value form a set; all possible intersections of those form a powerset. E.g. for (3, 5, 7) you have the 305071, 305170, ..., 315171 subsets to consider.

Here's my attempt at a generic version. I'm not quite sure if it's sound in principle. (Now where are the resident mathematicians?)

#! /usr/bin/perl -wl use feature qw( signatures ); no warnings qw( experimental::signatures ); use List::Util qw( sum0 product reduce any ); sub gcd($a, $b) { !$b ? $a : gcd($b, $a % $b) } sub lcm { reduce { $a * $b / gcd($a, $b) } @_ } sub fk1($max, @A) { sum0 grep { my $x = $_; any {$x % $_ == 0} @A } 1 .. $max } sub fk2($max, @A) { sum0 map { (parity($_) || -1) * sum_every_nth($max, lcm_select($_, @A)) } 1 .. (1<<@A)-1 } sub sum_every_nth($max, $n) { int($max/$n) * int($max/$n + 1) / 2 * $n } sub lcm_select($sel, @A) { lcm @A[grep {$sel>>$_ & 1} 0..$#A] } sub parity { unpack "%1b*", pack "J", shift } my @A = (3, 5, 74017, 74027, 74047, 74077); print join ' ', 0+$_, fk1($_, @A), fk2($_, @A) while <>;
Again, the naive version and a smarter one. Subseries are summed with alternating signs according to cardinality: that way each number is tallied exactly once in the end.

Where the guarantee is given that moduli are mutually prime, one can use product() instead of lcm(). Then, if the limit $max is much greater than lcm(@A), one may reduce it first: e.g. with lcm(3, 5) you have a wheel15 going on. Etc. Talk about trivial exercises...


In reply to Re^2: Elegantly map fizz to buzz by oiskuu
in thread Elegantly map fizz to buzz by oiskuu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.