Sum multiples of 3 and 5: Difference between revisions
→{{header|Perl}}: Update to use v5.20 signatures and syntax; make the style consistent between the two solutions.
(→{{header|dc}}: Add implementation) |
(→{{header|Perl}}: Update to use v5.20 signatures and syntax; make the style consistent between the two solutions.) |
||
Line 2,959:
=={{header|Perl}}==
<lang Perl>#!/usr/bin/perl
use
use experimental qw(signatures);
use List::Util qw( sum ) ;
sub sum_3_5($limit) {
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}
{{Out}}
<pre>The sum is 233168
{{Trans|Tcl}}
An alternative approach, using the analytical solution from the Tcl example.
<lang Perl>use
use experimental qw(signatures);
sub tri▼
▲sub tri($n) {
}
sub sum_multiples($n, $limit) {
$n * tri( int( ($limit - 1) / $n ) )
}
sub sum($n) {
sum_multiples(3, $n) + sum_multiples(5, $n) - sum_multiples(15, $n);
}
say sum
use bigint; # Machine precision was sufficient for the first calculation
say sum
{{Out}}
<pre>233168
|