Sum multiples of 3 and 5: Difference between revisions

(114 intermediate revisions by 47 users not shown)
Line 6:
Show output for ''n'' = 1000.
 
This is is the same as [https://projecteuler.net/problem=1 Project Euler problem 1].
 
'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F sum35(limit)
V sum = 0
L(i) 1 .< limit
I i % 3 == 0 | i % 5 == 0
sum += i
R sum
 
print(sum35(1000))</syntaxhighlight>
 
{{out}}
<pre>
233168
</pre>
 
=={{header|8th}}==
Implements both the naive method and inclusion/exclusion.
<syntaxhighlight lang="8th">
needs combinators/bi
 
: mul3or5? ( 3 mod 0 = ) ( 5 mod 0 = ) bi or ;
 
"The sum of the multiples of 3 or 5 below 1000 is " .
0 ( mul3or5? if I n:+ then ) 1 999 loop . cr
 
with: n
 
: >triangular SED: n -- n
dup 1+ * 2 / ;
: sumdiv SED: n n -- n
dup >r /mod nip >triangular r> * ;
: sumdiv_3,5 SED: n -- n
( swap sumdiv ) curry [3, 5, 15] swap a:map a:open neg + + ;
 
;with
 
"For 10^20 - 1, the sum is " . 10 20 ^ 1- sumdiv_3,5 . cr
bye
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 below 1000 is 233168
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668
</pre>
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Sum multiples of 3 and 5
SUM35 CSECT
USING SUM35,R13 base register
Line 56 ⟶ 103:
PG DC CL80'123456789012 : 1234567890123456'
YREGS
END SUM35</langsyntaxhighlight>
{{out}}
<pre>
Line 66 ⟶ 113:
1000000 : 233333166668
10000000 : 23333331666668
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
PROC Main()
REAL sum,r
INT i
 
Put(125) PutE() ;clear the screen
IntToReal(0,sum)
FOR i=0 TO 999
DO
IF i MOD 3=0 OR i MOD 5=0 THEN
IntToReal(i,r)
RealAdd(sum,r,sum)
FI
OD
 
PrintRE(sum)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_multiples_of_3_and_5.png Screenshot from Atari 8-bit computer]
<pre>
233168
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO;
 
procedure Sum_Multiples is
 
type Natural is range 0 .. 2**63 - 1;
 
function Sum_3_5 (Limit : in Natural) return Natural is
Sum : Natural := 0;
begin
for N in 1 .. Limit - 1 loop
if N mod 3 = 0 or else N mod 5 = 0 then
Sum := Sum + N;
end if;
end loop;
return Sum;
end Sum_3_5;
 
begin
Ada.Text_IO.Put_Line ("n=1000: " & Sum_3_5 (1000)'Image);
Ada.Text_IO.Put_Line ("n=5e9 : " & Sum_3_5 (5e9)'Image);
end Sum_Multiples;</syntaxhighlight>
{{out}}
<pre>n=1000: 233168
n=5e9 : 5833333329166666668</pre>
 
===Extra Credit===
Requires upcoming Ada 202x with big integer package.
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Numerics.Big_Numbers.Big_Integers;
 
procedure Sum_Multiples_Big is
use Ada.Numerics.Big_Numbers.Big_Integers;
use Ada.Text_IO;
 
type Natural is new Big_Natural;
 
function Sum_Mults (First, Last : Natural) return Natural is
High : constant Natural := Last - Last mod First;
Sum : constant Natural := (High / First) * (First + High) / 2;
begin
return Sum;
end Sum_Mults;
 
function Sum_35 (Limit : in Natural) return Natural is
Last : constant Natural := Limit - 1;
Mult_3 : constant Natural := Sum_Mults (3, Last);
Mult_5 : constant Natural := Sum_Mults (5, Last);
Mult_15 : constant Natural := Sum_Mults (15, Last);
begin
return Mult_3 + Mult_5 - Mult_15;
end Sum_35;
 
begin
Put_Line (" n : Sum_35 (n)");
Put_Line ("-----------------------------------------------------------------");
for E in 0 .. 30 loop
declare
N : constant Natural := 10**E;
begin
Put (To_String (N, Width => 32));
Put (" : ");
Put (Sum_35 (N)'Image);
New_Line;
end;
end loop;
end Sum_Multiples_Big;</syntaxhighlight>
{{out}}
<pre> n : Sum_35 (n)
-----------------------------------------------------------------
1 : 0
10 : 23
100 : 2318
1000 : 233168
10000 : 23331668
100000 : 2333316668
1000000 : 233333166668
10000000 : 23333331666668
100000000 : 2333333316666668
1000000000 : 233333333166666668
10000000000 : 23333333331666666668
100000000000 : 2333333333316666666668
1000000000000 : 233333333333166666666668
10000000000000 : 23333333333331666666666668
100000000000000 : 2333333333333316666666666668
1000000000000000 : 233333333333333166666666666668
10000000000000000 : 23333333333333331666666666666668
100000000000000000 : 2333333333333333316666666666666668
1000000000000000000 : 233333333333333333166666666666666668
10000000000000000000 : 23333333333333333331666666666666666668
100000000000000000000 : 2333333333333333333316666666666666666668
1000000000000000000000 : 233333333333333333333166666666666666666668
10000000000000000000000 : 23333333333333333333331666666666666666666668
100000000000000000000000 : 2333333333333333333333316666666666666666666668
1000000000000000000000000 : 233333333333333333333333166666666666666666666668
10000000000000000000000000 : 23333333333333333333333331666666666666666666666668
100000000000000000000000000 : 2333333333333333333333333316666666666666666666666668
1000000000000000000000000000 : 233333333333333333333333333166666666666666666666666668
10000000000000000000000000000 : 23333333333333333333333333331666666666666666666666666668
100000000000000000000000000000 : 2333333333333333333333333333316666666666666666666666666668
1000000000000000000000000000000 : 233333333333333333333333333333166666666666666666666666666668</pre>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="ALGOL">
begin
 
comment - return n mod m;
integer procedure mod(n,m);
value n, m; integer n, m;
begin
mod := n - m * entier(n / m);
end;
 
integer i, limit;
real sum;
 
limit := 1000;
sum := 0;
for i := 1 step 1 until (limit - 1) do
if mod(i, 3) = 0 or mod(i, 5) = 0 then
sum := sum + i;
outreal(1,sum);
 
end
</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
 
Line 71 ⟶ 275:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT to handle large numbers.
<langsyntaxhighlight lang="algol68"># returns the sum of the multiples of 3 and 5 below n #
PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT:
BEGIN
Line 96 ⟶ 300:
, newline
)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 103 ⟶ 307:
</pre>
 
== {{header|APL}} ==
=== Dyalog APL ===
<lang apl>⎕IO←0
<syntaxhighlight lang="apl">
{+/((0=3|a)∨0=5|a)/a←⍳⍵} 1000</lang>[http://ngn.github.io/apl/web/index.html#code=%7B+/%28%280%3D3%7Ca%29%u22280%3D5%7Ca%29/a%u2190%u2373%u2375%7D%201000,run=1 run]
Sum ← +/∘⍸1<15∨⍳
</syntaxhighlight>
{{out}}
<pre> Sum 999
233168</pre>
 
=== ngn/APL ===
<syntaxhighlight lang="apl">⎕IO←0
{+/((0=3|a)∨0=5|a)/a←⍳⍵} 1000</syntaxhighlight>[http://ngn.github.io/apl/web/index.html#code=%7B+/%28%280%3D3%7Ca%29%u22280%3D5%7Ca%29/a%u2190%u2373%u2375%7D%201000,run=1 run]
{{out}}
<pre>233168</pre>
 
== {{header|AppleScript}} ==
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- SUM MULTIPLES OF 3 AND 5 --------------------------------- SUM MULTIPLES OF 3 AND 5 -----------------
 
-- sum35 :: Int -> Int
-- sums of all multiples of 3 or 5 below or equal to N
on sum35(n)
-- for N = 10 to N = 10E8 (limit of AS integers)
tell sumMults(n)
|λ|(3) + |λ|(5) - |λ|(15)
end tell
end sum35
 
-- sum35Result :: String -> Int -> Int -> String
script sum35Result
-- sum35 :: Int -> Int
on sum35(n)
sumMults(n, 3) + sumMults(n, 5) - sumMults(n, 15)
end sum35
-- Area under straight line between first multiple and last:
-- sumMults :: Int -> Int -> Int
on sumMults(n, f)
set n1 to (n - 1) div f
f * n1 * (n1 + 1) div 2
end sumMults
on |λ|(a, x, i)
a & "10<sup>" & i & "</sup> -> " & ¬
sum35(10 ^ x) & "<br>"
end |λ|
end script
 
 
-- sumMults :: Int -> Int -> Int
-- TEST ----------------------------------------------------------------------
on sumMults(n)
-- Area under straight line
-- between first multiple and last.
script
on |λ|(m)
set n1 to (n - 1) div m
m * n1 * (n1 + 1) div 2
end |λ|
end script
end sumMults
 
 
--------------------------- TEST ---------------------------
on run
-- sum35Result :: String -> Int -> Int -> String
script sum35Result
-- sums of all multiples of 3 or 5 below or equal to N
-- for N = 10 to N = 10E8 (limit of AS integers)
on |λ|(a, x, i)
a & "10<sup>" & i & "</sup> -> " & ¬
sum35(10 ^ x) & "<br>"
end |λ|
end script
foldl(sum35Result, "", enumFromTo(1, 8))
end run
 
 
-- GENERIC FUNCTIONS ------------------------------------ GENERIC FUNCTIONS ---------------------
 
-- enumFromTo :: Int -> Int -> [Int]
Line 186 ⟶ 401:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
10<sup>1</sup> -> 23<br>10<sup>2</sup> -> 2318<br>10<sup>3</sup> -> 233168<br>10<sup>4</sup> -> 23331668<br>10<sup>5</sup> -> 2.333316668E+9<br>10<sup>6</sup> -> 2.33333166668E+11<br>10<sup>7</sup> -> 2.333333166667E+13<br>10<sup>8</sup> -> 2.333333316667E+15<br>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">sumMul35: function [n][
sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]
 
print sumMul35 1000</syntaxhighlight>
 
{{out}}
 
<pre>233168</pre>
 
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">n := 1000
 
msgbox % "Sum is " . Sum3_5(n) . " for n = " . n
Line 226 ⟶ 453:
}
return sum
}</langsyntaxhighlight>
'''Output:''' <pre>Sum is 233168 for n = 1000
Sum is 233168 for n = 1000</pre>
Line 232 ⟶ 459:
=={{header|AWK}}==
Save this into file "sum_multiples_of3and5.awk"
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
{
n = $1-1;
Line 240 ⟶ 467:
m = int(n/d);
return (d*m*(m+1)/2);
}</langsyntaxhighlight>
 
{{Out}}
Line 254 ⟶ 481:
2333333333333333333316666666666666666668</pre>
 
== {{header|BASIC}} ==
{{works with|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">Declare function mulsum35(n as integer) as integer
Function mulsum35(n as integer) as integer
Dim s as integer
Line 268 ⟶ 495:
Print mulsum35(1000)
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 10 INPUT N
20 LET SUM = 0
30 FOR I = 3 TO N - 1
40 IF I / 3 = INT (I / 3) OR I / 5 = INT (I / 5) THEN SUM = SUM + I
50 NEXT I
60 PRINT SUM</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">function multSum35(n)
if n = 0 then return 0
suma = 0
for i = 1 to n
if (i mod 3 = 0) or (i mod 5 = 0) then suma += i
next i
return suma
end function
 
print multSum35(999)
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 cls
20 print multsum35(1000)
30 end
40 function multsum35(n)
50 suma = 0
60 for i = 1 to n-1
70 if (i mod 3 = 0) or (i mod 5 = 0) then suma = suma+i
80 next i
90 multsum35 = suma
100 end function</syntaxhighlight>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; multSum35(999)
End
 
Function multSum35(n As Integer) As Integer
 
If n = 0 Then Return 0
Dim suma As Integer = 0
For i As Integer = 1 To n
If (i Mod 3 = 0) Or (i Mod 5 = 0) Then suma += i
Next
Return suma
 
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|MSX BASIC|any}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 CLS : REM 10 HOME for Applesoft BASIC
20 LET N = 1000
30 GOSUB 60
40 PRINT S
50 END
60 REM multsum35
70 LET S = 0
80 FOR I = 1 TO N-1
90 IF I/3 = INT(I/3) OR I/5 = INT(I/5) THEN LET S = S+I : REM for Applesoft BASIC & Quite BASIC
90 IF (I MOD 3 = 0) OR (I MOD 5 = 0) THEN LET S = S+I : REM for MSX Basic & Chipmunk Basic
100 NEXT I
110 RETURN</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 INPUT N
20 LET S = 0
30 FOR I = 3 TO N - 1
40 IF I / 3 = INT (I / 3) THEN 70
50 IF I / 5 = INT (I / 5) THEN 70
60 GOTO 80
70 LET S = S + I
80 NEXT I
90 PRINT S
100 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
See [[#GW-BASIC|GW-BASIC]].
 
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">FUNCTION multSum35 (n)
IF n = 0 THEN multSum35 = 0
suma = 0
FOR i = 1 TO n
IF (i MOD 3 = 0) OR (i MOD 5 = 0) THEN suma = suma + i
NEXT i
multSum35 = suma
END FUNCTION
 
PRINT multSum35(999)</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION multSum35(n)
IF n = 0 THEN LET multSum35 = 0
LET suma = 0
FOR i = 1 TO n
IF MOD(i, 3) = 0 OR MOD(i, 5) = 0 THEN LET suma = suma + i
NEXT i
LET multSum35 = suma
END FUNCTION
 
PRINT multSum35(999)
END</syntaxhighlight>
 
==={{header|Quite BASIC}}===
See [[#GW-BASIC|GW-BASIC]].
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub multSum35(n)
if n = 0 then return 0 : fi
suma = 0
for i = 1 to n
if mod(i, 3) = 0 or mod(i, 5) = 0 then suma = suma + i : fi
next i
return suma
end sub
 
print multSum35(999)
end</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PRINT MULTSUM35(1000)
110 DEF MULTSUM35(N)
120 LET S=0
Line 280 ⟶ 636:
150 NEXT
160 LET MULTSUM35=S
170 END DEF</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 286 ⟶ 642:
 
The ZX81 doesn't offer enough numeric precision to try for the extra credit. This program is pretty unsophisticated; the only optimization is that we skip testing whether <math>i</math> is divisible by 5 if we already know it's divisible by 3. (ZX81 BASIC doesn't do this automatically: both sides of an <code>OR</code> are evaluated, even if we don't need the second one.) Even so, with <math>n</math> = 1000 the performance is pretty acceptable.
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 FAST
30 LET SUM=0
Line 295 ⟶ 651:
80 NEXT I
90 SLOW
100 PRINT SUM</langsyntaxhighlight>
{{in}}
<pre>1000</pre>
Line 303 ⟶ 659:
=={{header|bc}}==
{{trans|Groovy}}
<langsyntaxhighlight lang="bc">define t(n, f) {
auto m
 
Line 315 ⟶ 671:
 
s(1000)
s(10 ^ 20)</langsyntaxhighlight>
{{Out}}
<pre>233168
2333333333333333333316666666666666666668</pre>
 
== {{header|BefungeBCPL}} ==
There is both the naive method and the fast inclusion/exclusion method demonstrated. The code is limited to values that don't overflow a 64 bit integer.
<syntaxhighlight lang="bcpl">
GET "libhdr"
 
LET sumdiv(n, d) = VALOF {
LET m = n/d
RESULTIS m*(m + 1)/2 * d
}
 
LET sum3or5(n) = sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)
 
LET start() = VALOF {
LET sum = 0
LET n = 1
 
FOR k = 1 TO 999 DO
IF k MOD 3 = 0 | k MOD 5 = 0 THEN sum +:= k
writef("The sum of the multiples of 3 and 5 < 1000 is %d *n", sum)
 
writef("Next, the awesome power of inclusion/exclusion...*n");
FOR i = 1 TO 10 {
writef("%11d %d *n", n, sum3or5(n - 1))
n *:= 10
}
 
RESULTIS 0
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 and 5 < 1000 is 233168
Next, the awesome power of inclusion/exclusion...
1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668
</pre>
 
=={{header|Befunge}}==
Slow (iterative) version:
<langsyntaxhighlight Befungelang="befunge">&1-:!#v_:3%#v_ >:>#
>+\:v >:5%#v_^
@.$_^#! < > ^</langsyntaxhighlight>
{{Out}}
<pre>233168</pre>
Fast (analytic) version:
<langsyntaxhighlight Befungelang="befunge">&1-::3/:1+*3*2/\5/:1+*5*2/+\96+/:1+*96+*2/-.@</langsyntaxhighlight>
{{Out}}
<pre>233168</pre>
 
=={{header|BQN}}==
A naive solution:
<syntaxhighlight lang="bqn">Sum ← +´·(0=3⊸|⌊5⊸|)⊸/↕</syntaxhighlight>
 
A much faster solution:
<syntaxhighlight lang="bqn">Sum ← {
m ← (0=3⊸|⌊5⊸|)↕15 ⋄ h‿l ← 15(⌊∘÷˜∾|)𝕩
(+´l↑m×15(×+↕∘⊣)h) + (15×(+´m)×2÷˜h×h-1) + h×+´m×↕15
}</syntaxhighlight>
 
{{out}}
 
<pre>
Sum 1000
233168
</pre>
 
([https://mlochbaum.github.io/BQN/try.html#code=U3VtIOKGkCB7CiAgbSDihpAgKDA9M+KKuHzijIo14oq4fCnihpUxNSDii4QgaOKAv2wg4oaQIDE1KOKMiuKImMO3y5ziiL58KfCdlakKICAoK8K0bOKGkW3DlzE1KMOXK+KGleKImOKKoyloKSArICgxNcOXKCvCtG0pw5cyw7fLnGjDl2gtMSkgKyBow5crwrRtw5fihpUxNQp9CgpTdW0gMTAwMAo= online REPL])
 
=={{header|C}}==
===Simple version===
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 357 ⟶ 777:
printf("%lld\n", sum35(limit));
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>$ ./a.out
Line 366 ⟶ 786:
===Fast version with arbitrary precision===
{{libheader|GMP}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <gmp.h>
 
Line 418 ⟶ 838:
mpz_clear(limit);
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>$ ./a.out
Line 428 ⟶ 848:
The following C# 5 / .Net 4 code is an <i>efficient solution</i> in that it does not iterate through the numbers 1 ... n - 1 in order to calculate the answer. On the other hand, the System.Numerics.BigInteger class (.Net 4 and upwards) is not itself efficient because calculations take place in software instead of hardware. Consequently, it may be <i>faster</i> to conduct the calculation for smaller values with native ("primitive") types using a 'brute force' iteration approach.
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 469 ⟶ 889:
}
}
</syntaxhighlight>
</lang>
{{out}}
The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168
Line 484 ⟶ 904:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
 
Line 527 ⟶ 947:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Sum is 233168 for n = 1000
Sum is 233168 for n = 1000
</pre>
 
===Fast version with arbitrary precision===
{{libheader|Boost}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
 
template <typename T> T sum_multiples(T n, T m) {
n -= T(1);
n -= n % m;
return (n / m) * (m + n) / T(2);
}
 
template <typename T> T sum35(T n) {
return sum_multiples(n, T(3)) + sum_multiples(n, T(5)) -
sum_multiples(n, T(15));
}
 
int main() {
using big_int = boost::multiprecision::cpp_int;
 
std::cout << sum35(1000) << '\n';
std::cout << sum35(big_int("100000000000000000000")) << '\n';
}</syntaxhighlight>
 
{{out}}
<pre>
233168
2333333333333333333316666666666666666668
</pre>
 
=={{header|Clojure}}==
Quick, concise way:
<langsyntaxhighlight lang="clojure">(defn sum-mults [n & mults]
(let [pred (apply some-fn
(map #(fn [x] (zero? (mod x %))) mults))]
(->> (range n) (filter pred) (reduce +))))
 
(println (sum-mults 1000 3 5))</langsyntaxhighlight>
 
Transducers approach:
<syntaxhighlight lang="clojure">(defn sum-mults [n & mults]
(transduce (filter (fn [x] (some (fn [mult] (zero? (mod x mult))) mults)))
+ (range n)))
 
(println (sum-mults 1000 3 5))</syntaxhighlight>
 
Or optimized (translated from Groovy):
<langsyntaxhighlight lang="clojure">(defn sum-mul [n f]
(let [n1 (/' (inc' n) f)]
(*' f n1 (inc' n1) 1/2)))
 
(def sum-35 #(-> % (sum-mul 3) (+ (sum-mul % 5)) (- (sum-mul % 15))))
(println (sum-35 1000000000))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 551 ⟶ 1,010:
Using OpenCOBOL.
 
<langsyntaxhighlight lang="cobol">
Identification division.
Program-id. three-five-sum.
Line 575 ⟶ 1,034:
or function mod(ws-the-number, 5) = zero
then add ws-the-number to ws-the-sum.
</syntaxhighlight>
</lang>
 
Output:
Line 583 ⟶ 1,042:
 
Using triangular numbers:
<langsyntaxhighlight lang="cobol">
Identification division.
Program-id. three-five-sum-fast.
Line 631 ⟶ 1,090:
Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2.
goback.
</syntaxhighlight>
</lang>
 
Output:
Line 641 ⟶ 1,100:
A brute-method using only comparisons and adds. Compiles and runs as is in GnuCOBOL 2.0 and Micro Focus Visual COBOL 2.3. Takes about 7.3 seconds to calculate 1,000,000,000 iterations (AMD A6 quadcore 64bit)
 
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. SUM35.
Line 682 ⟶ 1,141:
EXIT.
END PROGRAM SUM35.
</syntaxhighlight>
</lang>
Output
<pre>+00233333333166666668</pre>
Line 688 ⟶ 1,147:
=={{header|Common Lisp}}==
Slow, naive version:
<langsyntaxhighlight lang="lisp">(defun sum-3-5-slow (limit)
(loop for x below limit
when (or (zerop (rem x 3)) (zerop (rem x 5)))
sum x))</langsyntaxhighlight>
 
Fast version (adapted translation of [[#Tcl|Tcl]]):
<langsyntaxhighlight lang="lisp">(defun sum-3-5-fast (limit)
(flet ((triangular (n) (truncate (* n (1+ n)) 2)))
(let ((n (1- limit))) ; Sum multiples *below* the limit
(- (+ (* 3 (triangular (truncate n 3)))
(* 5 (triangular (truncate n 5))))
(* 15 (triangular (truncate n 15)))))))</langsyntaxhighlight>
 
{{Out}}
Line 707 ⟶ 1,166:
> (sum-3-5-fast 1000000000000000000000)
233333333333333333333166666666666666666668</pre>
 
 
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Sum3_5;
IMPORT StdLog, Strings, Args;
Line 739 ⟶ 1,196:
 
END Sum3_5.
</syntaxhighlight>
</lang>
Execute: ^Q Sum3_5.Compute 1000 ~ <br/>
Output:
Line 745 ⟶ 1,202:
Sum: 233168
</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
# sum multiples up to given input
interface SumMulTo(mul: uint32, to: uint32): (rslt: uint32);
 
# naive implementation
sub naiveSumMulTo implements SumMulTo is
rslt := 0;
var cur := mul;
while cur < to loop
rslt := rslt + cur;
cur := cur + mul;
end loop;
end sub;
 
# number theoretical implementation
sub fastSumMulTo implements SumMulTo is
to := (to - 1)/mul;
rslt := mul * to * (to + 1)/2;
end sub;
 
# sum multiples of 3 and 5 up to given number using given method
sub sum35(to: uint32, sum: SumMulTo): (rslt: uint32) is
rslt := sum(3, to) + sum(5, to) - sum(15, to);
end sub;
 
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method: "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
</syntaxhighlight>
 
{{out}}
 
<pre>Naive method: 233168
Fast method: 233168</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
Short, but not optimized.
<lang ruby>def sum_3_5_muliples(n)
<syntaxhighlight lang="ruby">def sum_3_5_multiples(n)
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end
 
puts sum_3_5_muliplessum_3_5_multiples(1000)</langsyntaxhighlight>
{{out}}
<pre>
233168
</pre>
 
Alternative fast version 1.
The Ruby version sums up to and including n.
To conform to task requirements, and other versions,
modified to find sums below n.
<syntaxhighlight lang="ruby">require "big"
 
def g(n1, n2, n3)
g1 = n1*n2; n3 -= 1
(1..g1).select{|x| x%n1==0 || x%n2==0}.map{|x| g2=(n3-x)//g1; (x+g1*g2+x)*(g2+1)}.sum // 2
end
 
puts g(3,5,999)
puts g(3,5,1000)
# For extra credit
puts g(3,5,"100000000000000000000".to_big_i - 1)
puts g(3,5,"100000000000000000000".to_big_i)</syntaxhighlight>
{{out}}
<pre>
232169
233168
2333333333333333333216666666666666666669
2333333333333333333316666666666666666668
</pre>
 
Alternative faster version 2.
<syntaxhighlight lang="ruby">require "big"
 
def sumMul(n, f)
n1 = (n.to_big_i - 1) // f # number of multiples of f < n
f * n1 * (n1 + 1) // 2 # f * (sum of number of multiples)
end
def sum35(n)
sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15)
end
(1..20).each do |e| limit = 10.to_big_i ** e
puts "%2d:%22d %s" % [e, limit, sum35(limit)]
end</syntaxhighlight>
{{out}}
<pre>
1: 10 23
2: 100 2318
3: 1000 233168
4: 10000 23331668
5: 100000 2333316668
6: 1000000 233333166668
7: 10000000 23333331666668
8: 100000000 2333333316666668
9: 1000000000 233333333166666668
10: 10000000000 23333333331666666668
11: 100000000000 2333333333316666666668
12: 1000000000000 233333333333166666666668
13: 10000000000000 23333333333331666666666668
14: 100000000000000 2333333333333316666666666668
15: 1000000000000000 233333333333333166666666666668
16: 10000000000000000 23333333333333331666666666666668
17: 100000000000000000 2333333333333333316666666666666668
18: 1000000000000000000 233333333333333333166666666666666668
19: 10000000000000000000 23333333333333333331666666666666666668
20: 100000000000000000000 2333333333333333333316666666666666666668
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.bigint;
 
BigInt sum35(in BigInt n) pure nothrow {
Line 776 ⟶ 1,334:
1000.BigInt.sum35.writeln;
(10.BigInt ^^ 20).sum35.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 785 ⟶ 1,343:
2333333333333333333316666666666666666668</pre>
 
=={{header|Déjà Vudc}}==
<syntaxhighlight lang="dc">[ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm
<lang dejavu>sum-divisible n:
0
for i range 1 -- n:
if or = 0 % i 3 = 0 % i 5:
+ i
 
[ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss
!. sum-divisible 1000</lang>
{{out}}
<pre>233168</pre>
 
[ 27 P 91 P 65 P 27 P 91 P 50 P 50 P 67 P ]su
 
[ ll p lsx lux p ll 10 * d sl 1000000000000000000000 >d]sd
 
1 sl ldx</syntaxhighlight>
 
{{Out}}
<pre>1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668
10000000000 23333333331666666668
100000000000 2333333333316666666668
1000000000000 233333333333166666666668
10000000000000 23333333333331666666666668
100000000000000 2333333333333316666666666668
1000000000000000 233333333333333166666666666668
10000000000000000 23333333333333331666666666666668
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668
10000000000000000000 23333333333333333331666666666666666668
100000000000000000000 2333333333333333333316666666666666666668</pre>
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program sum35;
 
{$APPTYPE CONSOLE}
Line 818 ⟶ 1,398:
end;
writeln(sum);
end.</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">sum-divisible n:
0
for i range 1 -- n:
if or = 0 % i 3 = 0 % i 5:
+ i
 
!. sum-divisible 1000</syntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func msum35 n .
for i = 1 to n
if i mod 3 = 0 or i mod 5 = 0
sum += i
.
.
return sum
.
print msum35 999
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when
Line 857 ⟶ 1,461:
❌ error: expected coprimes (42 666)
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 889 ⟶ 1,493:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 897 ⟶ 1,501:
=={{header|Elixir}}==
Simple (but slow)
<langsyntaxhighlight lang="elixir">iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum
233168</langsyntaxhighlight>
 
Fast version:
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def sumMul(n, f) do
n1 = div(n - 1, f)
Line 916 ⟶ 1,520:
n = round(:math.pow(10, i))
IO.puts RC.sum35(n)
end)</langsyntaxhighlight>
 
{{out}}
Line 943 ⟶ 1,547:
 
=={{header|Emacs Lisp}}==
===version 1===
<lang Emacs Lisp>
(defun sum-3-5 (ls)
(apply '+ (mapcar
'(lambda (x) (if (or (= 0 (% x 3) ) (= 0 (% x 5) ))
x 0) )
ls) ))
</lang>
===version 2===
<lang Emacs Lisp>
(defun sum-3-5 (ls)
(apply '+ (seq-filter
'(lambda (x) (or (= 0 (% x 3) ) (= 0 (% x 5) )))
ls) ))
</lang>
<b>Eval:</b>
<lang Emacs Lisp>
(insert (format "%d" (sum-3-5 (number-sequence 1 100) )))
</lang>
<b>Output:</b>
<pre>
2418
</pre>
 
Vanilla:
 
<syntaxhighlight lang="lisp">(defun sum-3-5 (n)
(let ((sum 0))
(dotimes (x n)
(when (or (zerop (% x 3)) (zerop (% x 5)))
(setq sum (+ sum x))))
sum))</syntaxhighlight>
 
{{libheader|seq.el}}
<syntaxhighlight lang="lisp">(defun sum-3-5 (n)
(apply #'+ (seq-filter
(lambda (x) (or (zerop (% x 3) ) (zerop (% x 5))))
(number-sequence 1 (- n 1)))))</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0).
sum_3_5(X, Total) when X < 3 -> Total;
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
Line 976 ⟶ 1,571:
sum_3_5(X-1, Total).
 
io:format("~B~n", [sum_3_5(1000)]).</langsyntaxhighlight>
 
{{out}}
Line 982 ⟶ 1,577:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)
 
Line 995 ⟶ 1,590:
 
[for i = 0 to 30 do yield i]
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))</langsyntaxhighlight>
{{out}}
<pre style="height:5em">233168
Line 1,032 ⟶ 1,627:
 
=={{header|Factor}}==
This solution is based on the following formula to find the sum of an arithmetic sequence:<br><br>
<lang factor>USING: formatting kernel math math.functions sequences
<code>n/2 * (2 * a + (n - 1) * d)</code><br><br>
tools.time ;
&nbsp; &nbsp; '''where'''
IN: rosetta-code.sum35
* <code>a</code> is the first term
* <code>d</code> is the common difference between terms
* <code>n</code> is how many terms to add up
<br>
{{works with|Factor|0.99 2019-10-06}}
<syntaxhighlight lang="factor">USING: kernel math prettyprint ;
 
: sum-multiples ( m n upto -- sum )
: {x+y-z} ( {x,y,z} -- x+y-z ) first3 [ + ] dip - ;
>integer 1 - [ 2dup * ] dip
[ 2dup swap [ mod - + ] [ /i * 2/ ] 2bi ] curry tri@
[ + ] [ - ] bi* ;
 
3 5 1000 sum-multiples .
: range-length ( limit multiple -- len ) [ 1 - ] dip /i ;
3 5 1e20 sum-multiples .</syntaxhighlight>
 
: triangular ( limit multiple -- sum )
[ range-length ] [ nip over 1 + ] 2bi * * 2 / ;
 
: sum35 ( limit -- sum )
{ 3 5 15 } [ triangular ] with map {x+y-z} ;
: msg ( limit sum -- )
"The sum of multiples of 3 or 5 below %d is %d.\n" printf ;
: output ( limit -- ) dup sum35 msg ;
: main ( -- ) [ 1000 10 20 ^ [ output ] bi@ ] time ;
 
MAIN: main</lang>
{{out}}
<pre>
233168
The sum of multiples of 3 or 5 below 1000 is 233168.
The sum of multiples of 3 or 5 below 100000000000000000000 is 2333333333333333333316666666666666666668.
Running time: 0.000923753 seconds
</pre>
 
=={{header|FBSL}}==
Derived from BASIC version
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
Line 1,077 ⟶ 1,666:
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
</syntaxhighlight>
</lang>
Output
<pre>233168
Line 1,085 ⟶ 1,674:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: main ( n -- )
0 swap
3 do
Line 1,096 ⟶ 1,685:
. ;
 
1000 main \ 233168 ok</langsyntaxhighlight>
 
Another FORTH version using the Inclusion/Exclusion Principle. The result is a double precision integer (128 bits on a 64 bit computer) which lets us calculate up to 10^18 (the max precision of a single precision 64 bit integer) Since this is Project Euler problem 1, the name of the main function is named euler1tower.
 
<langsyntaxhighlight lang="forth">: third 2 pick ;
 
: >dtriangular ( n -- d )
Line 1,142 ⟶ 1,731:
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668 ok
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
The method here recalls the story of the young Gauss being set the problem of adding up all the integers from one to a hundred by a master who wanted some peace and quiet from his class. The trick here is to apply the formula for multiples of three and for five, then remember that multiples of fifteen will have been counted twice.
 
Early Fortrans did not offer such monsters as INTEGER*8 but the F95 compiler I have does so. Even so, the source is in the style of F77 which means that in the absence of the MODULE protocol, the types of the functions must be specified if they are not default types. F77 also does not accept the <code>END FUNCTION ''name''</code> protocol that F90 does, but such documentation enables compiler checks and not using it makes me wince.
<syntaxhighlight lang="fortran">
<lang Fortran>
INTEGER*8 FUNCTION SUMI(N) !Sums the integers 1 to N inclusive.
Calculates as per the young Gauss: N*(N + 1)/2 = 1 + 2 + 3 + ... + N.
Line 1,187 ⟶ 1,777:
GO TO 10 !Have another go.
END !So much for that.
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 1,210 ⟶ 1,800:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function sum35 (n As UInteger) As UInteger
Line 1,224 ⟶ 1,814:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
<pre>
Sum of positive integers below 1000 divisible by 3 or 5 is : 233168
</pre>
 
=={{header|Frink}}==
Program has a brute-force approach for n=1000, and also inclusion/exclusion for larger values.
<syntaxhighlight lang="frink">
sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]
 
sumdiv[n, d] :=
{
m = floor[n/d]
m(m + 1)/2 d
}
 
sum35big[n] := sumdiv[n, 3] + sumdiv[n, 5] - sumdiv[n, 15]
 
println["The sum of all the multiples of 3 or 5 below 1000 is $sum999"]
println["The sum of all multiples less than 1e20 is " + sum35big[1_00000_00000_00000_00000 - 1]]
</syntaxhighlight>
{{Out}}
<pre>
The sum of all the multiples of 3 or 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
_n = 1000
 
void local fn DoIt
long i, sum = 0
for i = 0 to _n - 1
if ( i mod 3 == 0 or i mod 5 == 0 )
sum += i
end if
next
NSLog(@"%ld",sum)
end fn
 
fn Doit
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
233168
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,253 ⟶ 1,892:
return n
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,259 ⟶ 1,898:
</pre>
Extra credit:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,289 ⟶ 1,928:
s := sum2(b3)
return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,297 ⟶ 1,936:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 }
def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }</langsyntaxhighlight>
Test Code:
<langsyntaxhighlight lang="groovy">[(1000): 233168, (10e20): 233333333333333333333166666666666666666668].each { arg, value ->
println "Checking $arg == $value"
assert sum35(arg) == value
}</langsyntaxhighlight>
{{out}}
<pre>Checking 1000 == 233168
Line 1,310 ⟶ 1,949:
=={{header|Haskell}}==
Also a method for calculating sum of multiples of any list of numbers.
<langsyntaxhighlight lang="haskell">import Data.List (nub)
 
----------------- SUM MULTIPLES OF 3 AND 5 ---------------
sum35 :: Integral a => a -> a
sum35 n = sumMul n 3 + sumMul n 5 - sumMul n 15
 
sum35 :: Integer -> Integer
sumMul :: Integral a => a -> a -> a
sum35 n = f 3 + f 5 - f 15
where
f = sumMul n
 
sumMul :: Integer -> Integer -> Integer
sumMul n f = f * n1 * (n1 + 1) `div` 2
where
n1 = (n - 1) `div` f
 
-- Functions below are for variable length inputs
 
pairLCM :: Integral a => [a] -> [a]
pairLCM [] = []
pairLCM (x:xs) = (lcm x <$> xs) ++ pairLCM xs
 
sumMulS :: Integral a => a -> [a] -> a
sumMulS _ [] = 0
sumMulS n s = sum (sumMul n <$> ss) - sumMulS n (pairLCM ss)
where
ss = nub s
 
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
print
[ sum35 1000,
, sum35 100000000000000000000000000000000,
, sumMulS 1000 [3, 5],
, sumMulS 10000000 [2, 3, 5, 7, 11, 13]
]</lang>
 
---------------- FOR VARIABLE LENGTH INPUTS --------------
 
pairLCM :: [Integer] -> [Integer]
pairLCM [] = []
pairLCM (x : xs) = (lcm x <$> xs) <> pairLCM xs
 
sumMulS :: Integer -> [Integer] -> Integer
sumMulS _ [] = 0
sumMulS n s =
( ((-) . sum . fmap f)
<*> (g . pairLCM)
)
(nub s)
where
f = sumMul n
g = sumMulS n</syntaxhighlight>
{{out}}
<pre>233168
Line 1,351 ⟶ 2,001:
The following works in both langauges.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
n := (integer(A[1]) | 1000)-1
write(sum(n,3)+sum(n,5)-sum(n,15))
Line 1,358 ⟶ 2,008:
procedure sum(n,m)
return m*((n/m)*(n/m+1)/2)
end</langsyntaxhighlight>
 
Sample output:
Line 1,372 ⟶ 2,022:
=={{header|J}}==
 
The problem can also be solved with a simple use of inclusion/exclusion; this solution is more in keeping with how one could approach the problem from a more traditional language.
<lang J>
<syntaxhighlight lang="j">
mp =: $:~ :(+/ .*) NB. matrix product
NB. Naive method
f =: (mp 0 = [: */ 3 5 |/ ])@:i.
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.
assert 233168 -: f 1000 NB. ****************** THIS IS THE ANSWER FOR 1000
echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)
</lang>
For the efficient computation with large n, we start with observation that the sum of these multiples with the reversed list follows a pattern.
<lang J>
g =: #~ (0 = [: */ 3 5&(|/))
assert 0 3 5 6 9 10 12 15 18 20 21 24 25 27 30 33 35 36 39 40 42 45 48 -: g i. 50
assert 48 48 47 46 48 46 47 48 48 47 46 48 46 47 48 48 47 46 48 46 47 48 48 -: (+ |.)g i. 50 NB. the pattern
 
NB. slightly less naive: select the numbers which have no remainder when divided by 3 or 5:
assert (f -: -:@:(+/)@:(+|.)@:g@:i.) 50 NB. half sum of the pattern.
echo 'The sum of the multiples of 3 or 5 < 1000 is still ', ": +/I.+./0=3 5|/i.1000
 
NB. continue...
</lang>
Stealing the idea from the python implementation to use 3 simple patterns rather than 1 complicated pattern,
<lang J>
first =: 0&{
last =: first + skip * <.@:(skip %~ <:@:(1&{) - first)
skip =: 2&{
terms =: >:@:<.@:(skip %~ last - first)
sum_arithmetic_series =: -:@:(terms * first + last) NB. sum_arithmetic_series FIRST LAST SKIP
NB. interval is [FIRST, LAST)
NB. sum_arithmetic_series is more general than required.
 
(0,.10 10000 10000000000000000000x)(,"1 0"1 _)3 5 15x NB. demonstration: form input vectors for 10, ten thousand, and 1*10^(many)
0 10 3
0 10 5
0 10 15
 
NB. inclusion/exclusion
0 10000 3
0 10000 5
0 10000 15
 
triangular =: -:@:(*: + 1&*)
0 10000000000000000000 3
sumdiv =: dyad define
0 10000000000000000000 5
(triangular <. x % y) * y
0 10000000000000000000 15
)
 
echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
 
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 < 1000 is 233168
The sum of the multiples of 3 or 5 < 1000 is still 233168
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668
</pre>
 
=={{header|Java}}==
(0,.10 10000 10000000000000000000x)+`-/"1@:(sum_arithmetic_series"1@:(,"1 0"1 _))3 5 15x
===Simple Version===
23 23331668 23333333333333333331666666666666666668
<syntaxhighlight lang="java">class SumMultiples {
</lang>
public static long getSum(long n) {
long sum = 0;
for (int i = 3; i < n; i++) {
if (i % 3 == 0 || i % 5 == 0) sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(getSum(1000));
}
}</syntaxhighlight>
{{out}}
<pre>233168</pre>
===Extra Credit===
<syntaxhighlight lang="java">
import java.math.BigInteger;
 
public class SumMultiples {
 
public static void main(String[] args) {
BigInteger m1 = BigInteger.valueOf(3);
BigInteger m2 = BigInteger.valueOf(5);
for ( int i = 1 ; i <= 25 ; i++ ) {
BigInteger limit = BigInteger.valueOf(10).pow(i);
System.out.printf("Limit = 10^%d, answer = %s%n", i, sumMultiples(limit.subtract(BigInteger.ONE), m1, m2));
}
}
 
// Use Inclusion - Exclusion
private static BigInteger sumMultiples(BigInteger max, BigInteger n1, BigInteger n2) {
return sumMultiple(max, n1).add(sumMultiple(max, n2)).subtract(sumMultiple(max, n1.multiply(n2)));
}
private static BigInteger sumMultiple(BigInteger max, BigInteger m) {
BigInteger maxDivM = max.divide(m);
return m.multiply(maxDivM.multiply(maxDivM.add(BigInteger.ONE))).divide(BigInteger.valueOf(2));
}
// Used for testing
@SuppressWarnings("unused")
private static long sumMultiples(long max, long n1, long n2) {
return sumMultiple(max, n1) + sumMultiple(max, n2) - sumMultiple(max, n1 * n2);
}
private static long sumMultiple(long max, long n) {
long sum = 0;
for ( int i = 1 ; i <= max ; i++ ) {
if ( i % n == 0 ) {
sum += i;
}
}
return sum;
}
 
}
</syntaxhighlight>
{{out}}
<pre>
Limit = 10^1, answer = 23
Limit = 10^2, answer = 2318
Limit = 10^3, answer = 233168
Limit = 10^4, answer = 23331668
Limit = 10^5, answer = 2333316668
Limit = 10^6, answer = 233333166668
Limit = 10^7, answer = 23333331666668
Limit = 10^8, answer = 2333333316666668
Limit = 10^9, answer = 233333333166666668
Limit = 10^10, answer = 23333333331666666668
Limit = 10^11, answer = 2333333333316666666668
Limit = 10^12, answer = 233333333333166666666668
Limit = 10^13, answer = 23333333333331666666666668
Limit = 10^14, answer = 2333333333333316666666666668
Limit = 10^15, answer = 233333333333333166666666666668
Limit = 10^16, answer = 23333333333333331666666666666668
Limit = 10^17, answer = 2333333333333333316666666666666668
Limit = 10^18, answer = 233333333333333333166666666666666668
Limit = 10^19, answer = 23333333333333333331666666666666666668
Limit = 10^20, answer = 2333333333333333333316666666666666666668
Limit = 10^21, answer = 233333333333333333333166666666666666666668
Limit = 10^22, answer = 23333333333333333333331666666666666666666668
Limit = 10^23, answer = 2333333333333333333333316666666666666666666668
Limit = 10^24, answer = 233333333333333333333333166666666666666666666668
Limit = 10^25, answer = 23333333333333333333333331666666666666666666666668
</pre>
 
=={{header|JavaScript}}==
Line 1,421 ⟶ 2,142:
===ES5===
 
JavaScript is better equipped for flexibility than for scale. The value of <syntaxhighlight lang JavaScript="javascript"> Number.MAX_SAFE_INTEGER</langsyntaxhighlight> is 9007199254740991, or 2^53 - 1 – resulting from an IEEE 754 double-precision floating point representation of numeric values).
 
As ''Number.MAX_SAFE_INTEGER < 1E20'' evaluates to ''true'', the most obvious JS attack on a solution for 1E20 might involve some string processing …
Line 1,427 ⟶ 2,148:
At more modest scales, however, we can generalise a little to allow for an arbitrary list of integer factors, and write a simple generate, filter and sum approach:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (lstFactors, intExponent) {
 
// [n] -> n -> n
Line 1,485 ⟶ 2,206:
JSON.stringify(lstTable);
 
})([3, 5], 8);</langsyntaxhighlight>
 
 
Line 1,511 ⟶ 2,232:
|}
 
<langsyntaxhighlight JavaScriptlang="javascript"> [["Below","Sum"],["10^1",23],["10^2",2318],["10^3",233168],
["10^4",23331668],["10^5",2333316668],["10^6",233333166668],
["10^7",23333331666668],["10^8",2333333316666668]]</langsyntaxhighlight>
====With wheel increments====
<langsyntaxhighlight JavaScriptlang="javascript">function sm35(n){
var s=0, inc=[3,2,1,3,1,2,3]
for (var j=6, i=0; i<n; j+=j==6?-j:1, i+=inc[j]) s+=i
return s
}</langsyntaxhighlight>
====With triangular numbers====
<langsyntaxhighlight JavaScriptlang="javascript">function sm35(n){
return tri(n,3) + tri(n,5) - tri(n,15)
function tri(n, f) {
Line 1,527 ⟶ 2,248:
return f * n * (n+1) / 2
}
}</langsyntaxhighlight>
'''This:'''
<langsyntaxhighlight JavaScriptlang="javascript">for (var i=1, n=10; i<9; n*=10, i+=1) {
document.write(10, '<sup>', i, '</sup> ', sm35(n), '<br>')
}</langsyntaxhighlight>
{{out}}
10<sup>1</sup> 23
Line 1,545 ⟶ 2,266:
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// sum35 :: Int -> Int
const sum35 = n => {
// The sum of all positive multiples of
// 3 or 5 below n.
const f = sumMults(n);
return f(3) + f(5) - f(15);
};
 
// Area under straight line
// between first multiple and last.
 
// sumMults :: Int -> Int -> Int
const sumMults = (n, factor) => {
const// n1Area =under quot(nstraight - 1, factor);line
return// quot(factorbetween *first n1multiple *and (n1 + 1), 2);last.
}; factor => {
const n1 = quot(n - 1)(factor);
return quot(factor * n1 * (n1 + 1))(2);
};
 
// ------------------------- TEST --------------------------
// sum35 :: Int -> Int
 
const sum35 = n => sumMults(n, 3) + sumMults(n, 5) - sumMults(n, 15);
// main :: IO ()
const main = () =>
fTable('Sums for n = 10^1 thru 10^8:')(str)(str)(
sum35
)(
enumFromTo(1)(8)
.map(n => Math.pow(10, n))
);
 
 
// GENERIC ---------------------------------------- GENERIC ------------------------
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.fromn => !isNaN(m) ? ({
length: MathArray.floorfrom(n - m) + 1{
}, (_, i) => m length: 1 + i);n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
 
// Integral a => a -> a -> a
const quot = (n, m) => Math.floor(n / m);
 
// quot :: Int -> Int -> Int
// TEST -------------------------------------------------------------------
const quot = n =>
m => Math.floor(n / m);
 
 
// Sums for 10^1 thru 10^8
// ------------------------ DISPLAY ------------------------
return enumFromTo(1, 8)
 
.map(n => Math.pow(10, n))
// compose (<<<) :: .reduce(b -> c) -> (a, x-> b) =-> (a -> c
const compose = a[x(.toString(..fs)] = sum35(x),>
// A function defined aby the right-to-left
// composition of all the functions in fs.
), {});
fs.reduce(
})();</lang>
(f, g) => x => f(g(x)),
x => x
);
 
 
// fTable :: String -> (a -> String) -> (b -> String)
// -> (a -> b) -> [a] -> String
const fTable = s =>
// Heading -> x display function ->
// fx display function ->
// f -> values -> tabular string
xShow => fxShow => f => xs => {
const
ys = xs.map(xShow),
w = Math.max(...ys.map(length));
return s + '\n' + zipWith(
a => b => a.padStart(w, ' ') + ' -> ' + b
)(ys)(
xs.map(x => fxShow(f(x)))
).join('\n');
};
 
 
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.length
) : Infinity;
 
 
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs);
 
 
// str :: a -> String
const str = x =>
Array.isArray(x) && x.every(
v => ('string' === typeof v) && (1 === v.length)
) ? (
x.join('')
) : x.toString();
 
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
 
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// Use of `take` and `length` here allows zipping with non-finite lists
// i.e. generators like cycle, repeat, iterate.
xs => ys => {
const n = Math.min(length(xs), length(ys));
return (([as, bs]) => Array.from({
length: n
}, (_, i) => f(as[i])(
bs[i]
)))([xs, ys].map(
compose(take(n), list)
));
};
 
// ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>Sums for n = 10^1 thru 10^8:
<lang JavaScript>{"10":23, "100":2318, "1000":233168, "10000":23331668,
10 -> 23
"100000":2333316668, "1000000":233333166668, "10000000":23333331666668,
100 -> 2318
"100000000":2333333316666668}</lang>
1000 -> 233168
10000 -> 23331668
100000 -> 2333316668
1000000 -> 233333166668
10000000 -> 23333331666668
100000000 -> 2333333316666668</pre>
 
=={{header|JavaJoy}}==
<syntaxhighlight lang="jq">
<lang Java>class SumMultiples {
DEFINE divisor == rem 0 = ;
public static long getSum(long n) {
mul3or5 == [3 divisor] [5 divisor] cleave or ;
long sum = 0;
for (int i = 3; i < n;when == swap [] i++)ifte {.
if (i % 3 == 0 || i % 5 == 0) sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(getSum(1000));
}
}</lang>
{{out}}
<pre>233168</pre>
 
"The sum of the multiples of 3 or 5 below 1000 is " putchars
 
0 999 [0 =] [pop]
[
[dup rollup + swap] [mul3or5] when
pred
] tailrec .
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 below 1000 is 233168
</pre>
=={{header|jq}}==
<syntaxhighlight lang="jq">
<lang jq>
def sum_multiples(d):
((./d) | floor) | (d * . * (.+1))/2 ;
Line 1,610 ⟶ 2,444:
def task(a;b):
. - 1
| sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);</langsyntaxhighlight>Examples:
 
jq does not (yet) support arbitrary-precision integer arithmetic but converts large integers to floats, so:
<syntaxhighlight lang="jq">
<lang jq>
1000 | task(3;5) # => 233168
 
10e20 | task(3;5) # => 2.333333333333333e+41</langsyntaxhighlight>
 
 
=={{header|Julia}}==
sum multiples of each, minus multiples of the least common multiple (lcm). Similar to MATLAB's version.
<langsyntaxhighlight Julialang="julia">multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)</langsyntaxhighlight>
Output:
<pre>julia> multsum(3, 5, 1000)
Line 1,656 ⟶ 2,491:
(100000000000000000000,2333333333333333333316666666666666666668)</pre>
a slightly more efficient version
<langsyntaxhighlight Julialang="julia">multsum(n, lim) = (occ = div(lim-1, n); div(n*occ*(occ+1), 2))
multsum(n, m, lim) = multsum(n, lim) + multsum(m, lim) - multsum(lcm(n,m), lim)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 1,690 ⟶ 2,525:
val e20 = big100k * big100k * big100k * big100k
println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,699 ⟶ 2,534:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(limit = 1)
while(#limit <= 100000) => {^
local(s = 0)
Line 1,707 ⟶ 2,542:
'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
#limit = integer(#limit->asString + '0')
^}</langsyntaxhighlight>
{{out}}
<pre>The sum of multiples of 3 or 5 between 1 and 0 is: 0
Line 1,720 ⟶ 2,555:
Uses the IPints library when the result will be very large.
 
<langsyntaxhighlight Limbolang="limbo">implement Sum3and5;
 
include "sys.m"; sys: Sys;
Line 1,792 ⟶ 2,627:
sub(isum_multiples(ints[15], limit)));
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,800 ⟶ 2,635:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on sum35 (n)
res = 0
repeat with i = 0 to (n-1)
Line 1,808 ⟶ 2,643:
end repeat
return res
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">put sum35(1000)
-- 233168</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function sumUntil n
repeat with i = 0 to (n-1)
if i mod 3 = 0 or i mod 5 = 0 then
Line 1,823 ⟶ 2,658:
end sumUntil
 
put sumUntil(1000) // 233168</langsyntaxhighlight>
 
=={{header|Lua}}==
{{trans|Tcl}}
<syntaxhighlight lang="lua">
<lang Lua>
function tri (n) return n * (n + 1) / 2 end
 
Line 1,840 ⟶ 2,675:
print(sum35(1000))
print(sum35(1e+20))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,849 ⟶ 2,684:
=={{header|Maple}}==
By using symbolic function <code>sum</code> instead of numeric function <code>add</code> the program <code>F</code> will run O(1) rather than O(n).
<syntaxhighlight lang="maple">
<lang Maple>
F := unapply( sum(3*i,i=1..floor((n-1)/3))
+ sum(5*i,i=1..floor((n-1)/5))
Line 1,857 ⟶ 2,692:
 
F(10^20);
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,876 ⟶ 2,711:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">sum35[n_] :=
Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] -
Sum[k, {k, 15, n - 1, 15}]
sum35[1000]</syntaxhighlight>
 
sum35[1000]</lang>
{{out}}
<pre>233168</pre>
<syntaxhighlight lang ="mathematica">sum35[10^20]</langsyntaxhighlight>
{{out}}
<pre>233333333333333333333166666666666666666668</pre>
 
Another alternative is
<langsyntaxhighlight lang="mathematica"> Union @@ Range[0, 999, {3, 5}] // Tr </langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0))</langsyntaxhighlight>
<pre>ans = 233168</pre>
Another alternative is
<langsyntaxhighlight MATLABlang="matlab">n=1000; sum(0:3:n-1)+sum(0:5:n-1)-sum(0:15:n-1)</langsyntaxhighlight>
Of course, it's more efficient to use [http://mathforum.org/library/drmath/view/57919.html Gauss' approach] of adding subsequent integers:
<langsyntaxhighlight MATLABlang="matlab">n=999;
n3=floor(n/3);
n5=floor(n/5);
n15=floor(n/15);
(3*n3*(n3+1) + 5*n5*(n5+1) - 15*n15*(n15+1))/2</langsyntaxhighlight>
<pre>ans = 233168</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang Maxima="maxima">sumi(n, incrinc):= block([kmax: quotient(n, incr)],
[kmax],
''(ev(sum(incr*k, k, 1, kmax), simpsum)));
 
/* below n means [1 .. n-1] */
sum35(n):=sumi(n, 3) + sumi(n, 5) - sumi(n, 15);
kmax: quotient(n-1, inc),
return(
''(ev(sum(inc*k, k, 1, kmax), simpsum))
)
);
sum35(n):= sumi(n, 3) + sumi(n, 5) - sumi(n, 15);
 
sum35(1000);
sum35(10^20);</langsyntaxhighlight>
Output:
<pre>(%i16) sum35(1000);
(%i4) sum35(1000)
(%o16) 234168
(%o4) 233168
(%i17) sum35(10^20);
(%i5) sum35(10^20)
(%o17) 2333333333333333333416666666666666666668</pre>
(%o5) 2333333333333333333316666666666666666668
</pre>
 
=={{header|MiniScript}}==
 
First, the simple implementation. It loops by threes and fives, and in the second loop, skips any multiples of five that are also divisible by three.
<syntaxhighlight lang="miniscript">// simple version:
sum35 = function(n)
sum = 0
for i in range(3, n-1, 3)
sum = sum + i
end for
for i in range(5, n-1, 5)
if i % 3 then sum = sum + i // (skip multiples of 3 here)
end for
return sum
end function
 
print sum35(1000)</syntaxhighlight>
{{out}}
<pre>233168</pre>
 
Now the fast version.
{{trans|D}}
<syntaxhighlight lang="miniscript">// fast version:
sumMul = function(n, f)
n1 = floor((n - 1) / f)
return f * n1 * (n1 + 1) / 2
end function
 
sum35fast = function(n)
return sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15)
end function
 
print sum35fast(1000)</syntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 0 П0 3 П4 ИП4 3 / {x} x#0
17 ИП4 5 / {x} x=0 21 ИП0 ИП4 +
П0 КИП4 ИП1 ИП4 - x=0 05 ИП0 С/П</langsyntaxhighlight>
 
Input: ''n''.
 
Output for n = 1000: ''233168''.
 
=={{header|Nanoquery}}==
{{trans|Java}}
This solution is translated from the simple Java version. Since all integers are arbitrary precision in Nanoquery, it is possible to use this solution for large n, but it is inefficient.
<syntaxhighlight lang="nanoquery">def getSum(n)
sum = 0
for i in range(3, n - 1)
if (i % 3 = 0) or (i % 5 = 0)
sum += i
end
end
return sum
end
 
println getSum(1000)</syntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|NetRexx}}==
Portions translation of [[#Perl 6Raku|Perl 6Raku]]
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 40
Line 1,946 ⟶ 2,840:
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- translation of perl 6Raku
method sum_mults(first, limit) public static
last = limit - 1
Line 2,006 ⟶ 2,900:
say
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,064 ⟶ 2,958:
 
=={{header|Nim}}==
Here is the solution using normal integers.
<lang nim>proc sum35(n: int): int =
<syntaxhighlight lang="nim">proc sum35(n: int): int =
for x in 0 .. <n:
for x in 0 ..< n:
if x mod 3 == 0 or x mod 5 == 0:
result += x
 
echo sum35(1000)</langsyntaxhighlight>
 
{{out}}
With BigInts:
<pre>233168</pre>
{{trans|Perl 6}}
 
<lang nim>import bigints
To compute until 1e20, we have to use big integers. As Nim doesn’t provided them in its library, we have to use a third party library, either "bigints" or "bignum".
 
{{trans|Raku}}
{{libheader|bigints}}
<syntaxhighlight lang="nim">import bigints
 
proc sumMults(first: int32, limit: BigInt): BigInt =
Line 2,088 ⟶ 2,988:
while x < "1000000000000000000000000000000".initBigInt:
echo sum35 x
x *= 10</langsyntaxhighlight>
 
Output:
{{out}}
<pre>-0
<pre>0
23
2318
Line 2,123 ⟶ 3,024:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class SumMultiples {
function : native : GetSum(n : Int) ~ Int {
sum := 0;
Line 2,139 ⟶ 3,040:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 2,146 ⟶ 3,047:
</pre>
 
=={{header|Odin}}==
Note: 1e19 is the largest sum that can be calculated with 128 bit integers.
<syntaxhighlight lang="odin">
package main
 
import "core:fmt"
 
sumdiv :: proc(n, d: i128) -> i128 {
m := n / d
return (m % 2 == 0)? \
m/2 * (m + 1) * d : \
(m + 1)/2 * m * d
}
 
sum3or5 :: proc(n: i128) -> i128 {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)
}
 
main :: proc() {
sum := 0
for n in 1..=999 {
if n % 3 == 0 || n % 5 == 0 {
sum += n
}
}
fmt.println("The sum of all multiples of 3 and 5 < 1000 is", sum)
fmt.println("The sum of all multiples of 3 and 5 < 1e19 is", sum3or5(1e19 - 1))
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of all multiples of 3 and 5 < 1000 is 233168
The sum of all multiples of 3 and 5 < 1e19 is 23333333333333333331666666666666666668
</pre>
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sum_multssum_m3m5 n =
let termial x = (x * letx sum+ =x) reflsr 01 in
3 * (termial (n / 3) for- i5 =* 3 totermial (n -/ 115)) do+ 5 * termial (n / 5)
if (i mod 3) = 0 || (i mod 5) = 0 then
sum := !sum + i;
done;
!sum;;
 
let () =
print_endline (string_of_int (sum_mults 1000));;
let pow10 x = truncate (10. ** (float x)) in
</lang>
for i = 1 to 9 do
let u = pred (pow10 i) in
Printf.printf "Summing multiples of 3 or 5 in 1..%u: %u\n" u (sum_m3m5 u)
done</syntaxhighlight>
{{out}}
<pre>233168</pre>
Summing multiples of 3 or 5 in 1..9: 23
Summing multiples of 3 or 5 in 1..99: 2318
Summing multiples of 3 or 5 in 1..999: 233168
Summing multiples of 3 or 5 in 1..9999: 23331668
Summing multiples of 3 or 5 in 1..99999: 2333316668
Summing multiples of 3 or 5 in 1..999999: 233333166668
Summing multiples of 3 or 5 in 1..9999999: 23333331666668
Summing multiples of 3 or 5 in 1..99999999: 2333333316666668
Summing multiples of 3 or 5 in 1..999999999: 233333333166666668
</pre>
=== With wheel increments (slower) ===
<syntaxhighlight lang="ocaml">
open Printf;;
 
let mul3or5 =
let rec wheel = 3 :: 2 :: 1 :: 3 :: 1 :: 2 :: 3 :: wheel in
Seq.scan (+) 0 (List.to_seq wheel);;
 
let sum3or5 upto =
mul3or5
|> Seq.take_while (fun n -> n < upto)
|> Seq.fold_left (+) 0;;
 
printf "The sum of the multiples of 3 or 5 below 1000 is %d\n" (sum3or5 1000);;
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 below 1000 is 233168
</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">999 seq filter(#[ dup 3 mod 0 == swap 5 mod 0 == or ]) sum println</langsyntaxhighlight>
 
Output:
Line 2,170 ⟶ 3,134:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(print
(fold (lambda (s x)
Line 2,176 ⟶ 3,140:
0 (iota 1000)))
; ==> 233168
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">ct(n,k)=n=n--\k;k*n*(n+1)/2;
a(n)=ct(n,3)+ct(n,5)-ct(n,15);
a(1000)
a(1e20)</langsyntaxhighlight>
{{output}}
<pre>
Line 2,193 ⟶ 3,157:
{{works with|Free Pascal|2.6.2}}
 
<langsyntaxhighlight Pascallang="pascal">program Sum3sAnd5s;
function Multiple(x, y: integer): Boolean;
Line 2,215 ⟶ 3,179:
{ Show sum of all multiples less than 1000. }
writeln(SumMultiples(1000))
end.</langsyntaxhighlight>
===alternative===
using gauss summation formula, but subtract double counted.
adapted translation of [[#Tcl|Tcl]]
<langsyntaxhighlight Pascallang="pascal">program sum35;
//sum of all positive multiples of 3 or 5 below n
 
Line 2,240 ⟶ 3,204:
sum := sum-cntSumdivisibleBelowN(n,3*5);
writeln(sum);
end.</langsyntaxhighlight>
output
<pre>233168</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="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" ;</langsyntaxhighlight>
{{Out}}
<pre>The sum is 233168 !</pre>
 
{{Trans|Tcl}}
An alternative approach, using the analytical solution from the Tcl example.
<syntaxhighlight lang Perl="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) {
sub sum
$n * tri( int( ($limit - 1) / $n ) )
{
}
my $n = (shift) - 1;
 
(3 * tri( int($n/3) ) + 5 * tri( int($n/5) ) - 15 * tri( int($n/15) ) );
sub sum($n) {
sum_multiples(3, $n) + sum_multiples(5, $n) - sum_multiples(15, $n);
}
 
say sum( 1e3);
use bigint; # Machine precision was sufficient for the first calculation
say sum( 1e20);</langsyntaxhighlight>
{{Out}}
<pre>233168
2333333333333333333316666666666666666668</pre>
Interestingly, the prime factorization of the second result produces a 35 digit prime number.
 
=={{header|Perl 6}}==
<lang perl6>sub sum35($n) { [+] grep * %% (3|5), ^$n; }
 
say sum35 1000;</lang>
{{out}}
<pre>233168</pre>
Here's an analytical approach that scales much better for large values.
<lang perl6>sub sum-mults($first, $limit) {
(my $last = $limit - 1) -= $last % $first;
($last div $first) * ($first + $last) div 2;
}
 
sub sum35(\n) {
sum-mults(3,n) + sum-mults(5,n) - sum-mults(15,n);
}
 
say sum35($_) for 1,10,100...10**30;</lang>
{{out}}
<pre>0
23
2318
233168
23331668
2333316668
233333166668
23333331666668
2333333316666668
233333333166666668
23333333331666666668
2333333333316666666668
233333333333166666666668
23333333333331666666666668
2333333333333316666666666668
233333333333333166666666666668
23333333333333331666666666666668
2333333333333333316666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668
2333333333333333333316666666666666666668
233333333333333333333166666666666666666668
23333333333333333333331666666666666666666668
2333333333333333333333316666666666666666666668
233333333333333333333333166666666666666666666668
23333333333333333333333331666666666666666666666668
2333333333333333333333333316666666666666666666666668
233333333333333333333333333166666666666666666666666668
23333333333333333333333333331666666666666666666666666668
2333333333333333333333333333316666666666666666666666666668
233333333333333333333333333333166666666666666666666666666668</pre>
 
=={{header|Phix}}==
===native===
{{trans|AWK}}
note the result of sum35() is inaccurate above 2^53 on 32-bit, 2^64 on 64-bit.
{{libheader|bigatom}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sum35</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span>
<span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">-</span>
<span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">sp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s%s%s %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sum35</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
</pre>
===gmp===
{{trans|C}}
{{libheader|Phix/mpfr}}
Fast analytical version with arbitrary precision
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include bigatom.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
function s(bigatom n, integer d)
bigatom m = ba_idivide(n,d)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpz</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
m = ba_multiply(m,ba_add(m,1))
<span style="color: #004080;">mpz</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
return ba_divide(ba_multiply(d,m),2)
<span style="color: #7060A8;">mpz_sub_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
 
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
function sum35(bigatom n)
<span style="color: #7060A8;">mpz_add_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">);</span>
bigatom n1 = ba_sub(n,1)
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
return ba_sub(ba_add(s(n1,3),s(n1,5)),s(n1,15))
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #7060A8;">mpz_fdiv_q_2exp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
for i=0 to 20 do
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
string sp = repeat(' ',20-i)
printf(1,sp&"1"&repeat('0',i)&sp)
<span style="color: #004080;">mpz</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
ba_printf(1," %B\n",sum35(ba_power(10,i)))
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
end for</lang>
<span style="color: #004080;">string</span> <span style="color: #000000;">sp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"1"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %s\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,379 ⟶ 3,340:
</pre>
 
=={{header|PHP}}==
 
Naive version (slow) :
 
<syntaxhighlight lang="php">$max = 1000;
$sum = 0;
for ($i = 1 ; $i < $max ; $i++) {
if (($i % 3 == 0) or ($i % 5 == 0)) {
$sum += $i;
}
}
echo $sum, PHP_EOL;
</syntaxhighlight>
 
{{out}}
<pre>233168</pre>
 
Fast version:
 
<syntaxhighlight lang="php">function sum_multiples($max, $divisor) {
// Number of multiples of $divisor <= $max
$num = floor($max / $divisor);
// Sum of multiples of $divisor
return ($divisor * $num * ($num + 1) / 2);
}
 
$max = 1000;
$sum = sum_multiples($max - 1, 3)
+ sum_multiples($max - 1, 5)
- sum_multiples($max - 1, 15);
echo $sum, PHP_EOL;</syntaxhighlight>
 
{{out}}
<pre>233168</pre>
 
{{libheader|GMP}}
 
Fast version using GNU Multiple Precision library.
These functions allow for arbitrary-length integers to be worked with.
 
<syntaxhighlight lang="php">function sum_multiples_gmp($max, $divisor) {
// Number of multiples of $divisor <= $max
$num = gmp_div($max, $divisor);
// Sum of multiples of $divisor
return gmp_div(gmp_mul(gmp_mul($divisor, $num), gmp_add($num, 1)), 2);
}
 
for ($i = 0, $n = gmp_init(10) ; $i < 21 ; $i++, $n = gmp_mul($n, 10)) {
$max = gmp_sub($n, 1);
$sum =
gmp_sub(
gmp_add(
sum_multiples_gmp($max, 3),
sum_multiples_gmp($max, 5)
),
sum_multiples_gmp($max, 15)
);
printf('%22s : %s' . PHP_EOL, gmp_strval($n), $sum);
}</syntaxhighlight>
 
{{out}}
<pre> 10 : 23
100 : 2318
1000 : 233168
10000 : 23331668
100000 : 2333316668
1000000 : 233333166668
10000000 : 23333331666668
100000000 : 2333333316666668
1000000000 : 233333333166666668
10000000000 : 23333333331666666668
100000000000 : 2333333333316666666668
1000000000000 : 233333333333166666666668
10000000000000 : 23333333333331666666666668
100000000000000 : 2333333333333316666666666668
1000000000000000 : 233333333333333166666666666668
10000000000000000 : 23333333333333331666666666666668
100000000000000000 : 2333333333333333316666666666666668
1000000000000000000 : 233333333333333333166666666666666668
10000000000000000000 : 23333333333333333331666666666666666668
100000000000000000000 : 2333333333333333333316666666666666666668
1000000000000000000000 : 233333333333333333333166666666666666666668
</pre>
 
=={{header|Picat}}==
Uses both the naive method and inclusion/exclusion.
<syntaxhighlight lang="picat">
sumdiv(N, D) = S =>
M = N div D,
S = (M*(M + 1) div 2) * D.
 
sum35big(N) = sumdiv(N, 3) + sumdiv(N, 5) - sumdiv(N, 15).
 
main =>
Upto1K = [N: N in 1..999, (N mod 3 = 0; N mod 5 = 0)].sum,
writef("The sum of all multiples of 3 and 5 below 1000 is %w%n", Upto1K),
writef("The sum of all multiples less than 1e20 is %w%n", sum35big(99999_99999_99999_99999)).
</syntaxhighlight>
{{Out}}
<pre>
The sum of all multiples of 3 and 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668
</pre>
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de sumMul (N F)
(let N1 (/ (dec N) F)
(*/ F N1 (inc N1) 2) ) )
Line 2,389 ⟶ 3,453:
(-
(+ (sumMul N 3) (sumMul N 5))
(sumMul N 15) ) ) ) )</syntaxhighlight>
{{out}}
 
<pre>
(bye)</lang>
23
2318
233168
23331668
2333316668
233333166668
23333331666668
2333333316666668
233333333166666668
23333333331666666668
2333333333316666666668
233333333333166666666668
23333333333331666666666668
2333333333333316666666666668
233333333333333166666666666668
23333333333333331666666666666668
2333333333333333316666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668
2333333333333333333316666666666666666668
</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">threeor5: procedure options (main); /* 8 June 2014 */
declare (i, n) fixed(10), sum fixed (31) static initial (0);
 
Line 2,406 ⟶ 3,491:
put edit ( trim(sum) ) (A);
 
end threeor5;</langsyntaxhighlight>
Outputs:
<pre>
Line 2,415 ⟶ 3,500:
The number of multiples of 3 or 5 below 10000000 is 23333331666668
The number of multiples of 3 or 5 below 100000000 is 2333333316666668</pre>
 
==={{header|PL/I-80}}===
Although a brute-force approach gets the job done with a minimum
of fuss, and would generally be the preferred first choice, the use of Gauss's
summation formula will significantly speed up running time if
summing to higher limits than required by the problem. The solution
here demonstrates both approaches
<syntaxhighlight lang = "PL/I">
sum35_demo: proc options (main);
dcl limit fixed bin;
limit = 1000;
put skip list ('Sum of all multiples of 3 and 5 below', limit);
put skip edit ('Sum = ', sum35(limit)) ((a),(f(6)));
put skip edit ('Also: ', sum35alt(limit)) ((a),(f(6)));
 
stop;
 
sum35:
proc(limit) returns (float bin);
dcl
(limit, i) fixed bin,
sum float bin;
sum = 0;
do i=1 to (limit-1);
if mod(i,3) = 0 | mod(i,5) = 0 then
sum = sum + i;
end;
return (sum);
end sum35;
 
sum35alt:
proc(limit) returns (float bin);
dcl
limit fixed bin,
sum float bin;
sum = sum_of_multiples(3, limit) +
sum_of_multiples(5, limit) -
sum_of_multiples(15, limit);
return (sum);
end sum35alt;
 
sum_of_multiples:
proc(n, limit) returns (float bin);
dcl
(n, limit, i) fixed bin,
m float bin;
m = (limit - 1) / n;
return (n * m * (m + 1) / 2);
end sum_of_multiples;
 
end sum35_demo;
</syntaxhighlight>
{{out}}
<pre>
Sum of all multiples of 3 and 5 below 1000
Sum = 233168
Also: 233168
</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
function SumMultiples ( [int]$Base, [int]$Upto )
{
$X = ( $Upto - ( $Upto % $Base ) ) / $Base + ( [int] ( $Upto % $Base -ne 0 ) )
$Sum = ( $X * $X +- $X ) * $Base / 2
Return $Sum
}
Line 2,427 ⟶ 3,570:
# Calculate the sum of the multiples of 3 and 5 up to 1000
( SumMultiples -Base 3 -Upto 1000 ) + ( SumMultiples -Base 5 -Upto 1000 ) - ( SumMultiples -Base 15 -Upto 1000 )
</syntaxhighlight>
</lang>
{{out}}
<pre>
233168
234168
</pre>
SimplyFor arbitrarily large integers, simply change the variable type to handle really, really big number.
<langsyntaxhighlight lang="powershell">
function SumMultiples ( [bigint]$Base, [bigint]$Upto )
{
$X = ( $Upto - ( $Upto % $Base ) ) / $Base + ( [int] ( $Upto % $Base -ne 0 ) )
$Sum = ( $X * $X +- $X ) * $Base / 2
Return $Sum
}
Line 2,444 ⟶ 3,587:
$Upto = [bigint]::Pow( 10, 210 )
( SumMultiples -Base 3 -Upto $Upto ) + ( SumMultiples -Base 5 -Upto $Upto ) - ( SumMultiples -Base 15 -Upto $Upto )
</syntaxhighlight>
</lang>
{{out}}
<pre>
233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666668
233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333334166666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666668
</pre>
Here is a cmdlet that will provide the sum of unique multiples of any group of numbers below a given limit. I haven't attempted the extra credit here as the math is too complex for me at the moment.
<langsyntaxhighlight Powershelllang="powershell">function Get-SumOfMultiples
{
Param
Line 2,480 ⟶ 3,623:
}
$Sum
}</langsyntaxhighlight>
{{out}}
<pre>Get-SumOfMultiples</pre>
Line 2,490 ⟶ 3,633:
=={{header|Prolog}}==
===Slow version===
<langsyntaxhighlight Prologlang="prolog">sum_of_multiples_of_3_and_5_slow(N, TT) :-
sum_of_multiples_of_3_and_5(N, 1, 0, TT).
 
Line 2,506 ⟶ 3,649:
sum_of_multiples_of_3_and_5(N, K1, C5, S).
 
</syntaxhighlight>
</lang>
 
===Fast version===
<langsyntaxhighlight Pologlang="polog">sum_of_multiples_of_3_and_5_fast(N, TT):-
maplist(compute_sum(N), [3,5,15], [TT3, TT5, TT15]),
TT is TT3 + TT5 - TT15.
Line 2,518 ⟶ 3,661:
; N2 is N div N1),
Sum is N1 * N2 * (N2 + 1) / 2.
</syntaxhighlight>
</lang>
 
Output :
Line 2,529 ⟶ 3,672:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
 
Line 2,550 ⟶ 3,693:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,559 ⟶ 3,702:
=={{header|Python}}==
Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()
<langsyntaxhighlight lang="python">def sum35a(n):
'Direct count'
# note: ranges go to n-1
Line 2,590 ⟶ 3,733:
# Scalability
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))</langsyntaxhighlight>
 
{{out}}
Line 2,608 ⟶ 3,751:
Or, more generally – taking the area under the straight line between the first multiple and the last:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Summed multiples of 3 and 5 up to n'''
 
 
Line 2,678 ⟶ 3,821:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Summed multiples of 3 and 5 up to n:
Line 2,697 ⟶ 3,840:
 
=={{header|Q}}==
<langsyntaxhighlight lang="q">s35:{sum {?[(0=x mod 3) | 0=x mod 5;x;0]} each 1+til x - 1}
s35 each 10 100 1000 10000 1000000</langsyntaxhighlight>
 
Extra credit, using the summation formula:
 
<langsyntaxhighlight lang="q">sn:{x*(x+1)%2} / Sum of 1 to n
s35:{a:x-1; (3*sn floor a%3) + (5*sn floor a%5) - (15*sn floor a%15)}
s35 e+10</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ dup 1+ * 2 / ] is triangulared ( n --> n )
[ 1 -
dup 3 / triangulared 3 *
over 5 / triangulared 5 * +
swap 15 / triangulared 15 * - ] is sum-of-3s&5s ( n --> n )
1000 sum-of-3s&5s echo cr
10 20 ** sum-of-3s&5s echo cr</syntaxhighlight>
 
{{out}}
 
<pre>233168
2333333333333333333316666666666666666668
</pre>
 
=={{header|R}}==
 
<langsyntaxhighlight lang="rsplus">m35 = function(n) sum(unique(c(
seq(3, n-1, by = 3), seq(5, n-1, by = 5))))
m35(1000) # 233168</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,740 ⟶ 3,902:
 
(for/list ([k 20]) (analytical k))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
'(0 23 2318 233168 23331668 2333316668 233333166668)
'(0
Line 2,764 ⟶ 3,926:
233333333333333333166666666666666668
23333333333333333331666666666666666668)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub sum35($n) { [+] grep * %% (3|5), ^$n; }
 
say sum35 1000;</syntaxhighlight>
{{out}}
<pre>233168</pre>
Here's an analytical approach that scales much better for large values.
<syntaxhighlight lang="raku" line>sub sum-mults($first, $limit) {
(my $last = $limit - 1) -= $last % $first;
($last div $first) * ($first + $last) div 2;
}
 
sub sum35(\n) {
sum-mults(3,n) + sum-mults(5,n) - sum-mults(15,n);
}
 
say sum35($_) for 1,10,100...10**30;</syntaxhighlight>
{{out}}
<pre>0
23
2318
233168
23331668
2333316668
233333166668
23333331666668
2333333316666668
233333333166666668
23333333331666666668
2333333333316666666668
233333333333166666666668
23333333333331666666666668
2333333333333316666666666668
233333333333333166666666666668
23333333333333331666666666666668
2333333333333333316666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668
2333333333333333333316666666666666666668
233333333333333333333166666666666666666668
23333333333333333333331666666666666666666668
2333333333333333333333316666666666666666666668
233333333333333333333333166666666666666666666668
23333333333333333333333331666666666666666666666668
2333333333333333333333333316666666666666666666666668
233333333333333333333333333166666666666666666666666668
23333333333333333333333333331666666666666666666666666668
2333333333333333333333333333316666666666666666666666666668
233333333333333333333333333333166666666666666666666666666668</pre>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 14.05.2013 Walter Pachl
**********************************************************************/
Line 2,779 ⟶ 3,992:
s=s+i
End
Return s</langsyntaxhighlight>
Output:
<pre>233168</pre>
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Translation from Perl6Raku->NetRexx->REXX
* 15.05.2013 Walter Pachl
**********************************************************************/
Line 2,807 ⟶ 4,020:
last = last - last // first
sum = (last % first) * (first + last) % 2
return sum</langsyntaxhighlight>
Output:
<pre> 1 0
Line 2,843 ⟶ 4,056:
 
===version 3===
This version automatically adjusts the numeric digits. and&nbsp; aA little extra code was added to format the output nicely.
 
The formula used is a form of the Gauss Summation formula.
<langsyntaxhighlight lang="rexx">/*REXX program counts all integers from 1 ──► N─1 that are multiples of 3 or 5. */
parse arg N t . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=1000 1000 /*Not specified? Then use the default.*/
if t=='' | t=="," then t= 1 1 /* " " " " " " */
numeric digits 1000; w= 2 + length(t) /*W: used for formatting 'e' part of Y.*/
say 'The sum of all positive integers that are a multiple of 3 and 5 are:'
say /* [↓] change the format/look of nE+nn*/
do t; parse value format(N,2,1,,0) 'E0' with m 'E' _ . /*get the exponent.*/
y= right( (m/1)'e' || (_+0), w)"-1" /*this fixes a bug in a certain REXX. */
z= n - 1; if t==1 then y=z z /*handle a special case of a one─timer.*/
say 'integers from 1 ──►' y " is " sumDiv(z,3) + sumDiv(z,5) - sumDiv(z,3*5)
N= N'0' /*fast *10 multiply for next iteration.*/
end /*t*/ /* [↑] simply append a zero to the num*/
end /*t*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDiv: procedure; parse arg x,d; $= x % d; return d * $ * ($+1) % 2</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the default input:}}
<pre>
The sum of all positive integers that are a multiple of 3 and 5 are:
Line 2,868 ⟶ 4,081:
integers from 1 ──► 999 is 233168
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 1 &nbsp; 85 </tt>}}
 
<pre style="height:80ex">
(Shown at three-quarter size.)
 
<pre style="font-size:75%;height:188ex">
The sum of all positive integers that are a multiple of 3 and 5 are:
 
Line 2,960 ⟶ 4,176:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see sum35(1000) + nl
Line 2,971 ⟶ 4,187:
func tri n
return n * (n + 1) / 2
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
===Simple solution===
Just counting...
≪ 0 1 DO
1 +
IF DUP 3 MOD NOT OVER 5 MOD NOT OR THEN SWAP OVER + SWAP END
UNTIL DUP 4 PICK == END
ROT DROP2
===Efficient solution===
This is a fast approach to calculate the sum for higher values of n, taking into account that:
# the sum of multiples of 3 and 5 is the sum of multiples of 3 plus the sum of multiples of 5, minus the sum of multiples of 15 to remove double counting
# the sum of multiples of m being < n is equal to m*(1+2+ ... k) with k =[n/m]
# 1+2+...k = k*(k+1)/2
Unfortunately, RPL can only handle double precision numbers, which prevents from precisely calculating the sum for n > 1E+15
≪ → n
≪ 0 1 3 FOR j
{ 3 5 -15 } j GET
n OVER / ABS IP
DUP 1 + * 2 / * +
NEXT
≫ ≫
‘SUM35’ STO
 
999 SUM35
{{out}}
<pre>
1: 233168
</pre>
 
=={{header|Ruby}}==
Simple Version (Slow):
<langsyntaxhighlight lang="ruby">def sum35(n)
(1...n).select{|i|i%3==0 or i%5==0}.inject(:+)sum
end
puts sum35(1000) #=> 233168</langsyntaxhighlight>
 
Fast Version:
<langsyntaxhighlight lang="ruby"># Given two integers n1,n2 return sum of multiples upto n3
#
# Nigel_Galloway
Line 2,993 ⟶ 4,240:
 
# For extra credit
puts g(3,5,100000000000000000000-1)</langsyntaxhighlight>
 
{{out}}
Line 3,003 ⟶ 4,250:
Other way:
{{trans|D}}
<langsyntaxhighlight lang="ruby">def sumMul(n, f)
n1 = (n - 1) / f
f * n1 * (n1 + 1) / 2
Line 3,014 ⟶ 4,261:
for i in 1..20
puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)]
end</langsyntaxhighlight>
 
{{out}}
Line 3,041 ⟶ 4,288:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print multSum35(1000)
end
function multSum35(n)
Line 3,047 ⟶ 4,294:
If (i mod 3 = 0) or (i mod 5 = 0) then multSum35 = multSum35 + i
next i
end function</langsyntaxhighlight><pre>233168</pre>
 
=={{header|Scala}}==
<lang scala>def sum35( max:BigInt ) : BigInt = max match {
 
// Simplest solution but limited to Ints only
case j if j < 100000 => (1 until j.toInt).filter( i => i % 3 == 0 || i % 5 == 0 ).sum
// Using a custom iterator that takes Longs
case j if j < 10e9.toLong => {
def stepBy( step:Long ) : Iterator[Long] = new Iterator[Long] { private var i = step; def hasNext = true; def next() : Long = { val result = i; i = i + step; result } }
stepBy(3).takeWhile( _< j ).sum + stepBy(5).takeWhile( _< j ).sum - stepBy(15).takeWhile( _< j ).sum
}
// Using the formula for a Triangular number
case j => {
def triangle( i:BigInt ) = i * (i+1) / BigInt(2)
3 * triangle( (j-1)/3 ) + 5 * triangle( (j-1)/5 ) - 15 * triangle( (j-1)/15 )
}
}
 
{
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
}</lang>
{{out}}
<pre> 1 => 0
10 => 23
100 => 2318
1000 => 233168
10000 => 23331668
100000 => 2333316668
1000000 => 233333166668
10000000 => 23333331666668
100000000 => 2333333316666668
1000000000 => 233333333166666668
10000000000 => 23333333331666666668
100000000000 => 2333333333316666666668
1000000000000 => 233333333333166666666668
10000000000000 => 23333333333331666666666668
100000000000000 => 2333333333333316666666666668
1000000000000000 => 233333333333333166666666666668
10000000000000000 => 23333333333333331666666666666668
100000000000000000 => 2333333333333333316666666666666668
1000000000000000000 => 233333333333333333166666666666666668
10000000000000000000 => 23333333333333333331666666666666666668
100000000000000000000 => 2333333333333333333316666666666666666668</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
extern crate rug;
 
Line 3,132 ⟶ 4,334:
}
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 3,146 ⟶ 4,348:
</pre>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang="basic">
rem - return n mod m
function mod(n, m = integer) = integer
end = n - m * (n / m)
 
var i, limit = integer
var sum = real
 
limit = 1000
sum = 0
for i = 1 to limit-1
if (mod(i,3) = 0) or (mod(i, 5) = 0) then
sum = sum + i
next i
print using "Sum = #######"; sum
 
end
</syntaxhighlight>
{{out}}
<pre>
Sum = 233168
</pre>
 
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">def sum35( max:BigInt ) : BigInt = max match {
 
// Simplest solution but limited to Ints only
case j if j < 100000 => (1 until j.toInt).filter( i => i % 3 == 0 || i % 5 == 0 ).sum
// Using a custom iterator that takes Longs
case j if j < 10e9.toLong => {
def stepBy( step:Long ) : Iterator[Long] = new Iterator[Long] { private var i = step; def hasNext = true; def next() : Long = { val result = i; i = i + step; result } }
stepBy(3).takeWhile( _< j ).sum + stepBy(5).takeWhile( _< j ).sum - stepBy(15).takeWhile( _< j ).sum
}
// Using the formula for a Triangular number
case j => {
def triangle( i:BigInt ) = i * (i+1) / BigInt(2)
3 * triangle( (j-1)/3 ) + 5 * triangle( (j-1)/5 ) - 15 * triangle( (j-1)/15 )
}
}
 
{
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
}</syntaxhighlight>
{{out}}
<pre> 1 => 0
10 => 23
100 => 2318
1000 => 233168
10000 => 23331668
100000 => 2333316668
1000000 => 233333166668
10000000 => 23333331666668
100000000 => 2333333316666668
1000000000 => 233333333166666668
10000000000 => 23333333331666666668
100000000000 => 2333333333316666666668
1000000000000 => 233333333333166666666668
10000000000000 => 23333333333331666666666668
100000000000000 => 2333333333333316666666666668
1000000000000000 => 233333333333333166666666666668
10000000000000000 => 23333333333333331666666666666668
100000000000000000 => 2333333333333333316666666666666668
1000000000000000000 => 233333333333333333166666666666666668
10000000000000000000 => 23333333333333333331666666666666666668
100000000000000000000 => 2333333333333333333316666666666666666668</pre>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000))</langsyntaxhighlight>
 
Output:
Line 3,157 ⟶ 4,428:
Or, more clearly by decomposition:
 
<langsyntaxhighlight lang="scheme">(define (fac35? x)
(or (zero? (remainder x 3))
(zero? (remainder x 5))))
Line 3,164 ⟶ 4,435:
(+ tot (if (fac35? x) x 0)))
 
(fold fac35filt 0 (iota 1000))</langsyntaxhighlight>
 
Output:
Line 3,173 ⟶ 4,444:
For larger numbers iota can take quite a while just to build the list -- forget about waiting for all the computation to finish!
 
<langsyntaxhighlight lang="scheme">(define (trisum n fac)
(let* ((n1 (quotient (- n 1) fac))
(n2 (+ n1 1)))
Line 3,183 ⟶ 4,454:
(fast35sum 1000)
(fast35sum 100000000000000000000)
</syntaxhighlight>
</lang>
 
Output:
Line 3,192 ⟶ 4,463:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 3,216 ⟶ 4,487:
writeln(sum35(1000_));
writeln(sum35(10_ ** 20));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,226 ⟶ 4,497:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func sumMul(n, f) {
var m = int((n - 1) / f)
f * m * (m + 1) / 2
Line 3,237 ⟶ 4,508:
for i in (1..20) {
printf("%2s:%22s %s\n", i, 10**i, sum35(10**i))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,264 ⟶ 4,535:
=={{header|Simula}}==
(referenced from [[Greatest common divisor#Simula|Greatest common divisor]])
<langsyntaxhighlight lang="algol68">! Find the sum of multiples of two factors below a limit -
! Project Euler problem 1: multiples of 3 or 5 below 1000 & 10**20;
BEGIN
Line 3,317 ⟶ 4,588:
OUTIMAGE
END
END</langsyntaxhighlight>
{{out}}
sum of positive multiples of 3 and 5: 233168<br />
Line 3,330 ⟶ 4,601:
=={{header|Stata}}==
=== With a dataset ===
<langsyntaxhighlight lang="stata">clear all
set obs 999
gen a=_n
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)</langsyntaxhighlight>
 
=== With Mata ===
<langsyntaxhighlight lang="stata">mata
a=1..999
sum(a:*(mod(a,3):==0 :| mod(a,5):==0))</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
 
 
Line 3,362 ⟶ 4,633:
print(sumofmult)
 
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># Fairly simple version; only counts by 3 and 5, skipping intermediates
proc mul35sum {n} {
for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} {
Line 3,381 ⟶ 4,652:
}
return $total
}</langsyntaxhighlight>
However, that's pretty dumb. We can do much better by observing that the sum of the multiples of <math>k</math> below some <math>n+1</math> is <math>k T_{n/k}</math>, where <math>T_i</math> is the <math>i</math>'th [[wp:Triangular number|triangular number]], for which there exists a trivial formula. Then we simply use an overall formula of <math>3T_{n/3} + 5T_{n/5} - 15T_{n/15}</math> (that is, summing the multiples of three and the multiples of five, and then subtracting the multiples of 15 which were double-counted).
<langsyntaxhighlight lang="tcl"># Smart version; no iteration so very scalable!
proc tcl::mathfunc::triangle {n} {expr {
$n * ($n+1) / 2
Line 3,391 ⟶ 4,662:
incr n -1
expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts [mul35sum 1000],[sum35 1000]
puts [mul35sum 10000000],[sum35 10000000]
# Just the quick one; waiting for the other would get old quickly...
puts [sum35 100000000000000000000]</langsyntaxhighlight>
{{out}}
<pre>233168,233168
Line 3,403 ⟶ 4,674:
</pre>
 
=={{header|TI SR-56}}==
=== Iterative solution ===
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Sum Multiples" (Iterative)
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 33 || STO || 50 || || 75 ||
|-
| 01 04 || 4 || 26 00 || 0 || 51 || || 76 ||
|-
| 02 04 || 4 || 27 57 || *subr || 52 || || 77 ||
|-
| 03 52 || ( || 28 00 || 0 || 53 || || 78 ||
|-
| 04 52 || ( || 29 03 || 3 || 54 || || 79 ||
|-
| 05 34 || RCL || 30 12 || INV || 55 || || 80 ||
|-
| 06 00 || 0 || 31 37 || *x=t || 56 || || 81 ||
|-
| 07 54 || / || 32 03 || 3 || 57 || || 82 ||
|-
| 08 05 || 5 || 33 08 || 8 || 58 || || 83 ||
|-
| 09 53 || ) || 34 34 || RCL || 59 || || 84 ||
|-
| 10 12 || INV || 35 00 || 0 || 60 || || 85 ||
|-
| 11 29 || *Int || 36 35 || SUM || 61 || || 86 ||
|-
| 12 64 || x || 37 01 || 1 || 62 || || 87 ||
|-
| 13 52 || ( || 38 27 || *dsz || 63 || || 88 ||
|-
| 14 34 || RCL || 39 02 || 2 || 64 || || 89 ||
|-
| 15 00 || 0 || 40 07 || 7 || 65 || || 90 ||
|-
| 16 54 || / || 41 34 || RCL || 66 || || 91 ||
|-
| 17 03 || 3 || 42 01 || 1 || 67 || || 92 ||
|-
| 18 53 || ) || 43 41 || R/S || 68 || || 93 ||
|-
| 19 12 || INV || 44 74 || - || 69 || || 94 ||
|-
| 20 29 || *Int || 45 01 || 1 || 70 || || 95 ||
|-
| 21 53 || ) || 46 94 || = || 71 || || 96 ||
|-
| 22 58 || *rtn || 47 22 || GTO || 72 || || 97 ||
|-
| 23 56 || *CP || 48 02 || 2 || 73 || || 98 ||
|-
| 24 38 || *CMs || 49 03 || 3 || 74 || || 99 ||
|}
 
Asterisk denotes 2nd function key.
 
{| class="wikitable"
|+ Register allocation
|-
| 0: Current Term || 1: Sum Of Terms || 2: Unused || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
 
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point.
GTO 4 4
 
// Address 03: Subroutine
// If R0 is divisible by 3 and 5, return 0, else nonzero
( ( RCL 0 / 5 ) INV *Int x ( RCL 0 / 3 ) INV *Int ) *rtn
 
// Address 23: Main program
*CP *CMs // Zero all registers and T register.
STO 0 // R0 := Maximum number to consider.
*subr 0 3 // Check divisibility by 3 and 5.
INV *x=t 3 8 // Divisible?
RCL 0
SUM 1 // R1 += R0
*dsz 2 7 // R0--, repeat while nonzero.
RCL 1 // Retrieve answer.
R/S // End.
 
// Address 44: Input parsing
- 1 = // Consider all numbers *less than* N.
GTO 2 3
</syntaxhighlight>
 
'''Usage:'''
 
{{in}}
 
<pre>1000 RST R/S</pre>
 
{{out}}
 
<pre>233168</pre>
 
This took between 20 and 30 minutes to run.
 
=== Efficient closed-form solution ===
 
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Sum Multiples" (Closed-form)
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 29 || *Int || 50 54 || / || 75 ||
|-
| 01 01 || 1 || 26 57 || *subr || 51 01 || 1 || 76 ||
|-
| 02 06 || 6 || 27 00 || 0 || 52 05 || 5 || 77 ||
|-
| 03 33 || STO || 28 03 || 3 || 53 94 || = || 78 ||
|-
| 04 01 || 1 || 29 64 || x || 54 29 || *Int || 79 ||
|-
| 05 54 || / || 30 05 || 5 || 55 57 || *subr || 80 ||
|-
| 06 02 || 2 || 31 94 || = || 56 00 || 0 || 81 ||
|-
| 07 64 || x || 32 35 || SUM || 57 03 || 3 || 82 ||
|-
| 08 52 || ( || 33 02 || 2 || 58 64 || x || 83 ||
|-
| 09 34 || RCL || 34 34 || RCL || 59 01 || 1 || 84 ||
|-
| 10 01 || 1 || 35 00 || 0 || 60 05 || 5 || 85 ||
|-
| 11 84 || + || 36 54 || / || 61 94 || = || 86 ||
|-
| 12 01 || 1 || 37 03 || 3 || 62 12 || INV || 87 ||
|-
| 13 53 || ) || 38 94 || = || 63 35 || SUM || 88 ||
|-
| 14 53 || ) || 39 29 || *Int || 64 02 || 2 || 89 ||
|-
| 15 58 || *rtn || 40 57 || *subr || 65 34 || RCL || 90 ||
|-
| 16 38 || *CMs || 41 00 || 0 || 66 02 || 2 || 91 ||
|-
| 17 74 || - || 42 03 || 3 || 67 41 || R/S || 92 ||
|-
| 18 01 || 1 || 43 64 || x || 68 || || 93 ||
|-
| 19 94 || = || 44 03 || 3 || 69 || || 94 ||
|-
| 20 33 || STO || 45 94 || = || 70 || || 95 ||
|-
| 21 00 || 0 || 46 35 || SUM || 71 || || 96 ||
|-
| 22 54 || / || 47 02 || 2 || 72 || || 97 ||
|-
| 23 05 || 5 || 48 34 || RCL || 73 || || 98 ||
|-
| 24 94 || = || 49 00 || 0 || 74 || || 99 ||
|}
 
Asterisk denotes 2nd function key.
 
{| class="wikitable"
|+ Register allocation
|-
| 0: Maximum Term || 1: Parameter || 2: Answer || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
 
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point.
GTO 1 6
 
// Address 03: Subroutine
// Calculates sum of nums 1-N as (N/2)(N+1).
STO 1
/ 2 x ( RCL 1 + 1 ) ) *rtn
 
// Address 16: Main program
*CMs // Clear registers.
- 1 = STO 0 // R0 := N-1
/ 5 = *Int *subr 0 3 x 5 = SUM 2 // R2 += fives
RCL 0 / 3 = *Int *subr 0 3 x 3 = SUM 2 // R2 += threes
RCL 0 / 1 5 = *Int *subr 0 3 x 1 5 = INV SUM 2 // R2 -= fifteens
RCL 2 // Retrieve answer.
R/S // End.
</syntaxhighlight>
 
'''Usage:'''
 
{{in}}
 
<pre>1000 RST R/S</pre>
 
{{out}}
 
<pre>233168</pre>
 
Completed in 4 seconds.
 
{{in}}
 
<pre>1 EE 20 RST R/S</pre>
 
{{out}}
 
<pre>2.333333333 39</pre>
 
Completed in 4 seconds.
 
=={{header|Uiua}}==
<syntaxhighlight>
End ← 1000
 
MultOfthree ← ⊚=0◿3 # indices where divisible by 3
Indicesthree ← MultOfthree ↘1⇡End
MultOffive ← ⊚=0◿5 # indices where divisible by 5
IndicesFive ← MultOffive ↘1⇡End
 
/+ ⊏⊂ Indicesthree IndicesFive ↘1⇡End # join, select and sum
</syntaxhighlight>
{{out}}
233168
</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
Only works up to 1000000000 due to limits of shell integer representation.
 
<syntaxhighlight lang="sh">function sum_multiples {
typeset -i n=$1 limit=$2
typeset -i max=limit-1
(( max -= max % n ))
printf '%d\n' $(( max / n * (n+max)/2 ))
}
 
function sum35 {
typeset -i limit=$1
printf '%d\n' $(( $(sum_multiples 3 $limit)
+ $(sum_multiples 5 $limit)
- $(sum_multiples 15 $limit) ))
}
 
for (( l=1; l<=1000000000; l*=10 )); do
printf '%10d\t%18d\n' "$l" "$(sum35 "$l")"
done</syntaxhighlight>
 
{{Out}}
<pre> 1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668</pre>
=={{header|VBA}}==
{{trans|VBScript}}
<langsyntaxhighlight lang="vb">Private Function SumMult3and5VBScript(n As Double) As Double
Dim i As Double
For i = 1 To n - 1
Line 3,412 ⟶ 4,948:
End If
Next
End Function</langsyntaxhighlight>
Other way :
<langsyntaxhighlight lang="vb">Private Function SumMult3and5(n As Double) As Double
Dim i As Double
For i = 3 To n - 1 Step 3
Line 3,422 ⟶ 4,958:
If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
Next
End Function</langsyntaxhighlight>
Better way :
<langsyntaxhighlight lang="vb">Private Function SumMult3and5BETTER(n As Double) As Double
Dim i As Double
For i = 3 To n - 1 Step 3
Line 3,435 ⟶ 4,971:
SumMult3and5BETTER = SumMult3and5BETTER - i
Next
End Function</langsyntaxhighlight>
 
Call :
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 3,450 ⟶ 4,986:
Debug.Print "-------------------------"
Debug.Print SumMult3and5BETTER(1000)
End Sub</langsyntaxhighlight>
{{Out}}
<pre>2,33333331666667E+15 9,059 sec.
Line 3,461 ⟶ 4,997:
=={{header|VBScript}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function multsum35(n)
For i = 1 To n - 1
Line 3,472 ⟶ 5,008:
WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
<pre>
F:\>cscript /nologo multsum35.vbs 1000
233168
</pre>
 
 
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">module main;
integer i, suma;
initial begin
suma = 0;
for(i = 1; i <= 999; i=i+1)
begin
if(i % 3 == 0) suma = suma + i;
else if(i % 5 == 0) suma = suma + i;
end
$display(suma);
$finish ;
end
endmodule</syntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="go">fn s35(n int) int {
mut nn := n-1
mut threes := nn/3
mut fives := nn/5
mut fifteen := nn/15
 
threes = 3 * threes * (threes + 1)
fives = 5 * fives * (fives + 1)
fifteen = 15 * fifteen * (fifteen + 1)
 
nn = (threes + fives - fifteen) / 2
return nn
}
 
fn main(){
println(s35(1000))
}</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
sum35 ^(@sum \!-@(\~%%3 || \~%%5) @til)
!sum35 1000 ; returns 233168
}</langsyntaxhighlight>
 
=={{header|Wren}}==
===Simple version===
<syntaxhighlight lang="wren">var sum35 = Fn.new { |n|
n = n - 1
var s3 = (n/3).floor
var s5 = (n/5).floor
var s15 = (n/15).floor
s3 = 3 * s3 * (s3+1)
s5 = 5 * s5 * (s5+1)
s15 = 15 * s15 * (s15+1)
return (s3 + s5 - s15)/2
}
 
System.print(sum35.call(1000))</syntaxhighlight>
 
{{out}}
<pre>
233168
</pre>
<br>
===Fast version with arbitrary precision===
{{trans|C}}
{{libheader|Wren-gmp}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./gmp" for Mpz
import "./fmt" for Fmt
 
var sumMultiples = Fn.new { |result, limit, f|
var m = Mpz.from(limit).sub(1).fdiv(f)
result.set(m).inc.mul(m).mul(f).rsh(1)
}
 
var limit = Mpz.one
var tempSum = Mpz.new()
var sum35 = Mpz.new()
var max = 25
Fmt.print("$*s $s", max + 1, "limit", "sum")
for (i in 0..max) {
Fmt.write("$*s ", max + 1, limit)
sumMultiples.call(tempSum, limit, 3)
sum35.set(tempSum)
sumMultiples.call(tempSum, limit, 5)
sum35.add(tempSum)
sumMultiples.call(tempSum, limit, 15)
sum35.sub(tempSum)
System.print(sum35)
limit.mul(10)
}</syntaxhighlight>
 
{{out}}
<pre>
limit sum
1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668
10000000000 23333333331666666668
100000000000 2333333333316666666668
1000000000000 233333333333166666666668
10000000000000 23333333333331666666666668
100000000000000 2333333333333316666666666668
1000000000000000 233333333333333166666666666668
10000000000000000 23333333333333331666666666666668
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668
10000000000000000000 23333333333333333331666666666666666668
100000000000000000000 2333333333333333333316666666666666666668
1000000000000000000000 233333333333333333333166666666666666666668
10000000000000000000000 23333333333333333333331666666666666666666668
100000000000000000000000 2333333333333333333333316666666666666666666668
1000000000000000000000000 233333333333333333333333166666666666666666666668
10000000000000000000000000 23333333333333333333333331666666666666666666666668
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func Sum1; \Return sum the straightforward way
Line 3,529 ⟶ 5,187:
StrNSub(S, T, 40);
TextN(0, T, 40); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,538 ⟶ 5,196:
</pre>
 
=={{header|Zig}}==
Note that solving for 1e20 requires numbers > 128 bits. However, Zig supports fixed size integers up to 65,556 bits, and with Zig, it's possible to figure out at compile-time what the maximum width of an integer should be at run-time.
<syntaxhighlight lang="zig">
const std = @import("std");
 
fn DoubleWide(comptime n: anytype) type {
const Signedness = std.builtin.Signedness;
switch (@typeInfo(@TypeOf(n))) {
.Int => |t|
return std.meta.Int(t.signedness, t.bits * 2),
.ComptimeInt => {
const sz = @as(u16, @intFromFloat(@log2(@as(f64, @floatFromInt(n))))) + 1;
return std.meta.Int(Signedness.signed, sz * 2);
},
else =>
@compileError("must have integral type for DoubleWide")
}
}
 
fn sumdiv(n: anytype, d: anytype) DoubleWide(n) {
var m: DoubleWide(n) = @divFloor(n, d);
return @divExact(m * (m + 1), 2) * d;
}
 
fn sum3or5(n: anytype) DoubleWide(n) {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}
 
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
 
var s: usize = 0;
for (1..1000) |n| {
if (n % 3 == 0 or n % 5 == 0)
s += n;
}
try stdout.print("The sum of the multiples of 3 and 5 below 1000 is {}\n", .{s});
try stdout.print("The sum of the multiples of 3 and 5 below 1e20 is {}\n", .{sum3or5(99_999_999_999_999_999_999)});
}
 
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1e20 is 2333333333333333333316666666666666666668
 
</pre>
=={{header|zkl}}==
Brute force:
<langsyntaxhighlight lang="zkl">[3..999,3].reduce('+,0) + [5..999,5].reduce('+,0) - [15..999,15].reduce('+,0)
233168</langsyntaxhighlight>
{{trans|Groovy}}
Using a formula, making sure the input will cast the result to the same type (ie if called with a BigNum, the result is a BigNum).
<langsyntaxhighlight lang="zkl">fcn sumMul(N,m){N=(N-1)/m; N*(N+1)*m/2}
fcn sum35(N){sumMul(N,3) + sumMul(N,5) - sumMul(N,15)}</langsyntaxhighlight>
{{out}}
<pre>
2

edits