Sum multiples of 3 and 5: Difference between revisions

Content added Content deleted
(→‎{{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: Line 2,959:
=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>#!/usr/bin/perl
<lang Perl>#!/usr/bin/perl
use strict ;
use v5.20;
use experimental qw(signatures);
use warnings ;

use List::Util qw( sum ) ;
use List::Util qw( sum ) ;


sub sum_3_5 {
sub sum_3_5($limit) {
my $limit = shift ;
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}
}


print "The sum is " . sum_3_5( 1000 ) . " !\n" ;</lang>
say "The sum is ${\(sum_3_5 1000)}!\n" ;</lang>
{{Out}}
{{Out}}
<pre>The sum is 233168 !</pre>
<pre>The sum is 233168!</pre>


{{Trans|Tcl}}
{{Trans|Tcl}}
An alternative approach, using the analytical solution from the Tcl example.
An alternative approach, using the analytical solution from the Tcl example.
<lang Perl>use feature 'say';
<lang Perl>use v5.20;
use experimental qw(signatures);
sub tri

{
sub tri($n) {
my $n = shift;
return $n*($n+1) / 2;
$n*($n+1) / 2;
}

sub sum_multiples($n, $limit) {
$n * tri( int( ($limit - 1) / $n ) )
}
}


sub sum
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);
say sum 1e3;
use bigint; # Machine precision was sufficient for the first calculation
use bigint; # Machine precision was sufficient for the first calculation
say sum(1e20);</lang>
say sum 1e20;</lang>
{{Out}}
{{Out}}
<pre>233168
<pre>233168