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 strict v5.20;
use experimental qw(signatures);
use warnings ;
 
use List::Util qw( sum ) ;
 
sub sum_3_5($limit) {
my $limit = shift ;
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}
 
printsay "The sum is " . ${\(sum_3_5( 1000 ) . " }!\n" ;</lang>
{{Out}}
<pre>The sum is 233168 !</pre>
 
{{Trans|Tcl}}
An alternative approach, using the analytical solution from the Tcl example.
<lang Perl>use feature 'say'v5.20;
use experimental qw(signatures);
sub tri
 
{
sub tri($n) {
my $n = shift;
return $n*($n+1) / 2;
}
 
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);
{
my $n = (shift) - 1;
(3 * tri( int($n/3) ) + 5 * tri( int($n/5) ) - 15 * tri( int($n/15) ) );
}
 
say sum( 1e3);
use bigint; # Machine precision was sufficient for the first calculation
say sum( 1e20);</lang>
{{Out}}
<pre>233168
1,479

edits