Sum multiples of 3 and 5: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added solution for Action!)
 
(40 intermediate revisions by 18 users not shown)
Line 12: Line 12:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F sum35(limit)
<syntaxhighlight lang="11l">F sum35(limit)
V sum = 0
V sum = 0
L(i) 1 .< limit
L(i) 1 .< limit
Line 19: Line 19:
R sum
R sum


print(sum35(1000))</lang>
print(sum35(1000))</syntaxhighlight>


{{out}}
{{out}}
Line 26: Line 26:
</pre>
</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}}==
=={{header|360 Assembly}}==
<lang 360asm>* Sum multiples of 3 and 5
<syntaxhighlight lang="360asm">* Sum multiples of 3 and 5
SUM35 CSECT
SUM35 CSECT
USING SUM35,R13 base register
USING SUM35,R13 base register
Line 72: Line 103:
PG DC CL80'123456789012 : 1234567890123456'
PG DC CL80'123456789012 : 1234567890123456'
YREGS
YREGS
END SUM35</lang>
END SUM35</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 86: Line 117:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


PROC Main()
PROC Main()
Line 103: Line 134:


PrintRE(sum)
PrintRE(sum)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_multiples_of_3_and_5.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_multiples_of_3_and_5.png Screenshot from Atari 8-bit computer]
Line 111: Line 142:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Sum_Multiples is
procedure Sum_Multiples is
Line 131: Line 162:
Ada.Text_IO.Put_Line ("n=1000: " & Sum_3_5 (1000)'Image);
Ada.Text_IO.Put_Line ("n=1000: " & Sum_3_5 (1000)'Image);
Ada.Text_IO.Put_Line ("n=5e9 : " & Sum_3_5 (5e9)'Image);
Ada.Text_IO.Put_Line ("n=5e9 : " & Sum_3_5 (5e9)'Image);
end Sum_Multiples;</lang>
end Sum_Multiples;</syntaxhighlight>
{{out}}
{{out}}
<pre>n=1000: 233168
<pre>n=1000: 233168
Line 138: Line 169:
===Extra Credit===
===Extra Credit===
Requires upcoming Ada 202x with big integer package.
Requires upcoming Ada 202x with big integer package.
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Numerics.Big_Numbers.Big_Integers;


Line 176: Line 207:
end;
end;
end loop;
end loop;
end Sum_Multiples_Big;</lang>
end Sum_Multiples_Big;</syntaxhighlight>
{{out}}
{{out}}
<pre> n : Sum_35 (n)
<pre> n : Sum_35 (n)
Line 211: Line 242:
100000000000000000000000000000 : 2333333333333333333333333333316666666666666666666666666668
100000000000000000000000000000 : 2333333333333333333333333333316666666666666666666666666668
1000000000000000000000000000000 : 233333333333333333333333333333166666666666666666666666666668</pre>
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>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT to handle large numbers.
Uses Algol 68G's LONG LONG INT to handle large numbers.
<lang algol68># returns the sum of the multiples of 3 and 5 below n #
<syntaxhighlight 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:
PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT:
BEGIN
BEGIN
Line 240: Line 300:
, newline
, newline
)
)
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 249: Line 309:
=={{header|APL}}==
=={{header|APL}}==
=== Dyalog APL ===
=== Dyalog APL ===
<lang apl>
<syntaxhighlight lang="apl">
Sum ← +/∘⍸1<15∨⍳
Sum ← +/∘⍸1<15∨⍳
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> Sum 999
<pre> Sum 999
Line 257: Line 317:


=== ngn/APL ===
=== ngn/APL ===
<lang apl>⎕IO←0
<syntaxhighlight lang="apl">⎕IO←0
{+/((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]
{+/((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}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>
Line 264: Line 324:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|JavaScript}}
<lang AppleScript>----------------- SUM MULTIPLES OF 3 AND 5 -----------------
<syntaxhighlight lang="applescript">----------------- SUM MULTIPLES OF 3 AND 5 -----------------


-- sum35 :: Int -> Int
-- sum35 :: Int -> Int
Line 341: Line 401:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{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>
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>
Line 347: Line 407:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>sumMul35: function [n][
<syntaxhighlight lang="rebol">sumMul35: function [n][
sum select 1..n-1 [x][or? 0=x%3 0=x%5]
sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]
]


print sumMul35 1000</lang>
print sumMul35 1000</syntaxhighlight>


{{out}}
{{out}}
Line 359: Line 419:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


<lang AutoHotkey>n := 1000
<syntaxhighlight lang="autohotkey">n := 1000


msgbox % "Sum is " . Sum3_5(n) . " for n = " . n
msgbox % "Sum is " . Sum3_5(n) . " for n = " . n
Line 393: Line 453:
}
}
return sum
return sum
}</lang>
}</syntaxhighlight>
'''Output:''' <pre>Sum is 233168 for n = 1000
'''Output:''' <pre>Sum is 233168 for n = 1000
Sum is 233168 for n = 1000</pre>
Sum is 233168 for n = 1000</pre>
Line 399: Line 459:
=={{header|AWK}}==
=={{header|AWK}}==
Save this into file "sum_multiples_of3and5.awk"
Save this into file "sum_multiples_of3and5.awk"
<lang AWK>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
{
{
n = $1-1;
n = $1-1;
Line 407: Line 467:
m = int(n/d);
m = int(n/d);
return (d*m*(m+1)/2);
return (d*m*(m+1)/2);
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 423: Line 483:
=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
<lang freebasic>Declare function mulsum35(n as integer) as integer
<syntaxhighlight lang="freebasic">Declare function mulsum35(n as integer) as integer
Function mulsum35(n as integer) as integer
Function mulsum35(n as integer) as integer
Dim s as integer
Dim s as integer
Line 435: Line 495:
Print mulsum35(1000)
Print mulsum35(1000)
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<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}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PRINT MULTSUM35(1000)
<syntaxhighlight lang="is-basic">100 PRINT MULTSUM35(1000)
110 DEF MULTSUM35(N)
110 DEF MULTSUM35(N)
120 LET S=0
120 LET S=0
Line 447: Line 636:
150 NEXT
150 NEXT
160 LET MULTSUM35=S
160 LET MULTSUM35=S
170 END DEF</lang>
170 END DEF</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Line 453: Line 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.
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.
<lang basic> 10 INPUT N
<syntaxhighlight lang="basic"> 10 INPUT N
20 FAST
20 FAST
30 LET SUM=0
30 LET SUM=0
Line 462: Line 651:
80 NEXT I
80 NEXT I
90 SLOW
90 SLOW
100 PRINT SUM</lang>
100 PRINT SUM</syntaxhighlight>
{{in}}
{{in}}
<pre>1000</pre>
<pre>1000</pre>
Line 470: Line 659:
=={{header|bc}}==
=={{header|bc}}==
{{trans|Groovy}}
{{trans|Groovy}}
<lang bc>define t(n, f) {
<syntaxhighlight lang="bc">define t(n, f) {
auto m
auto m


Line 482: Line 671:


s(1000)
s(1000)
s(10 ^ 20)</lang>
s(10 ^ 20)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>233168
<pre>233168
Line 489: Line 678:
=={{header|BCPL}}==
=={{header|BCPL}}==
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.
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">
<lang BCPL>
GET "libhdr"
GET "libhdr"


Line 515: Line 704:
RESULTIS 0
RESULTIS 0
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 534: Line 723:
=={{header|Befunge}}==
=={{header|Befunge}}==
Slow (iterative) version:
Slow (iterative) version:
<lang Befunge>&1-:!#v_:3%#v_ >:>#
<syntaxhighlight lang="befunge">&1-:!#v_:3%#v_ >:>#
>+\:v >:5%#v_^
>+\:v >:5%#v_^
@.$_^#! < > ^</lang>
@.$_^#! < > ^</syntaxhighlight>
{{Out}}
{{Out}}
<pre>233168</pre>
<pre>233168</pre>
Fast (analytic) version:
Fast (analytic) version:
<lang Befunge>&1-::3/:1+*3*2/\5/:1+*5*2/+\96+/:1+*96+*2/-.@</lang>
<syntaxhighlight lang="befunge">&1-::3/:1+*3*2/\5/:1+*5*2/+\96+/:1+*96+*2/-.@</syntaxhighlight>
{{Out}}
{{Out}}
<pre>233168</pre>
<pre>233168</pre>
Line 546: Line 735:
=={{header|BQN}}==
=={{header|BQN}}==
A naive solution:
A naive solution:
<lang bqn>Sum ← +´·(0=3⊸|⌊5⊸|)⊸/↕</lang>
<syntaxhighlight lang="bqn">Sum ← +´·(0=3⊸|⌊5⊸|)⊸/↕</syntaxhighlight>


A much faster solution:
A much faster solution:
<lang bqn>Sum ← {
<syntaxhighlight lang="bqn">Sum ← {
m ← (0=3⊸|⌊5⊸|)↕15 ⋄ h‿l ← 15(⌊∘÷˜∾|)𝕩
m ← (0=3⊸|⌊5⊸|)↕15 ⋄ h‿l ← 15(⌊∘÷˜∾|)𝕩
(+´l↑m×15(×+↕∘⊣)h) + (15×(+´m)×2÷˜h×h-1) + h×+´m×↕15
(+´l↑m×15(×+↕∘⊣)h) + (15×(+´m)×2÷˜h×h-1) + h×+´m×↕15
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 565: Line 754:
=={{header|C}}==
=={{header|C}}==
===Simple version===
===Simple version===
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 588: Line 777:
printf("%lld\n", sum35(limit));
printf("%lld\n", sum35(limit));
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>$ ./a.out
<pre>$ ./a.out
Line 597: Line 786:
===Fast version with arbitrary precision===
===Fast version with arbitrary precision===
{{libheader|GMP}}
{{libheader|GMP}}
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <gmp.h>
#include <gmp.h>


Line 649: Line 838:
mpz_clear(limit);
mpz_clear(limit);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>$ ./a.out
<pre>$ ./a.out
Line 659: Line 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.
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.


<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Collections.Generic;
using System.Collections.Generic;
Line 700: Line 889:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168
The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168
Line 715: Line 904:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>


Line 758: Line 947:
return system( "pause" );
return system( "pause" );
}
}
</syntaxhighlight>
</lang>
{{out}}
{{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}}==
=={{header|Clojure}}==
Quick, concise way:
Quick, concise way:
<lang clojure>(defn sum-mults [n & mults]
<syntaxhighlight lang="clojure">(defn sum-mults [n & mults]
(let [pred (apply some-fn
(let [pred (apply some-fn
(map #(fn [x] (zero? (mod x %))) mults))]
(map #(fn [x] (zero? (mod x %))) mults))]
(->> (range n) (filter pred) (reduce +))))
(->> (range n) (filter pred) (reduce +))))


(println (sum-mults 1000 3 5))</lang>
(println (sum-mults 1000 3 5))</syntaxhighlight>


Transducers approach:
Transducers approach:
<lang clojure>(defn sum-mults [n & mults]
<syntaxhighlight lang="clojure">(defn sum-mults [n & mults]
(transduce (filter (fn [x] (some (fn [mult] (zero? (mod x mult))) mults)))
(transduce (filter (fn [x] (some (fn [mult] (zero? (mod x mult))) mults)))
+ (range n)))
+ (range n)))


(println (sum-mults 1000 3 5))</lang>
(println (sum-mults 1000 3 5))</syntaxhighlight>


Or optimized (translated from Groovy):
Or optimized (translated from Groovy):
<lang clojure>(defn sum-mul [n f]
<syntaxhighlight lang="clojure">(defn sum-mul [n f]
(let [n1 (/' (inc' n) f)]
(let [n1 (/' (inc' n) f)]
(*' f n1 (inc' n1) 1/2)))
(*' f n1 (inc' n1) 1/2)))


(def sum-35 #(-> % (sum-mul 3) (+ (sum-mul % 5)) (- (sum-mul % 15))))
(def sum-35 #(-> % (sum-mul 3) (+ (sum-mul % 5)) (- (sum-mul % 15))))
(println (sum-35 1000000000))</lang>
(println (sum-35 1000000000))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 790: Line 1,010:
Using OpenCOBOL.
Using OpenCOBOL.


<lang cobol>
<syntaxhighlight lang="cobol">
Identification division.
Identification division.
Program-id. three-five-sum.
Program-id. three-five-sum.
Line 814: Line 1,034:
or function mod(ws-the-number, 5) = zero
or function mod(ws-the-number, 5) = zero
then add ws-the-number to ws-the-sum.
then add ws-the-number to ws-the-sum.
</syntaxhighlight>
</lang>


Output:
Output:
Line 822: Line 1,042:


Using triangular numbers:
Using triangular numbers:
<lang cobol>
<syntaxhighlight lang="cobol">
Identification division.
Identification division.
Program-id. three-five-sum-fast.
Program-id. three-five-sum-fast.
Line 870: Line 1,090:
Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2.
Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2.
goback.
goback.
</syntaxhighlight>
</lang>


Output:
Output:
Line 880: Line 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)
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)


<lang cobol>
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. SUM35.
PROGRAM-ID. SUM35.
Line 921: Line 1,141:
EXIT.
EXIT.
END PROGRAM SUM35.
END PROGRAM SUM35.
</syntaxhighlight>
</lang>
Output
Output
<pre>+00233333333166666668</pre>
<pre>+00233333333166666668</pre>
Line 927: Line 1,147:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Slow, naive version:
Slow, naive version:
<lang lisp>(defun sum-3-5-slow (limit)
<syntaxhighlight lang="lisp">(defun sum-3-5-slow (limit)
(loop for x below limit
(loop for x below limit
when (or (zerop (rem x 3)) (zerop (rem x 5)))
when (or (zerop (rem x 3)) (zerop (rem x 5)))
sum x))</lang>
sum x))</syntaxhighlight>


Fast version (adapted translation of [[#Tcl|Tcl]]):
Fast version (adapted translation of [[#Tcl|Tcl]]):
<lang lisp>(defun sum-3-5-fast (limit)
<syntaxhighlight lang="lisp">(defun sum-3-5-fast (limit)
(flet ((triangular (n) (truncate (* n (1+ n)) 2)))
(flet ((triangular (n) (truncate (* n (1+ n)) 2)))
(let ((n (1- limit))) ; Sum multiples *below* the limit
(let ((n (1- limit))) ; Sum multiples *below* the limit
(- (+ (* 3 (triangular (truncate n 3)))
(- (+ (* 3 (triangular (truncate n 3)))
(* 5 (triangular (truncate n 5))))
(* 5 (triangular (truncate n 5))))
(* 15 (triangular (truncate n 15)))))))</lang>
(* 15 (triangular (truncate n 15)))))))</syntaxhighlight>


{{Out}}
{{Out}}
Line 949: Line 1,169:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Sum3_5;
MODULE Sum3_5;
IMPORT StdLog, Strings, Args;
IMPORT StdLog, Strings, Args;
Line 976: Line 1,196:


END Sum3_5.
END Sum3_5.
</syntaxhighlight>
</lang>
Execute: ^Q Sum3_5.Compute 1000 ~ <br/>
Execute: ^Q Sum3_5.Compute 1000 ~ <br/>
Output:
Output:
Line 984: Line 1,204:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# sum multiples up to given input
# sum multiples up to given input
Line 1,012: Line 1,232:
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method: "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
print("Fast method: "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,022: Line 1,242:
{{trans|Ruby}}
{{trans|Ruby}}
Short, but not optimized.
Short, but not optimized.
<lang ruby>def sum_3_5_multiples(n)
<syntaxhighlight lang="ruby">def sum_3_5_multiples(n)
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end
end


puts sum_3_5_multiples(1000)</lang>
puts sum_3_5_multiples(1000)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,036: Line 1,256:
To conform to task requirements, and other versions,
To conform to task requirements, and other versions,
modified to find sums below n.
modified to find sums below n.
<lang ruby>require "big"
<syntaxhighlight lang="ruby">require "big"


def g(n1, n2, n3)
def g(n1, n2, n3)
Line 1,048: Line 1,268:
# For extra credit
# For extra credit
puts g(3,5,"100000000000000000000".to_big_i - 1)
puts g(3,5,"100000000000000000000".to_big_i - 1)
puts g(3,5,"100000000000000000000".to_big_i)</lang>
puts g(3,5,"100000000000000000000".to_big_i)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,058: Line 1,278:


Alternative faster version 2.
Alternative faster version 2.
<lang ruby>require "big"
<syntaxhighlight lang="ruby">require "big"


def sumMul(n, f)
def sumMul(n, f)
Line 1,071: Line 1,291:
(1..20).each do |e| limit = 10.to_big_i ** e
(1..20).each do |e| limit = 10.to_big_i ** e
puts "%2d:%22d %s" % [e, limit, sum35(limit)]
puts "%2d:%22d %s" % [e, limit, sum35(limit)]
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,097: Line 1,317:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.bigint;
<syntaxhighlight lang="d">import std.stdio, std.bigint;


BigInt sum35(in BigInt n) pure nothrow {
BigInt sum35(in BigInt n) pure nothrow {
Line 1,114: Line 1,334:
1000.BigInt.sum35.writeln;
1000.BigInt.sum35.writeln;
(10.BigInt ^^ 20).sum35.writeln;
(10.BigInt ^^ 20).sum35.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,123: Line 1,343:
2333333333333333333316666666666666666668</pre>
2333333333333333333316666666666666666668</pre>


=={{header|dc}}==
<syntaxhighlight lang="dc">[ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm

[ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss

[ 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}}==
=={{header|Delphi}}==
<lang delphi>program sum35;
<syntaxhighlight lang="delphi">program sum35;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,145: Line 1,398:
end;
end;
writeln(sum);
writeln(sum);
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>sum-divisible n:
<syntaxhighlight lang="dejavu">sum-divisible n:
0
0
for i range 1 -- n:
for i range 1 -- n:
Line 1,156: Line 1,409:
+ i
+ i


!. sum-divisible 1000</lang>
!. sum-divisible 1000</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<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}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'math) ;; divides?
(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when
(lib 'sequences) ;; sum/when
Line 1,195: Line 1,461:
❌ error: expected coprimes (42 666)
❌ error: expected coprimes (42 666)
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>


class
class
Line 1,227: Line 1,493:
end
end


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,235: Line 1,501:
=={{header|Elixir}}==
=={{header|Elixir}}==
Simple (but slow)
Simple (but slow)
<lang elixir>iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum
<syntaxhighlight lang="elixir">iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum
233168</lang>
233168</syntaxhighlight>


Fast version:
Fast version:
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def sumMul(n, f) do
def sumMul(n, f) do
n1 = div(n - 1, f)
n1 = div(n - 1, f)
Line 1,254: Line 1,520:
n = round(:math.pow(10, i))
n = round(:math.pow(10, i))
IO.puts RC.sum35(n)
IO.puts RC.sum35(n)
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,281: Line 1,547:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==

===version 1===
Vanilla:
<lang Emacs Lisp>

(defun sum-3-5 (n)
<syntaxhighlight lang="lisp">(defun sum-3-5 (n)
(apply '+ (mapcar
(let ((sum 0))
'(lambda (x) (if (or (= 0 (% x 3) ) (= 0 (% x 5) ))
x 0) )
(dotimes (x n)
(number-sequence 1 (- n 1)) )))
(when (or (zerop (% x 3)) (zerop (% x 5)))
(setq sum (+ sum x))))
</lang>
sum))</syntaxhighlight>
===version 2===

<lang Emacs Lisp>
{{libheader|seq.el}}
(defun sum-3-5 (n)
<syntaxhighlight lang="lisp">(defun sum-3-5 (n)
(apply '+ (seq-filter
(apply #'+ (seq-filter
'(lambda (x) (or (= 0 (% x 3) ) (= 0 (% x 5) )))
(number-sequence 1 (- n 1))) ))
(lambda (x) (or (zerop (% x 3) ) (zerop (% x 5))))
(number-sequence 1 (- n 1)))))</syntaxhighlight>
</lang>
<b>Eval:</b>
<lang Emacs Lisp>
(insert (format "%d" (sum-3-5 100) ))
(insert (format "%d" (sum-3-5 1000) ))
</lang>
<b>Output:</b>
<pre>
2318
233168
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0).
<syntaxhighlight 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 < 3 -> Total;
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
Line 1,315: Line 1,571:
sum_3_5(X-1, Total).
sum_3_5(X-1, Total).


io:format("~B~n", [sum_3_5(1000)]).</lang>
io:format("~B~n", [sum_3_5(1000)]).</syntaxhighlight>


{{out}}
{{out}}
Line 1,321: Line 1,577:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight 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)
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 1,334: Line 1,590:


[for i = 0 to 30 do yield i]
[for i = 0 to 30 do yield i]
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))</lang>
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:5em">233168
<pre style="height:5em">233168
Line 1,379: Line 1,635:
<br>
<br>
{{works with|Factor|0.99 2019-10-06}}
{{works with|Factor|0.99 2019-10-06}}
<lang factor>USING: kernel math prettyprint ;
<syntaxhighlight lang="factor">USING: kernel math prettyprint ;


: sum-multiples ( m n upto -- sum )
: sum-multiples ( m n upto -- sum )
Line 1,387: Line 1,643:


3 5 1000 sum-multiples .
3 5 1000 sum-multiples .
3 5 1e20 sum-multiples .</lang>
3 5 1e20 sum-multiples .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,396: Line 1,652:
=={{header|FBSL}}==
=={{header|FBSL}}==
Derived from BASIC version
Derived from BASIC version
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE


FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
Line 1,410: Line 1,666:
PRINT sumOfThreeFiveMultiples(1000)
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
PAUSE
</syntaxhighlight>
</lang>
Output
Output
<pre>233168
<pre>233168
Line 1,418: Line 1,674:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: main ( n -- )
<syntaxhighlight lang="forth">: main ( n -- )
0 swap
0 swap
3 do
3 do
Line 1,429: Line 1,685:
. ;
. ;


1000 main \ 233168 ok</lang>
1000 main \ 233168 ok</syntaxhighlight>


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.
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.


<lang forth>: third 2 pick ;
<syntaxhighlight lang="forth">: third 2 pick ;


: >dtriangular ( n -- d )
: >dtriangular ( n -- d )
Line 1,475: Line 1,731:
100000000000000000 2333333333333333316666666666666668
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668 ok
1000000000000000000 233333333333333333166666666666666668 ok
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,481: Line 1,737:


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.
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.
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.
Calculates as per the young Gauss: N*(N + 1)/2 = 1 + 2 + 3 + ... + N.
Line 1,521: Line 1,777:
GO TO 10 !Have another go.
GO TO 10 !Have another go.
END !So much for that.
END !So much for that.
</syntaxhighlight>
</lang>
Sample output:
Sample output:
<pre>
<pre>
Line 1,544: Line 1,800:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function sum35 (n As UInteger) As UInteger
Function sum35 (n As UInteger) As UInteger
Line 1,558: Line 1,814:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,567: Line 1,823:
=={{header|Frink}}==
=={{header|Frink}}==
Program has a brute-force approach for n=1000, and also inclusion/exclusion for larger values.
Program has a brute-force approach for n=1000, and also inclusion/exclusion for larger values.
<syntaxhighlight lang="frink">
<lang Frink>
sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]
sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]


Line 1,580: Line 1,836:
println["The sum of all the multiples of 3 or 5 below 1000 is $sum999"]
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]]
println["The sum of all multiples less than 1e20 is " + sum35big[1_00000_00000_00000_00000 - 1]]
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
The sum of all the multiples of 3 or 5 below 1000 is 233168
The sum of all the multiples of 3 or 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668
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>
</pre>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,609: Line 1,892:
return n
return n
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,615: Line 1,898:
</pre>
</pre>
Extra credit:
Extra credit:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,645: Line 1,928:
s := sum2(b3)
s := sum2(b3)
return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1)
return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,653: Line 1,936:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 }
<syntaxhighlight 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) }</lang>
def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }</syntaxhighlight>
Test Code:
Test Code:
<lang groovy>[(1000): 233168, (10e20): 233333333333333333333166666666666666666668].each { arg, value ->
<syntaxhighlight lang="groovy">[(1000): 233168, (10e20): 233333333333333333333166666666666666666668].each { arg, value ->
println "Checking $arg == $value"
println "Checking $arg == $value"
assert sum35(arg) == value
assert sum35(arg) == value
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Checking 1000 == 233168
<pre>Checking 1000 == 233168
Line 1,666: Line 1,949:
=={{header|Haskell}}==
=={{header|Haskell}}==
Also a method for calculating sum of multiples of any list of numbers.
Also a method for calculating sum of multiples of any list of numbers.
<lang haskell>import Data.List (nub)
<syntaxhighlight lang="haskell">import Data.List (nub)


----------------- SUM MULTIPLES OF 3 AND 5 ---------------
----------------- SUM MULTIPLES OF 3 AND 5 ---------------
Line 1,707: Line 1,990:
where
where
f = sumMul n
f = sumMul n
g = sumMulS n</lang>
g = sumMulS n</syntaxhighlight>
{{out}}
{{out}}
<pre>233168
<pre>233168
Line 1,718: Line 2,001:
The following works in both langauges.
The following works in both langauges.


<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
n := (integer(A[1]) | 1000)-1
n := (integer(A[1]) | 1000)-1
write(sum(n,3)+sum(n,5)-sum(n,15))
write(sum(n,3)+sum(n,5)-sum(n,15))
Line 1,725: Line 2,008:
procedure sum(n,m)
procedure sum(n,m)
return m*((n/m)*(n/m+1)/2)
return m*((n/m)*(n/m+1)/2)
end</lang>
end</syntaxhighlight>


Sample output:
Sample output:
Line 1,738: Line 2,021:


=={{header|J}}==
=={{header|J}}==
<lang J>
mp =: $:~ :(+/ .*) NB. matrix product
f =: (mp 0 = [: */ 3 5 |/ ])@:i.
assert 233168 -: f 1000 NB. ****************** THIS IS THE ANSWER FOR 1000
</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


assert (f -: -:@:(+/)@:(+|.)@:g@:i.) 50 NB. half sum of the pattern.

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

0 10000 3
0 10000 5
0 10000 15

0 10000000000000000000 3
0 10000000000000000000 5
0 10000000000000000000 15



(0,.10 10000 10000000000000000000x)+`-/"1@:(sum_arithmetic_series"1@:(,"1 0"1 _))3 5 15x
23 23331668 23333333333333333331666666666666666668
</lang>
=== Simple Solution ===
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.
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.
<syntaxhighlight lang="j">
<lang J>
NB. Naive method
NB. Naive method
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.
echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)

NB. slightly less naive: select the numbers which have no remainder when divided by 3 or 5:
echo 'The sum of the multiples of 3 or 5 < 1000 is still ', ": +/I.+./0=3 5|/i.1000


echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)




Line 1,798: Line 2,041:


echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
exit ''


</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
The sum of the multiples of 3 or 5 < 1000 is 233168
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
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668
</pre>
</pre>
Line 1,809: Line 2,052:
=={{header|Java}}==
=={{header|Java}}==
===Simple Version===
===Simple Version===
<lang Java>class SumMultiples {
<syntaxhighlight lang="java">class SumMultiples {
public static long getSum(long n) {
public static long getSum(long n) {
long sum = 0;
long sum = 0;
Line 1,820: Line 2,063:
System.out.println(getSum(1000));
System.out.println(getSum(1000));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>
===Extra Credit===
===Extra Credit===
<syntaxhighlight lang="java">
<lang Java>
import java.math.BigInteger;
import java.math.BigInteger;


Line 1,865: Line 2,108:


}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,899: Line 2,142:
===ES5===
===ES5===


JavaScript is better equipped for flexibility than for scale. The value of <lang JavaScript> Number.MAX_SAFE_INTEGER</lang> is 9007199254740991, or 2^53 - 1 – resulting from an IEEE 754 double-precision floating point representation of numeric values).
JavaScript is better equipped for flexibility than for scale. The value of <syntaxhighlight lang="javascript"> Number.MAX_SAFE_INTEGER</syntaxhighlight> 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 …
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,905: Line 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:
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:


<lang JavaScript>(function (lstFactors, intExponent) {
<syntaxhighlight lang="javascript">(function (lstFactors, intExponent) {


// [n] -> n -> n
// [n] -> n -> n
Line 1,963: Line 2,206:
JSON.stringify(lstTable);
JSON.stringify(lstTable);


})([3, 5], 8);</lang>
})([3, 5], 8);</syntaxhighlight>




Line 1,989: Line 2,232:
|}
|}


<lang JavaScript> [["Below","Sum"],["10^1",23],["10^2",2318],["10^3",233168],
<syntaxhighlight lang="javascript"> [["Below","Sum"],["10^1",23],["10^2",2318],["10^3",233168],
["10^4",23331668],["10^5",2333316668],["10^6",233333166668],
["10^4",23331668],["10^5",2333316668],["10^6",233333166668],
["10^7",23333331666668],["10^8",2333333316666668]]</lang>
["10^7",23333331666668],["10^8",2333333316666668]]</syntaxhighlight>
====With wheel increments====
====With wheel increments====
<lang JavaScript>function sm35(n){
<syntaxhighlight lang="javascript">function sm35(n){
var s=0, inc=[3,2,1,3,1,2,3]
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
for (var j=6, i=0; i<n; j+=j==6?-j:1, i+=inc[j]) s+=i
return s
return s
}</lang>
}</syntaxhighlight>
====With triangular numbers====
====With triangular numbers====
<lang JavaScript>function sm35(n){
<syntaxhighlight lang="javascript">function sm35(n){
return tri(n,3) + tri(n,5) - tri(n,15)
return tri(n,3) + tri(n,5) - tri(n,15)
function tri(n, f) {
function tri(n, f) {
Line 2,005: Line 2,248:
return f * n * (n+1) / 2
return f * n * (n+1) / 2
}
}
}</lang>
}</syntaxhighlight>
'''This:'''
'''This:'''
<lang JavaScript>for (var i=1, n=10; i<9; n*=10, i+=1) {
<syntaxhighlight lang="javascript">for (var i=1, n=10; i<9; n*=10, i+=1) {
document.write(10, '<sup>', i, '</sup> ', sm35(n), '<br>')
document.write(10, '<sup>', i, '</sup> ', sm35(n), '<br>')
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
10<sup>1</sup> 23
10<sup>1</sup> 23
Line 2,023: Line 2,266:
===ES6===
===ES6===


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// sum35 :: Int -> Int
// sum35 :: Int -> Int
Line 2,163: Line 2,406:
// ---
// ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Sums for n = 10^1 thru 10^8:
<pre>Sums for n = 10^1 thru 10^8:
Line 2,175: Line 2,418:
100000000 -> 2333333316666668</pre>
100000000 -> 2333333316666668</pre>


=={{header|Joy}}==
<syntaxhighlight lang="jq">
DEFINE divisor == rem 0 = ;
mul3or5 == [3 divisor] [5 divisor] cleave or ;
when == swap [] ifte .

"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}}==
=={{header|jq}}==
<syntaxhighlight lang="jq">
<lang jq>
def sum_multiples(d):
def sum_multiples(d):
((./d) | floor) | (d * . * (.+1))/2 ;
((./d) | floor) | (d * . * (.+1))/2 ;
Line 2,183: Line 2,444:
def task(a;b):
def task(a;b):
. - 1
. - 1
| sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);</lang>Examples:
| sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);</syntaxhighlight>Examples:


jq does not (yet) support arbitrary-precision integer arithmetic but converts large integers to floats, so:
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
1000 | task(3;5) # => 233168


10e20 | task(3;5) # => 2.333333333333333e+41</lang>
10e20 | task(3;5) # => 2.333333333333333e+41</syntaxhighlight>



=={{header|Julia}}==
=={{header|Julia}}==
sum multiples of each, minus multiples of the least common multiple (lcm). Similar to MATLAB's version.
sum multiples of each, minus multiples of the least common multiple (lcm). Similar to MATLAB's version.
<lang Julia>multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)</lang>
<syntaxhighlight lang="julia">multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)</syntaxhighlight>
Output:
Output:
<pre>julia> multsum(3, 5, 1000)
<pre>julia> multsum(3, 5, 1000)
Line 2,229: Line 2,491:
(100000000000000000000,2333333333333333333316666666666666666668)</pre>
(100000000000000000000,2333333333333333333316666666666666666668)</pre>
a slightly more efficient version
a slightly more efficient version
<lang Julia>multsum(n, lim) = (occ = div(lim-1, n); div(n*occ*(occ+1), 2))
<syntaxhighlight lang="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)</lang>
multsum(n, m, lim) = multsum(n, lim) + multsum(m, lim) - multsum(lcm(n,m), lim)</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.math.BigInteger
import java.math.BigInteger
Line 2,263: Line 2,525:
val e20 = big100k * big100k * big100k * big100k
val e20 = big100k * big100k * big100k * big100k
println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,272: Line 2,534:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(limit = 1)
<syntaxhighlight lang="lasso">local(limit = 1)
while(#limit <= 100000) => {^
while(#limit <= 100000) => {^
local(s = 0)
local(s = 0)
Line 2,280: Line 2,542:
'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
#limit = integer(#limit->asString + '0')
#limit = integer(#limit->asString + '0')
^}</lang>
^}</syntaxhighlight>
{{out}}
{{out}}
<pre>The sum of multiples of 3 or 5 between 1 and 0 is: 0
<pre>The sum of multiples of 3 or 5 between 1 and 0 is: 0
Line 2,293: Line 2,555:
Uses the IPints library when the result will be very large.
Uses the IPints library when the result will be very large.


<lang Limbo>implement Sum3and5;
<syntaxhighlight lang="limbo">implement Sum3and5;


include "sys.m"; sys: Sys;
include "sys.m"; sys: Sys;
Line 2,365: Line 2,627:
sub(isum_multiples(ints[15], limit)));
sub(isum_multiples(ints[15], limit)));
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,373: Line 2,635:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on sum35 (n)
<syntaxhighlight lang="lingo">on sum35 (n)
res = 0
res = 0
repeat with i = 0 to (n-1)
repeat with i = 0 to (n-1)
Line 2,381: Line 2,643:
end repeat
end repeat
return res
return res
end</lang>
end</syntaxhighlight>


<lang lingo>put sum35(1000)
<syntaxhighlight lang="lingo">put sum35(1000)
-- 233168</lang>
-- 233168</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>function sumUntil n
<syntaxhighlight lang="livecode">function sumUntil n
repeat with i = 0 to (n-1)
repeat with i = 0 to (n-1)
if i mod 3 = 0 or i mod 5 = 0 then
if i mod 3 = 0 or i mod 5 = 0 then
Line 2,396: Line 2,658:
end sumUntil
end sumUntil


put sumUntil(1000) // 233168</lang>
put sumUntil(1000) // 233168</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
{{trans|Tcl}}
{{trans|Tcl}}
<syntaxhighlight lang="lua">
<lang Lua>
function tri (n) return n * (n + 1) / 2 end
function tri (n) return n * (n + 1) / 2 end


Line 2,413: Line 2,675:
print(sum35(1000))
print(sum35(1000))
print(sum35(1e+20))
print(sum35(1e+20))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,422: Line 2,684:
=={{header|Maple}}==
=={{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).
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))
F := unapply( sum(3*i,i=1..floor((n-1)/3))
+ sum(5*i,i=1..floor((n-1)/5))
+ sum(5*i,i=1..floor((n-1)/5))
Line 2,430: Line 2,692:


F(10^20);
F(10^20);
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,450: Line 2,712:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang mathematica>sum35[n_] :=
<syntaxhighlight lang="mathematica">sum35[n_] :=
Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] -
Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] -
Sum[k, {k, 15, n - 1, 15}]
Sum[k, {k, 15, n - 1, 15}]
sum35[1000]</lang>
sum35[1000]</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>
<lang mathematica>sum35[10^20]</lang>
<syntaxhighlight lang="mathematica">sum35[10^20]</syntaxhighlight>
{{out}}
{{out}}
<pre>233333333333333333333166666666666666666668</pre>
<pre>233333333333333333333166666666666666666668</pre>
Another alternative is
Another alternative is
<lang mathematica> Union @@ Range[0, 999, {3, 5}] // Tr </lang>
<syntaxhighlight lang="mathematica"> Union @@ Range[0, 999, {3, 5}] // Tr </syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0))</lang>
<syntaxhighlight lang="matlab">n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0))</syntaxhighlight>
<pre>ans = 233168</pre>
<pre>ans = 233168</pre>
Another alternative is
Another alternative is
<lang MATLAB>n=1000; sum(0:3:n-1)+sum(0:5:n-1)-sum(0:15:n-1)</lang>
<syntaxhighlight lang="matlab">n=1000; sum(0:3:n-1)+sum(0:5:n-1)-sum(0:15:n-1)</syntaxhighlight>
Of course, it's more efficient to use [http://mathforum.org/library/drmath/view/57919.html Gauss' approach] of adding subsequent integers:
Of course, it's more efficient to use [http://mathforum.org/library/drmath/view/57919.html Gauss' approach] of adding subsequent integers:
<lang MATLAB>n=999;
<syntaxhighlight lang="matlab">n=999;
n3=floor(n/3);
n3=floor(n/3);
n5=floor(n/5);
n5=floor(n/5);
n15=floor(n/15);
n15=floor(n/15);
(3*n3*(n3+1) + 5*n5*(n5+1) - 15*n15*(n15+1))/2</lang>
(3*n3*(n3+1) + 5*n5*(n5+1) - 15*n15*(n15+1))/2</syntaxhighlight>
<pre>ans = 233168</pre>
<pre>ans = 233168</pre>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang Maxima>sumi(n, inc):= block(
<syntaxhighlight lang="maxima">sumi(n, inc):= block(
[kmax],
[kmax],


Line 2,489: Line 2,751:


sum35(1000);
sum35(1000);
sum35(10^20);</lang>
sum35(10^20);</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,501: Line 2,763:


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.
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.
<lang MiniScript>// simple version:
<syntaxhighlight lang="miniscript">// simple version:
sum35 = function(n)
sum35 = function(n)
sum = 0
sum = 0
Line 2,513: Line 2,775:
end function
end function


print sum35(1000)</lang>
print sum35(1000)</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>
Line 2,519: Line 2,781:
Now the fast version.
Now the fast version.
{{trans|D}}
{{trans|D}}
<lang MiniScript>// fast version:
<syntaxhighlight lang="miniscript">// fast version:
sumMul = function(n, f)
sumMul = function(n, f)
n1 = floor((n - 1) / f)
n1 = floor((n - 1) / f)
Line 2,529: Line 2,791:
end function
end function


print sum35fast(1000)</lang>
print sum35fast(1000)</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>П1 0 П0 3 П4 ИП4 3 / {x} x#0
<syntaxhighlight lang="text">П1 0 П0 3 П4 ИП4 3 / {x} x#0
17 ИП4 5 / {x} x=0 21 ИП0 ИП4 +
17 ИП4 5 / {x} x=0 21 ИП0 ИП4 +
П0 КИП4 ИП1 ИП4 - x=0 05 ИП0 С/П</lang>
П0 КИП4 ИП1 ИП4 - x=0 05 ИП0 С/П</syntaxhighlight>


Input: ''n''.
Input: ''n''.
Line 2,545: Line 2,807:
{{trans|Java}}
{{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.
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.
<lang nanoquery>def getSum(n)
<syntaxhighlight lang="nanoquery">def getSum(n)
sum = 0
sum = 0
for i in range(3, n - 1)
for i in range(3, n - 1)
Line 2,555: Line 2,817:
end
end


println getSum(1000)</lang>
println getSum(1000)</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>
Line 2,561: Line 2,823:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
Portions translation of [[#Raku|Raku]]
Portions translation of [[#Raku|Raku]]
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary
numeric digits 40
numeric digits 40
Line 2,638: Line 2,900:
say
say
return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,697: Line 2,959:
=={{header|Nim}}==
=={{header|Nim}}==
Here is the solution using normal integers.
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:
if x mod 3 == 0 or x mod 5 == 0:
result += x
result += x


echo sum35(1000)</lang>
echo sum35(1000)</syntaxhighlight>


{{out}}
{{out}}
Line 2,711: Line 2,973:
{{trans|Raku}}
{{trans|Raku}}
{{libheader|bigints}}
{{libheader|bigints}}
<lang nim>import bigints
<syntaxhighlight lang="nim">import bigints


proc sumMults(first: int32, limit: BigInt): BigInt =
proc sumMults(first: int32, limit: BigInt): BigInt =
Line 2,726: Line 2,988:
while x < "1000000000000000000000000000000".initBigInt:
while x < "1000000000000000000000000000000".initBigInt:
echo sum35 x
echo sum35 x
x *= 10</lang>
x *= 10</syntaxhighlight>


{{out}}
{{out}}
Line 2,762: Line 3,024:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<lang objeck>class SumMultiples {
<syntaxhighlight lang="objeck">class SumMultiples {
function : native : GetSum(n : Int) ~ Int {
function : native : GetSum(n : Int) ~ Int {
sum := 0;
sum := 0;
Line 2,778: Line 3,040:
}
}
}
}
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,785: Line 3,047:
</pre>
</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}}==
=={{header|OCaml}}==
<lang ocaml>let sum_mults n =
<syntaxhighlight lang="ocaml">let sum_m3m5 n =
let sum = ref 0 in
let termial x = (x * x + x) lsr 1 in
for i = 3 to (n - 1) do
3 * (termial (n / 3) - 5 * termial (n / 15)) + 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}}
{{out}}
<pre>233168</pre>
<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}}==
=={{header|Oforth}}==


<lang Oforth>999 seq filter(#[ dup 3 mod 0 == swap 5 mod 0 == or ]) sum println</lang>
<syntaxhighlight lang="oforth">999 seq filter(#[ dup 3 mod 0 == swap 5 mod 0 == or ]) sum println</syntaxhighlight>


Output:
Output:
Line 2,809: Line 3,134:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(print
(print
(fold (lambda (s x)
(fold (lambda (s x)
Line 2,815: Line 3,140:
0 (iota 1000)))
0 (iota 1000)))
; ==> 233168
; ==> 233168
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>ct(n,k)=n=n--\k;k*n*(n+1)/2;
<syntaxhighlight 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(n)=ct(n,3)+ct(n,5)-ct(n,15);
a(1000)
a(1000)
a(1e20)</lang>
a(1e20)</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 2,832: Line 3,157:
{{works with|Free Pascal|2.6.2}}
{{works with|Free Pascal|2.6.2}}


<lang Pascal>program Sum3sAnd5s;
<syntaxhighlight lang="pascal">program Sum3sAnd5s;
function Multiple(x, y: integer): Boolean;
function Multiple(x, y: integer): Boolean;
Line 2,854: Line 3,179:
{ Show sum of all multiples less than 1000. }
{ Show sum of all multiples less than 1000. }
writeln(SumMultiples(1000))
writeln(SumMultiples(1000))
end.</lang>
end.</syntaxhighlight>
===alternative===
===alternative===
using gauss summation formula, but subtract double counted.
using gauss summation formula, but subtract double counted.
adapted translation of [[#Tcl|Tcl]]
adapted translation of [[#Tcl|Tcl]]
<lang Pascal>program sum35;
<syntaxhighlight lang="pascal">program sum35;
//sum of all positive multiples of 3 or 5 below n
//sum of all positive multiples of 3 or 5 below n


Line 2,879: Line 3,204:
sum := sum-cntSumdivisibleBelowN(n,3*5);
sum := sum-cntSumdivisibleBelowN(n,3*5);
writeln(sum);
writeln(sum);
end.</lang>
end.</syntaxhighlight>
output
output
<pre>233168</pre>
<pre>233168</pre>


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict ;
use v5.20;
use experimental qw(signatures);
use warnings ;

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


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


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


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

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


sub sum_multiples($n, $limit) {
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);
say sum 1e3;
use bigint; # Machine precision was sufficient for the first calculation
use bigint; # Machine precision was sufficient for the first calculation
say sum(1e20);</lang>
say sum 1e20;</syntaxhighlight>
{{Out}}
{{Out}}
<pre>233168
<pre>233168
Line 2,924: Line 3,251:
===native===
===native===
note the result of sum35() is inaccurate above 2^53 on 32-bit, 2^64 on 64-bit.
note the result of sum35() is inaccurate above 2^53 on 32-bit, 2^64 on 64-bit.
<!--<lang Phix>(phixonline)-->
<!--<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: #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: #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>
Line 2,941: Line 3,268:
<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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,958: Line 3,285:
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
Fast analytical version with arbitrary precision
Fast analytical version with arbitrary precision
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,987: Line 3,314:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,017: Line 3,344:
Naive version (slow) :
Naive version (slow) :


<lang PHP>$max = 1000;
<syntaxhighlight lang="php">$max = 1000;
$sum = 0;
$sum = 0;
for ($i = 1 ; $i < $max ; $i++) {
for ($i = 1 ; $i < $max ; $i++) {
Line 3,025: Line 3,352:
}
}
echo $sum, PHP_EOL;
echo $sum, PHP_EOL;
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,032: Line 3,359:
Fast version:
Fast version:


<lang PHP>function sum_multiples($max, $divisor) {
<syntaxhighlight lang="php">function sum_multiples($max, $divisor) {
// Number of multiples of $divisor <= $max
// Number of multiples of $divisor <= $max
$num = floor($max / $divisor);
$num = floor($max / $divisor);
Line 3,043: Line 3,370:
+ sum_multiples($max - 1, 5)
+ sum_multiples($max - 1, 5)
- sum_multiples($max - 1, 15);
- sum_multiples($max - 1, 15);
echo $sum, PHP_EOL;</lang>
echo $sum, PHP_EOL;</syntaxhighlight>


{{out}}
{{out}}
Line 3,053: Line 3,380:
These functions allow for arbitrary-length integers to be worked with.
These functions allow for arbitrary-length integers to be worked with.


<lang PHP>function sum_multiples_gmp($max, $divisor) {
<syntaxhighlight lang="php">function sum_multiples_gmp($max, $divisor) {
// Number of multiples of $divisor <= $max
// Number of multiples of $divisor <= $max
$num = gmp_div($max, $divisor);
$num = gmp_div($max, $divisor);
Line 3,071: Line 3,398:
);
);
printf('%22s : %s' . PHP_EOL, gmp_strval($n), $sum);
printf('%22s : %s' . PHP_EOL, gmp_strval($n), $sum);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,099: Line 3,426:
=={{header|Picat}}==
=={{header|Picat}}==
Uses both the naive method and inclusion/exclusion.
Uses both the naive method and inclusion/exclusion.
<syntaxhighlight lang="picat">
<lang Picat>
sumdiv(N, D) = S =>
sumdiv(N, D) = S =>
M = N div D,
M = N div D,
Line 3,110: Line 3,437:
writef("The sum of all multiples of 3 and 5 below 1000 is %w%n", Upto1K),
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)).
writef("The sum of all multiples less than 1e20 is %w%n", sum35big(99999_99999_99999_99999)).
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,117: Line 3,444:
</pre>
</pre>
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de sumMul (N F)
<syntaxhighlight lang="picolisp">(de sumMul (N F)
(let N1 (/ (dec N) F)
(let N1 (/ (dec N) F)
(*/ F N1 (inc N1) 2) ) )
(*/ F N1 (inc N1) 2) ) )
Line 3,126: Line 3,453:
(-
(-
(+ (sumMul N 3) (sumMul N 5))
(+ (sumMul N 3) (sumMul N 5))
(sumMul N 15) ) ) ) )</lang>
(sumMul N 15) ) ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,152: Line 3,479:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>threeor5: procedure options (main); /* 8 June 2014 */
<syntaxhighlight lang="pl/i">threeor5: procedure options (main); /* 8 June 2014 */
declare (i, n) fixed(10), sum fixed (31) static initial (0);
declare (i, n) fixed(10), sum fixed (31) static initial (0);


Line 3,164: Line 3,491:
put edit ( trim(sum) ) (A);
put edit ( trim(sum) ) (A);


end threeor5;</lang>
end threeor5;</syntaxhighlight>
Outputs:
Outputs:
<pre>
<pre>
Line 3,173: Line 3,500:
The number of multiples of 3 or 5 below 10000000 is 23333331666668
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>
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}}==
=={{header|PowerShell}}==
<lang powershell>
<syntaxhighlight lang="powershell">
function SumMultiples ( [int]$Base, [int]$Upto )
function SumMultiples ( [int]$Base, [int]$Upto )
{
{
Line 3,185: Line 3,570:
# Calculate the sum of the multiples of 3 and 5 up to 1000
# 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 )
( SumMultiples -Base 3 -Upto 1000 ) + ( SumMultiples -Base 5 -Upto 1000 ) - ( SumMultiples -Base 15 -Upto 1000 )
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,191: Line 3,576:
</pre>
</pre>
For arbitrarily large integers, simply change the variable type.
For arbitrarily large integers, simply change the variable type.
<lang powershell>
<syntaxhighlight lang="powershell">
function SumMultiples ( [bigint]$Base, [bigint]$Upto )
function SumMultiples ( [bigint]$Base, [bigint]$Upto )
{
{
Line 3,202: Line 3,587:
$Upto = [bigint]::Pow( 10, 210 )
$Upto = [bigint]::Pow( 10, 210 )
( SumMultiples -Base 3 -Upto $Upto ) + ( SumMultiples -Base 5 -Upto $Upto ) - ( SumMultiples -Base 15 -Upto $Upto )
( SumMultiples -Base 3 -Upto $Upto ) + ( SumMultiples -Base 5 -Upto $Upto ) - ( SumMultiples -Base 15 -Upto $Upto )
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,208: Line 3,593:
</pre>
</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.
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.
<lang Powershell>function Get-SumOfMultiples
<syntaxhighlight lang="powershell">function Get-SumOfMultiples
{
{
Param
Param
Line 3,238: Line 3,623:
}
}
$Sum
$Sum
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Get-SumOfMultiples</pre>
<pre>Get-SumOfMultiples</pre>
Line 3,248: Line 3,633:
=={{header|Prolog}}==
=={{header|Prolog}}==
===Slow version===
===Slow version===
<lang Prolog>sum_of_multiples_of_3_and_5_slow(N, TT) :-
<syntaxhighlight lang="prolog">sum_of_multiples_of_3_and_5_slow(N, TT) :-
sum_of_multiples_of_3_and_5(N, 1, 0, TT).
sum_of_multiples_of_3_and_5(N, 1, 0, TT).


Line 3,264: Line 3,649:
sum_of_multiples_of_3_and_5(N, K1, C5, S).
sum_of_multiples_of_3_and_5(N, K1, C5, S).


</syntaxhighlight>
</lang>


===Fast version===
===Fast version===
<lang Polog>sum_of_multiples_of_3_and_5_fast(N, TT):-
<syntaxhighlight lang="polog">sum_of_multiples_of_3_and_5_fast(N, TT):-
maplist(compute_sum(N), [3,5,15], [TT3, TT5, TT15]),
maplist(compute_sum(N), [3,5,15], [TT3, TT5, TT15]),
TT is TT3 + TT5 - TT15.
TT is TT3 + TT5 - TT15.
Line 3,276: Line 3,661:
; N2 is N div N1),
; N2 is N div N1),
Sum is N1 * N2 * (N2 + 1) / 2.
Sum is N1 * N2 * (N2 + 1) / 2.
</syntaxhighlight>
</lang>


Output :
Output :
Line 3,287: Line 3,672:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
EnableExplicit


Line 3,308: Line 3,693:
CloseConsole()
CloseConsole()
EndIf
EndIf
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,317: Line 3,702:
=={{header|Python}}==
=={{header|Python}}==
Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()
Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()
<lang python>def sum35a(n):
<syntaxhighlight lang="python">def sum35a(n):
'Direct count'
'Direct count'
# note: ranges go to n-1
# note: ranges go to n-1
Line 3,348: Line 3,733:
# Scalability
# Scalability
p = 20
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))</lang>
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))</syntaxhighlight>


{{out}}
{{out}}
Line 3,366: Line 3,751:
Or, more generally – taking the area under the straight line between the first multiple and the last:
Or, more generally – taking the area under the straight line between the first multiple and the last:
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Summed multiples of 3 and 5 up to n'''
<syntaxhighlight lang="python">'''Summed multiples of 3 and 5 up to n'''




Line 3,436: Line 3,821:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Summed multiples of 3 and 5 up to n:
<pre>Summed multiples of 3 and 5 up to n:
Line 3,455: Line 3,840:


=={{header|Q}}==
=={{header|Q}}==
<lang q>s35:{sum {?[(0=x mod 3) | 0=x mod 5;x;0]} each 1+til x - 1}
<syntaxhighlight 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</lang>
s35 each 10 100 1000 10000 1000000</syntaxhighlight>


Extra credit, using the summation formula:
Extra credit, using the summation formula:


<lang q>sn:{x*(x+1)%2} / Sum of 1 to n
<syntaxhighlight 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:{a:x-1; (3*sn floor a%3) + (5*sn floor a%5) - (15*sn floor a%15)}
s35 e+10</lang>
s35 e+10</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ dup 1+ * 2 / ] is triangulared ( n --> n )
<syntaxhighlight lang="quackery"> [ dup 1+ * 2 / ] is triangulared ( n --> n )
[ 1 -
[ 1 -
Line 3,475: Line 3,860:
1000 sum-of-3s&5s echo cr
1000 sum-of-3s&5s echo cr
10 20 ** sum-of-3s&5s echo cr</lang>
10 20 ** sum-of-3s&5s echo cr</syntaxhighlight>


{{out}}
{{out}}
Line 3,485: Line 3,870:
=={{header|R}}==
=={{header|R}}==


<lang rsplus>m35 = function(n) sum(unique(c(
<syntaxhighlight lang="rsplus">m35 = function(n) sum(unique(c(
seq(3, n-1, by = 3), seq(5, n-1, by = 5))))
seq(3, n-1, by = 3), seq(5, n-1, by = 5))))
m35(1000) # 233168</lang>
m35(1000) # 233168</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require math)
(require math)
Line 3,517: Line 3,902:


(for/list ([k 20]) (analytical k))
(for/list ([k 20]) (analytical k))
</syntaxhighlight>
</lang>
Output:
Output:
<lang racket>
<syntaxhighlight lang="racket">
'(0 23 2318 233168 23331668 2333316668 233333166668)
'(0 23 2318 233168 23331668 2333316668 233333166668)
'(0
'(0
Line 3,541: Line 3,926:
233333333333333333166666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668)
23333333333333333331666666666666666668)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub sum35($n) { [+] grep * %% (3|5), ^$n; }
<syntaxhighlight lang="raku" line>sub sum35($n) { [+] grep * %% (3|5), ^$n; }


say sum35 1000;</lang>
say sum35 1000;</syntaxhighlight>
{{out}}
{{out}}
<pre>233168</pre>
<pre>233168</pre>
Here's an analytical approach that scales much better for large values.
Here's an analytical approach that scales much better for large values.
<lang perl6>sub sum-mults($first, $limit) {
<syntaxhighlight lang="raku" line>sub sum-mults($first, $limit) {
(my $last = $limit - 1) -= $last % $first;
(my $last = $limit - 1) -= $last % $first;
($last div $first) * ($first + $last) div 2;
($last div $first) * ($first + $last) div 2;
Line 3,560: Line 3,945:
}
}


say sum35($_) for 1,10,100...10**30;</lang>
say sum35($_) for 1,10,100...10**30;</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 3,596: Line 3,981:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* 14.05.2013 Walter Pachl
* 14.05.2013 Walter Pachl
**********************************************************************/
**********************************************************************/
Line 3,607: Line 3,992:
s=s+i
s=s+i
End
End
Return s</lang>
Return s</syntaxhighlight>
Output:
Output:
<pre>233168</pre>
<pre>233168</pre>


===version 2===
===version 2===
<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* Translation from Raku->NetRexx->REXX
* Translation from Raku->NetRexx->REXX
* 15.05.2013 Walter Pachl
* 15.05.2013 Walter Pachl
Line 3,635: Line 4,020:
last = last - last // first
last = last - last // first
sum = (last % first) * (first + last) % 2
sum = (last % first) * (first + last) % 2
return sum</lang>
return sum</syntaxhighlight>
Output:
Output:
<pre> 1 0
<pre> 1 0
Line 3,674: Line 4,059:


The formula used is a form of the Gauss Summation formula.
The formula used is a form of the Gauss Summation formula.
<lang rexx>/*REXX program counts all integers from 1 ──► N─1 that are multiples of 3 or 5. */
<syntaxhighlight 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*/
parse arg N t . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 1000 /*Not specified? Then use the default.*/
if N=='' | N=="," then N= 1000 /*Not specified? Then use the default.*/
Line 3,689: Line 4,074:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDiv: procedure; parse arg x,d; $= x % d; return d * $ * ($+1) % 2</lang>
sumDiv: procedure; parse arg x,d; $= x % d; return d * $ * ($+1) % 2</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 3,791: Line 4,176:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see sum35(1000) + nl
see sum35(1000) + nl
Line 3,802: Line 4,187:
func tri n
func tri n
return n * (n + 1) / 2
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}}==
=={{header|Ruby}}==
Simple Version (Slow):
Simple Version (Slow):
<lang ruby>def sum35(n)
<syntaxhighlight lang="ruby">def sum35(n)
(1...n).select{|i|i%3==0 or i%5==0}.sum
(1...n).select{|i|i%3==0 or i%5==0}.sum
end
end
puts sum35(1000) #=> 233168</lang>
puts sum35(1000) #=> 233168</syntaxhighlight>


Fast Version:
Fast Version:
<lang ruby># Given two integers n1,n2 return sum of multiples upto n3
<syntaxhighlight lang="ruby"># Given two integers n1,n2 return sum of multiples upto n3
#
#
# Nigel_Galloway
# Nigel_Galloway
Line 3,824: Line 4,240:


# For extra credit
# For extra credit
puts g(3,5,100000000000000000000-1)</lang>
puts g(3,5,100000000000000000000-1)</syntaxhighlight>


{{out}}
{{out}}
Line 3,834: Line 4,250:
Other way:
Other way:
{{trans|D}}
{{trans|D}}
<lang ruby>def sumMul(n, f)
<syntaxhighlight lang="ruby">def sumMul(n, f)
n1 = (n - 1) / f
n1 = (n - 1) / f
f * n1 * (n1 + 1) / 2
f * n1 * (n1 + 1) / 2
Line 3,845: Line 4,261:
for i in 1..20
for i in 1..20
puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)]
puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)]
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,872: Line 4,288:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>print multSum35(1000)
<syntaxhighlight lang="runbasic">print multSum35(1000)
end
end
function multSum35(n)
function multSum35(n)
Line 3,878: Line 4,294:
If (i mod 3 = 0) or (i mod 5 = 0) then multSum35 = multSum35 + i
If (i mod 3 = 0) or (i mod 5 = 0) then multSum35 = multSum35 + i
next i
next i
end function</lang><pre>233168</pre>
end function</syntaxhighlight><pre>233168</pre>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
extern crate rug;
extern crate rug;


Line 3,918: Line 4,334:
}
}
}
}
</syntaxhighlight>
</lang>
Output :
Output :
<pre>
<pre>
Line 3,931: Line 4,347:


</pre>
</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}}==
=={{header|Scala}}==
<lang scala>def sum35( max:BigInt ) : BigInt = max match {
<syntaxhighlight lang="scala">def sum35( max:BigInt ) : BigInt = max match {


// Simplest solution but limited to Ints only
// Simplest solution but limited to Ints only
Line 3,953: Line 4,394:
{
{
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 => 0
<pre> 1 => 0
Line 3,978: Line 4,419:


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000))</lang>
<syntaxhighlight lang="scheme">(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000))</syntaxhighlight>


Output:
Output:
Line 3,987: Line 4,428:
Or, more clearly by decomposition:
Or, more clearly by decomposition:


<lang scheme>(define (fac35? x)
<syntaxhighlight lang="scheme">(define (fac35? x)
(or (zero? (remainder x 3))
(or (zero? (remainder x 3))
(zero? (remainder x 5))))
(zero? (remainder x 5))))
Line 3,994: Line 4,435:
(+ tot (if (fac35? x) x 0)))
(+ tot (if (fac35? x) x 0)))


(fold fac35filt 0 (iota 1000))</lang>
(fold fac35filt 0 (iota 1000))</syntaxhighlight>


Output:
Output:
Line 4,003: Line 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!
For larger numbers iota can take quite a while just to build the list -- forget about waiting for all the computation to finish!


<lang scheme>(define (trisum n fac)
<syntaxhighlight lang="scheme">(define (trisum n fac)
(let* ((n1 (quotient (- n 1) fac))
(let* ((n1 (quotient (- n 1) fac))
(n2 (+ n1 1)))
(n2 (+ n1 1)))
Line 4,013: Line 4,454:
(fast35sum 1000)
(fast35sum 1000)
(fast35sum 100000000000000000000)
(fast35sum 100000000000000000000)
</syntaxhighlight>
</lang>


Output:
Output:
Line 4,022: Line 4,463:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigint.s7i";


Line 4,046: Line 4,487:
writeln(sum35(1000_));
writeln(sum35(1000_));
writeln(sum35(10_ ** 20));
writeln(sum35(10_ ** 20));
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,056: Line 4,497:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>func sumMul(n, f) {
<syntaxhighlight lang="ruby">func sumMul(n, f) {
var m = int((n - 1) / f)
var m = int((n - 1) / f)
f * m * (m + 1) / 2
f * m * (m + 1) / 2
Line 4,067: Line 4,508:
for i in (1..20) {
for i in (1..20) {
printf("%2s:%22s %s\n", i, 10**i, sum35(10**i))
printf("%2s:%22s %s\n", i, 10**i, sum35(10**i))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,094: Line 4,535:
=={{header|Simula}}==
=={{header|Simula}}==
(referenced from [[Greatest common divisor#Simula|Greatest common divisor]])
(referenced from [[Greatest common divisor#Simula|Greatest common divisor]])
<lang algol68>! Find the sum of multiples of two factors below a limit -
<syntaxhighlight 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;
! Project Euler problem 1: multiples of 3 or 5 below 1000 & 10**20;
BEGIN
BEGIN
Line 4,147: Line 4,588:
OUTIMAGE
OUTIMAGE
END
END
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
sum of positive multiples of 3 and 5: 233168<br />
sum of positive multiples of 3 and 5: 233168<br />
Line 4,160: Line 4,601:
=={{header|Stata}}==
=={{header|Stata}}==
=== With a dataset ===
=== With a dataset ===
<lang stata>clear all
<syntaxhighlight lang="stata">clear all
set obs 999
set obs 999
gen a=_n
gen a=_n
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)</lang>
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)</syntaxhighlight>


=== With Mata ===
=== With Mata ===
<lang stata>mata
<syntaxhighlight lang="stata">mata
a=1..999
a=1..999
sum(a:*(mod(a,3):==0 :| mod(a,5):==0))</lang>
sum(a:*(mod(a,3):==0 :| mod(a,5):==0))</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>
<syntaxhighlight lang="swift">




Line 4,192: Line 4,633:
print(sumofmult)
print(sumofmult)


</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl># Fairly simple version; only counts by 3 and 5, skipping intermediates
<syntaxhighlight lang="tcl"># Fairly simple version; only counts by 3 and 5, skipping intermediates
proc mul35sum {n} {
proc mul35sum {n} {
for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} {
for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} {
Line 4,211: Line 4,652:
}
}
return $total
return $total
}</lang>
}</syntaxhighlight>
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).
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).
<lang tcl># Smart version; no iteration so very scalable!
<syntaxhighlight lang="tcl"># Smart version; no iteration so very scalable!
proc tcl::mathfunc::triangle {n} {expr {
proc tcl::mathfunc::triangle {n} {expr {
$n * ($n+1) / 2
$n * ($n+1) / 2
Line 4,221: Line 4,662:
incr n -1
incr n -1
expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
}</lang>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<lang tcl>puts [mul35sum 1000],[sum35 1000]
<syntaxhighlight lang="tcl">puts [mul35sum 1000],[sum35 1000]
puts [mul35sum 10000000],[sum35 10000000]
puts [mul35sum 10000000],[sum35 10000000]
# Just the quick one; waiting for the other would get old quickly...
# Just the quick one; waiting for the other would get old quickly...
puts [sum35 100000000000000000000]</lang>
puts [sum35 100000000000000000000]</syntaxhighlight>
{{out}}
{{out}}
<pre>233168,233168
<pre>233168,233168
Line 4,233: Line 4,674:
</pre>
</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}}==
=={{header|VBA}}==
{{trans|VBScript}}
{{trans|VBScript}}
<lang vb>Private Function SumMult3and5VBScript(n As Double) As Double
<syntaxhighlight lang="vb">Private Function SumMult3and5VBScript(n As Double) As Double
Dim i As Double
Dim i As Double
For i = 1 To n - 1
For i = 1 To n - 1
Line 4,242: Line 4,948:
End If
End If
Next
Next
End Function</lang>
End Function</syntaxhighlight>
Other way :
Other way :
<lang vb>Private Function SumMult3and5(n As Double) As Double
<syntaxhighlight lang="vb">Private Function SumMult3and5(n As Double) As Double
Dim i As Double
Dim i As Double
For i = 3 To n - 1 Step 3
For i = 3 To n - 1 Step 3
Line 4,252: Line 4,958:
If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
Next
Next
End Function</lang>
End Function</syntaxhighlight>
Better way :
Better way :
<lang vb>Private Function SumMult3and5BETTER(n As Double) As Double
<syntaxhighlight lang="vb">Private Function SumMult3and5BETTER(n As Double) As Double
Dim i As Double
Dim i As Double
For i = 3 To n - 1 Step 3
For i = 3 To n - 1 Step 3
Line 4,265: Line 4,971:
SumMult3and5BETTER = SumMult3and5BETTER - i
SumMult3and5BETTER = SumMult3and5BETTER - i
Next
Next
End Function</lang>
End Function</syntaxhighlight>


Call :
Call :
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Sub Main()
Sub Main()
Line 4,280: Line 4,986:
Debug.Print "-------------------------"
Debug.Print "-------------------------"
Debug.Print SumMult3and5BETTER(1000)
Debug.Print SumMult3and5BETTER(1000)
End Sub</lang>
End Sub</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2,33333331666667E+15 9,059 sec.
<pre>2,33333331666667E+15 9,059 sec.
Line 4,291: Line 4,997:
=={{header|VBScript}}==
=={{header|VBScript}}==
{{trans|Run BASIC}}
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function multsum35(n)
Function multsum35(n)
For i = 1 To n - 1
For i = 1 To n - 1
Line 4,302: Line 5,008:
WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.WriteLine
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
<pre>
<pre>
F:\>cscript /nologo multsum35.vbs 1000
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
233168
</pre>
</pre>


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
sum35 ^(@sum \!-@(\~%%3 || \~%%5) @til)
sum35 ^(@sum \!-@(\~%%3 || \~%%5) @til)
!sum35 1000 ; returns 233168
!sum35 1000 ; returns 233168
}</lang>
}</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
===Simple version===
<lang ecmascript>var sum35 = Fn.new { |n|
<syntaxhighlight lang="wren">var sum35 = Fn.new { |n|
n = n - 1
n = n - 1
var s3 = (n/3).floor
var s3 = (n/3).floor
Line 4,329: Line 5,078:
}
}


System.print(sum35.call(1000))</lang>
System.print(sum35.call(1000))</syntaxhighlight>


{{out}}
{{out}}
<pre>
<pre>
233168
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>
</pre>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\stdlib;
<syntaxhighlight lang="xpl0">include c:\cxpl\stdlib;


func Sum1; \Return sum the straightforward way
func Sum1; \Return sum the straightforward way
Line 4,378: Line 5,187:
StrNSub(S, T, 40);
StrNSub(S, T, 40);
TextN(0, T, 40); CrLf(0);
TextN(0, T, 40); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,388: Line 5,197:


=={{header|Zig}}==
=={{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.
Inclusion/Exclusion mapping i64 -> i128 (largest integers supported in Zig natively)
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const std = @import("std");
const stdout = std.io.getStdOut().writer();


fn sumdiv(n: i64, d: i64) i128 {
fn DoubleWide(comptime n: anytype) type {
const Signedness = std.builtin.Signedness;
var m: i128 = @divFloor(n, d);
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;
return @divExact(m * (m + 1), 2) * d;
}
}


fn sum3or5(n: i64) i128 {
fn sum3or5(n: anytype) DoubleWide(n) {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}
}


pub fn main() !void {
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("The sum of the multiples of 3 and 5 below 1000 is {}\n", .{sum3or5(999)});

try stdout.print("The sum of the multiples of 3 and 5 below 1e18 is {}\n", .{sum3or5(999_999_999_999_999_999)});
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)});
}
}

</lang>
</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1e18 is 233333333333333333166666666666666668
The sum of the multiples of 3 and 5 below 1e20 is 2333333333333333333316666666666666666668

</pre>
</pre>
=={{header|zkl}}==
=={{header|zkl}}==
Brute force:
Brute force:
<lang zkl>[3..999,3].reduce('+,0) + [5..999,5].reduce('+,0) - [15..999,15].reduce('+,0)
<syntaxhighlight lang="zkl">[3..999,3].reduce('+,0) + [5..999,5].reduce('+,0) - [15..999,15].reduce('+,0)
233168</lang>
233168</syntaxhighlight>
{{trans|Groovy}}
{{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).
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).
<lang zkl>fcn sumMul(N,m){N=(N-1)/m; N*(N+1)*m/2}
<syntaxhighlight 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)}</lang>
fcn sum35(N){sumMul(N,3) + sumMul(N,5) - sumMul(N,15)}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 12:45, 26 April 2024

Task
Sum multiples of 3 and 5
You are encouraged to solve this task according to the task description, using any language you may know.
Task

The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.

Show output for n = 1000.

This is is the same as Project Euler problem 1.

Extra credit: do this efficiently for n = 1e20 or higher.

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))
Output:
233168

8th

Implements both the naive method and inclusion/exclusion.

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
Output:
The sum of the multiples of 3 or 5 below 1000 is 233168
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668

360 Assembly

*        Sum multiples of 3 and 5
SUM35    CSECT
         USING  SUM35,R13          base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R9,1               n=1
         LA     R7,7               do j=7 to 1 step -1
LOOPJ    MH     R9,=H'10'            n=n*10
         LR     R10,R9               n
         BCTR   R10,0                n-1
         ZAP    SUM,=PL8'0'          sum=0
         LA     R6,3                 i=3
       DO WHILE=(CR,R6,LE,R10)       do i=3 to n-1
         LR     R4,R6                  i
         SRDA   R4,32
         D      R4,=F'3'               i/3
         LTR    R4,R4                  if mod(i,3)=0
         BZ     CVD
         LR     R4,R6                  i
         SRDA   R4,32
         D      R4,=F'5'               i/5
         LTR    R4,R4                  if  mod(i,5)=0
         BNZ    ITERI
CVD      CVD    R6,IP                  ip=p
         AP     SUM,IP                 sum=sum+i
ITERI    LA     R6,1(R6)               i++
       ENDDO    ,                    enddo i
         XDECO  R9,PG                n
         MVC    PG+15(16),EM16       load mask
         ED     PG+15(16),SUM        packed dec (PL8) to char (CL16)
         XPRNT  PG,L'PG              print
         BCT    R7,LOOPJ           enddo j
         L      R13,4(0,R13)       restore previous savearea pointer
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
SUM      DS     PL8
IP       DS     PL8    		 
EM16     DC     X'40202020202020202020202020202120'  mask CL16 15num
PG       DC     CL80'123456789012 : 1234567890123456'
         YREGS
         END    SUM35
Output:
          10 :               23
         100 :             2318
        1000 :           233168
       10000 :         23331668
      100000 :       2333316668
     1000000 :     233333166668
    10000000 :   23333331666668

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
Output:

Screenshot from Atari 8-bit computer

233168

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;
Output:
n=1000:  233168
n=5e9 :  5833333329166666668

Extra Credit

Requires upcoming Ada 202x with big integer package.

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;
Output:
                               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

ALGOL 60

Works with: A60
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
Output:
 233168

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

Uses Algol 68G's LONG LONG INT to handle large numbers.

# 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
        # calculate the sum of the multiples of 3 below n #
        LONG LONG INT multiples of  3 = ( n - 1 ) OVER  3;
        LONG LONG INT multiples of  5 = ( n - 1 ) OVER  5;
        LONG LONG INT multiples of 15 = ( n - 1 ) OVER 15;
        ( # twice the sum of multiples of  3 #
          (  3 * multiples of  3 * ( multiples of  3 + 1 ) )
          # plus twice the sum of multiples of  5 #
        + (  5 * multiples of  5 * ( multiples of  5 + 1 ) )
          # less twice the sum of multiples of 15 #
        - ( 15 * multiples of 15 * ( multiples of 15 + 1 ) )
        ) OVER 2
    END # sum of multiples of 3 and 5 below # ;

print( ( "Sum of multiples of 3 and 5 below 1000: "
       , whole( sum of multiples of 3 and 5 below( 1000 ), 0 )
       , newline 
       )
     );
print( ( "Sum of multiples of 3 and 5 below 1e20: "
       , whole( sum of multiples of 3 and 5 below( 100 000 000 000 000 000 000 ), 0 )
       , newline 
       )
     )
Output:
Sum of multiples of 3 and 5 below 1000: 233168
Sum of multiples of 3 and 5 below 1e20: 2333333333333333333316666666666666666668

APL

Dyalog APL

Sum  +/∘1<15∨⍳
Output:
      Sum 999
233168

ngn/APL

⎕IO0
{+/((0=3|a)0=5|a)/a} 1000

run

Output:
233168

AppleScript

Translation of: JavaScript
----------------- SUM MULTIPLES OF 3 AND 5 -----------------

-- sum35 :: Int -> Int
on sum35(n)
    tell sumMults(n)
        |λ|(3) + |λ|(5) - |λ|(15)
    end tell
end sum35



-- sumMults :: Int -> Int -> Int
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 ---------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m > n then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:

101 -> 23
102 -> 2318
103 -> 233168
104 -> 23331668
105 -> 2.333316668E+9
106 -> 2.33333166668E+11
107 -> 2.333333166667E+13
108 -> 2.333333316667E+15

Arturo

sumMul35: function [n][
	sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]

print sumMul35 1000
Output:
233168

AutoHotkey

n := 1000

msgbox % "Sum is " . Sum3_5(n)   . " for n = " . n
msgbox % "Sum is " . Sum3_5_b(n) . " for n = " . n

;Standard simple Implementation.
Sum3_5(n) {
	sum := 0
	loop % n-1 {
		if (!Mod(a_index,3) || !Mod(a_index,5))
		sum:=sum+A_index
	}
	return sum
}

;Translated from the C++ version.
Sum3_5_b( i ) {
	sum := 0, a := 0
	while (a < 28)
	{
		if (!Mod(a,3) || !Mod(a,5))
		{
			sum += a
			s := 30
			while (s < i)
			{
				if (a+s < i)
					sum += (a+s)
				s+=30
			}
		}
		a+=1
	}
	return sum
}

Output:

Sum is 233168 for n = 1000
Sum is 233168 for n = 1000

AWK

Save this into file "sum_multiples_of3and5.awk"

#!/usr/bin/awk -f
{ 
	n = $1-1;
	print sum(n,3)+sum(n,5)-sum(n,15);
}
function sum(n,d) {
	m = int(n/d);
	return (d*m*(m+1)/2);
}
Output:
$ echo 1000 |awk -f sum_multiples_of3and5.awk 
233168

Extra credit

Works with: Gawk version 4.1

In Awk, all numbers are represented internally as double precision floating-point numbers. Thus the result for the extra credit is unprecise. Since version 4.1, GNU Awk supports high precision arithmetic (using GNU MPFR and GMP) which is turned on with the -M / --bignum option. The variable PREC sets the working precision for arithmetic operations (here 80 bits):

$ echo -e "1000\n1e20" | gawk -M -v PREC=80 -f sum_multiples_of3and5.awk 
233168
2333333333333333333316666666666666666668

BASIC

Works with: FreeBASIC
Declare function mulsum35(n as integer) as integer
Function mulsum35(n as integer) as integer
    Dim s as integer
    For i as integer = 1 to n - 1
        If (i mod 3 = 0) or (i mod 5 = 0) then
            s += i
        End if
    Next i
    Return s
End Function
Print mulsum35(1000)
Sleep
End
Output:
233168

Applesoft BASIC

 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

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

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
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

Gambas

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
Output:
Same as FreeBASIC entry.

GW-BASIC

Works with: Applesoft BASIC
Works with: Chipmunk Basic
Works with: MSX BASIC version any
Works with: PC-BASIC version any
Works with: 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

Minimal BASIC

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

MSX Basic

See GW-BASIC.

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)

True BASIC

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

Quite BASIC

See GW-BASIC.

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

IS-BASIC

100 PRINT MULTSUM35(1000)
110 DEF MULTSUM35(N)
120   LET S=0
130   FOR I=1 TO N-1
140     IF MOD(I,3)=0 OR MOD(I,5)=0 THEN LET S=S+I
150   NEXT
160   LET MULTSUM35=S
170 END DEF

Sinclair ZX81 BASIC

Works with 1k of RAM.

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 is divisible by 5 if we already know it's divisible by 3. (ZX81 BASIC doesn't do this automatically: both sides of an OR are evaluated, even if we don't need the second one.) Even so, with = 1000 the performance is pretty acceptable.

 10 INPUT N
 20 FAST
 30 LET SUM=0
 40 FOR I=3 TO N-1
 50 IF I/3=INT (I/3) THEN GOTO 70
 60 IF I/5<>INT (I/5) THEN GOTO 80
 70 LET SUM=SUM+I
 80 NEXT I
 90 SLOW
100 PRINT SUM
Input:
1000
Output:
233168

bc

Translation of: Groovy
define t(n, f) {
    auto m

    m = (n - 1) / f
    return(f * m * (m + 1) / 2)
}

define s(l) {
    return(t(l, 3) + t(l, 5) - t(l, 15))
}

s(1000)
s(10 ^ 20)
Output:
233168
2333333333333333333316666666666666666668

BCPL

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.

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
}
Output:
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

Befunge

Slow (iterative) version:

&1-:!#v_:3%#v_     >:>#
      >+\:v >:5%#v_^
  @.$_^#! <      >   ^
Output:
233168

Fast (analytic) version:

&1-::3/:1+*3*2/\5/:1+*5*2/+\96+/:1+*96+*2/-.@
Output:
233168

BQN

A naive solution:

Sum  +´·(0=3|⌊5|)/↕

A much faster solution:

Sum  {
  m  (0=3|⌊5|)15  hl  15(÷˜∾|)𝕩
  (+´lm×15(×+↕)h) + (15×(+´m)×2÷˜h×h-1) + h×+´m×↕15
}
Output:
   Sum 1000
233168

(online REPL)

C

Simple version

#include <stdio.h>
#include <stdlib.h>

unsigned long long sum35(unsigned long long limit)
{
    unsigned long long sum = 0;
    for (unsigned long long i = 0; i < limit; i++)
        if (!(i % 3) || !(i % 5))
            sum += i;
    return sum;
}

int main(int argc, char **argv)
{
    unsigned long long limit;

    if (argc == 2)
        limit = strtoull(argv[1], NULL, 10);
    else
        limit = 1000;

    printf("%lld\n", sum35(limit));
    return 0;
}
Output:
$ ./a.out
233168
$ ./a.out 12345
35553600

Fast version with arbitrary precision

Library: GMP
#include <stdio.h>
#include <gmp.h>

void sum_multiples(mpz_t result, const mpz_t limit, const unsigned f)
{
    mpz_t m;
    mpz_init(m);
    mpz_sub_ui(m, limit, 1);
    mpz_fdiv_q_ui(m, m, f);

    mpz_init_set(result, m);
    mpz_add_ui(result, result, 1);
    mpz_mul(result, result, m);
    mpz_mul_ui(result, result, f);
    mpz_fdiv_q_2exp(result, result, 1);

    mpz_clear(m);
}

int main(int argc, char **argv)
{
    mpf_t temp;
    mpz_t limit;

    if (argc == 2)
    {
        mpf_init_set_str(temp, argv[1], 10);
        mpz_init(limit);
        mpz_set_f(limit, temp);
        mpf_clear(temp);
    }
    else
        mpz_init_set_str(limit, "1000000000000000000000", 10);

    mpz_t temp_sum;
    mpz_t sum35;
    
    mpz_init(temp_sum);
    sum_multiples(temp_sum, limit, 3);
    mpz_init_set(sum35, temp_sum);
    sum_multiples(temp_sum, limit, 5);
    mpz_add(sum35, sum35, temp_sum);
    sum_multiples(temp_sum, limit, 15);
    mpz_sub(sum35, sum35, temp_sum);

    mpz_out_str(stdout, 10, sum35);
    puts("");

    mpz_clear(temp_sum);
    mpz_clear(sum35);
    mpz_clear(limit);
    return 0;
}
Output:
$ ./a.out 
233333333333333333333166666666666666666668
$ ./a.out 23e45
123433333333333333333333333333333333333333333314166666666666666666666666666666666666666666668

C#

The following C# 5 / .Net 4 code is an efficient solution 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 faster to conduct the calculation for smaller values with native ("primitive") types using a 'brute force' iteration approach.

using System;
using System.Collections.Generic;
using System.Numerics;

namespace RosettaCode
{
    class Program
    {
        static void Main()
        {
            List<BigInteger> candidates = new List<BigInteger>(new BigInteger[] { 1000, 100000, 10000000, 10000000000, 1000000000000000 });
            candidates.Add(BigInteger.Parse("100000000000000000000"));

            foreach (BigInteger candidate in candidates)
            {
                BigInteger c = candidate - 1;
                BigInteger answer3 = GetSumOfNumbersDivisibleByN(c, 3);
                BigInteger answer5 = GetSumOfNumbersDivisibleByN(c, 5);
                BigInteger answer15 = GetSumOfNumbersDivisibleByN(c, 15);

                Console.WriteLine("The sum of numbers divisible by 3 or 5 between 1 and {0} is {1}", c, answer3 + answer5 - answer15);
            }

            Console.ReadKey(true);
        }

        private static BigInteger GetSumOfNumbersDivisibleByN(BigInteger candidate, uint n)
        {
            BigInteger largest = candidate;
            while (largest % n > 0)
                largest--;
            BigInteger totalCount = (largest / n);
            BigInteger pairCount = totalCount / 2;
            bool unpairedNumberOnFoldLine = (totalCount % 2 == 1);
            BigInteger pairSum = largest + n;
            return pairCount * pairSum + (unpairedNumberOnFoldLine ? pairSum / 2 : 0);
        }

    }
}
Output:

The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168

The sum of numbers divisible by 3 or 5 between 1 and 99999 is 2333316668

The sum of numbers divisible by 3 or 5 between 1 and 9999999 is 23333331666668

The sum of numbers divisible by 3 or 5 between 1 and 9999999999 is 23333333331666666668

The sum of numbers divisible by 3 or 5 between 1 and 999999999999999 is 233333333333333166666666666668

The sum of numbers divisible by 3 or 5 between 1 and 99999999999999999999 is 2333333333333333333316666666666666666668

C++

#include <iostream>

//--------------------------------------------------------------------------------------------------
typedef unsigned long long bigInt;

using namespace std;
//--------------------------------------------------------------------------------------------------
class m35
{
public:
    void doIt( bigInt i )
    {
	bigInt sum = 0;
	for( bigInt a = 1; a < i; a++ )
	    if( !( a % 3 ) || !( a % 5 ) ) sum += a;

	cout << "Sum is " << sum << " for n = " << i << endl << endl;
    }
	
    // this method uses less than half iterations than the first one
    void doIt_b( bigInt i )
    {
	bigInt sum = 0;
	for( bigInt a = 0; a < 28; a++ )
	{
	    if( !( a % 3 ) || !( a % 5 ) )
	    {
		sum += a;
		for( bigInt s = 30; s < i; s += 30 )
		    if( a + s < i ) sum += ( a + s );

	    }
	}
	cout << "Sum is " << sum << " for n = " << i << endl << endl;
    }
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    m35 m; m.doIt( 1000 );
    return system( "pause" );
}
Output:
Sum is 233168 for n = 1000

Fast version with arbitrary precision

Library: Boost
#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';
}
Output:
233168
2333333333333333333316666666666666666668

Clojure

Quick, concise way:

(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))

Transducers approach:

(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))

Or optimized (translated from Groovy):

(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))

COBOL

Using OpenCOBOL.

Identification division.
Program-id. three-five-sum.

Data division.
Working-storage section.
01 ws-the-limit  pic 9(18) value 1000.
01 ws-the-number pic 9(18).
01 ws-the-sum    pic 9(18).
01 ws-sum-out    pic z(18).

Procedure division.
Main-program.
    Perform Do-sum
        varying ws-the-number from 1 by 1 
        until ws-the-number = ws-the-limit.
    Move ws-the-sum to ws-sum-out.
    Display "Sum = " ws-sum-out.
    End-run.

Do-sum.
    If function mod(ws-the-number, 3) = zero
       or function mod(ws-the-number, 5) = zero
       then add ws-the-number to ws-the-sum.

Output:

Sum =             233168

Using triangular numbers:

Identification division.
Program-id. three-five-sum-fast.

Data division.
Working-storage section.
01 ws-num     pic 9(18) value 1000000000.
01 ws-n5      pic 9(18).
01 ws-n3      pic 9(18).
01 ws-n15     pic 9(18).
01 ws-sum     pic 9(18).
01 ws-out.
    02 ws-out-num pic z(18).
    02 filler pic x(3) value " = ".
    02 ws-out-sum pic z(18).

Procedure division.
Main-program.
    Perform
        call "tri-sum" using ws-num 3  by reference ws-n3
        call "tri-sum" using ws-num 5  by reference ws-n5
        call "tri-sum" using ws-num 15  by reference ws-n15
    end-perform.
    Compute ws-sum = ws-n3 + ws-n5 - ws-n15.
    Move ws-sum to ws-out-sum.
    Move ws-num to ws-out-num.
    Display ws-out.



Identification division.
Program-id. tri-sum.

Data division.
Working-storage section.
01 ws-n1 pic 9(18).
01 ws-n2 pic 9(18).

Linkage section.
77 ls-num pic 9(18).
77 ls-fac pic 9(18).
77 ls-ret pic 9(18).

Procedure division using ls-num, ls-fac, ls-ret.
    Compute ws-n1 = (ls-num - 1) / ls-fac.
    Compute ws-n2 = ws-n1 + 1.
    Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2.
    goback.

Output:

        1000000000 = 233333333166666668


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)

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SUM35.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  THREE-COUNTER   USAGE BINARY-CHAR value 1.
           88 IS-THREE VALUE 3.
       01  FIVE-COUNTER    USAGE BINARY-CHAR value 1.
           88 IS-FIVE VALUE 5.
       01  SUMMER          USAGE BINARY-DOUBLE value zero. 
       01  I               USAGE BINARY-LONG.
       01  N               USAGE BINARY-LONG.

       PROCEDURE DIVISION.
       10-MAIN-PROCEDURE.
           MOVE 1000000000 TO N.
           MOVE 1 TO I.
           PERFORM 20-INNER-LOOP WITH TEST AFTER UNTIL I >= N.
           DISPLAY SUMMER.
           STOP RUN.
       20-INNER-LOOP.
           IF IS-THREE OR IS-FIVE 
               ADD I TO SUMMER END-ADD
               IF IS-THREE
                   MOVE 1 TO THREE-COUNTER
               ELSE
                   ADD 1 TO THREE-COUNTER
               END-IF
               IF IS-FIVE
                   MOVE 1 TO FIVE-COUNTER
               ELSE    
                   ADD 1 TO FIVE-COUNTER
               END-IF
           ELSE
               ADD 1 TO FIVE-COUNTER END-ADD
               ADD 1 TO THREE-COUNTER END-ADD
           END-IF.
           ADD 1 TO I.
           EXIT.
       END PROGRAM SUM35.

Output

+00233333333166666668

Common Lisp

Slow, naive version:

(defun sum-3-5-slow (limit)
  (loop for x below limit
        when (or (zerop (rem x 3)) (zerop (rem x 5)))
          sum x))

Fast version (adapted translation of Tcl):

(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)))))))
Output:
> (values (sum-3-5-slow 1000) (sum-3-5-fast 1000))
233168 ;
233168
> (sum-3-5-fast 1000000000000000000000)
233333333333333333333166666666666666666668

Component Pascal

BlackBox Component Builder

MODULE Sum3_5;
IMPORT StdLog, Strings, Args;

PROCEDURE DoSum(n: INTEGER):INTEGER;
VAR
	i,sum: INTEGER;
BEGIN
	sum := 0;i := 0;
	WHILE (i < n) DO
		IF  (i MOD 3 = 0) OR (i MOD 5 = 0) THEN INC(sum,i) END;
		INC(i)
	END;
	RETURN sum
END DoSum;

PROCEDURE Compute*;
VAR
	params: Args.Params;
	i,n,res: INTEGER;
BEGIN
	Args.Get(params);
	Strings.StringToInt(params.args[0],n,res);
	StdLog.String("Sum: ");StdLog.Int(DoSum(n)); StdLog.Ln
END Compute;

END Sum3_5.

Execute: ^Q Sum3_5.Compute 1000 ~
Output:

Sum:  233168

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();
Output:
Naive method: 233168
Fast method:  233168

Crystal

Translation of: Ruby

Short, but not optimized.

def sum_3_5_multiples(n)
  (0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end

puts sum_3_5_multiples(1000)
Output:
233168

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.

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)
Output:
232169
233168
2333333333333333333216666666666666666669
2333333333333333333316666666666666666668

Alternative faster version 2.

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
Output:
 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

D

import std.stdio, std.bigint;

BigInt sum35(in BigInt n) pure nothrow {
    static BigInt sumMul(in BigInt n, in int f) pure nothrow {
        immutable n1 = (f==n?n:(n - 1) ) / f;
        return f * n1 * (n1 + 1) / 2;
    }

    return sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15);
}

void main() {
    1.BigInt.sum35.writeln;
    3.BigInt.sum35.writeln;
    5.BigInt.sum35.writeln;
    1000.BigInt.sum35.writeln;
    (10.BigInt ^^ 20).sum35.writeln;
}
Output:
0
3
8
233168
2333333333333333333316666666666666666668

dc

[ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm

[ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss

[ 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
Output:
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

Delphi

program sum35;

{$APPTYPE CONSOLE}

var
  sum: integer;
  i: integer;

function isMultipleOf(aNumber, aDivisor: integer): boolean;
begin
  result := aNumber mod aDivisor = 0
end;

begin
  sum := 0;
  for i := 3 to 999 do
  begin
    if isMultipleOf(i, 3) or isMultipleOf(i, 5) then
      sum := sum + i;
  end;
  writeln(sum);
end.
Output:
233168

Déjà Vu

sum-divisible n:
	0
	for i range 1 -- n:
		if or = 0 % i 3 = 0 % i 5:
			+ i

!. sum-divisible 1000
Output:
233168

EasyLang

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

EchoLisp

(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when

(define (task n  (k 3)  (p 5 ))
	 (when (!= (gcd k p) 1) (error "expected coprimes" (list k p)))
		(- 
	 	(+ (sum/mults n k) (sum/mults n p)) ;; add multiples of k , multiples of p
	 	(sum/mults n (* k p)))) ;; remove multiples of k * p

;; using sequences
;; sum of multiples of k < n 

(define (sum/mults n k)
	(sum/when (rcurry divides? k) [1 .. n]))

(task 1000 3 5)
     233168

;; using simple arithmetic - 🎩 young Gauss formula
;; sum of multiples of k < n  = 
;; k*m*(m+1)/2 where m = floor(n/k)
(lib 'bigint)

(define (sum/mults n k)
	(set! n (quotient (1- n) k))
	(/ (* k n (1+ n )) 2))

(task 1e20 3 5)
     2333333333333333333316666666666666666668

(task 1000 42 666)
     error: expected coprimes (42 666)

Eiffel

class
	APPLICATION

create
	make

feature {NONE}

	make
		do
			io.put_integer (sum_multiples (1000))
		end

	sum_multiples (n: INTEGER): INTEGER
			-- Sum of all positive multiples of 3 or 5 below 'n'.
		do
			across
				1 |..| (n - 1) as c
			loop
				if c.item \\ 3 = 0 or c.item \\ 5 = 0 then
					Result := Result + c.item
				end
			end
		end

end
Output:
233168

Elixir

Simple (but slow)

iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum
233168

Fast version:

Translation of: Ruby
defmodule RC do
  def sumMul(n, f) do
    n1 = div(n - 1, f)
    div(f * n1 * (n1 + 1), 2)
  end
  
  def sum35(n) do
    sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15)
  end
end

Enum.each(1..20, fn i ->
  n = round(:math.pow(10, i))
  IO.puts RC.sum35(n)
end)
Output:
23
2318
233168
23331668
2333316668
233333166668
23333331666668
2333333316666668
233333333166666668
23333333331666666668
2333333333316666666668
233333333333166666666668
23333333333331666666666668
2333333333333316666666666668
233333333333333166666666666668
23333333333333331666666666666668
2333333333333333316666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668
2333333333333333333316666666666666666668

Emacs Lisp

Vanilla:

(defun sum-3-5 (n)
  (let ((sum 0))
    (dotimes (x n)
      (when (or (zerop (% x 3)) (zerop (% x 5)))
        (setq sum (+ sum x))))
    sum))
Library: seq.el
(defun sum-3-5 (n)
  (apply #'+ (seq-filter
	      (lambda (x) (or (zerop (% x 3) ) (zerop (% x 5))))
	      (number-sequence 1 (- n 1)))))

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 ->
  sum_3_5(X-1, Total+X);
sum_3_5(X, Total) ->
  sum_3_5(X-1, Total).

io:format("~B~n", [sum_3_5(1000)]).
Output:
233168

F#

let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)

printfn "%d" (sum35 1000)
printfn "----------"

let sumUpTo (n : bigint) = n * (n + 1I) / 2I

let sumMultsBelow k n = k * (sumUpTo ((n-1I)/k))

let sum35fast n = (sumMultsBelow 3I n) + (sumMultsBelow 5I n) - (sumMultsBelow 15I n)

[for i = 0 to 30 do yield i]
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))
Output:
233168
----------
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

Factor

This solution is based on the following formula to find the sum of an arithmetic sequence:

n/2 * (2 * a + (n - 1) * d)

    where

  • a is the first term
  • d is the common difference between terms
  • n is how many terms to add up


Works with: Factor version 0.99 2019-10-06
USING: kernel math prettyprint ;

: sum-multiples ( m n upto -- sum )
    >integer 1 - [ 2dup * ] dip
    [ 2dup swap [ mod - + ] [ /i * 2/ ] 2bi ] curry tri@
    [ + ] [ - ] bi* ;

3 5 1000 sum-multiples .
3 5 1e20 sum-multiples .
Output:
233168
2333333333333333333316666666666666666668

FBSL

Derived from BASIC version

#APPTYPE CONSOLE

FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
    DIM sum AS INTEGER
    FOR DIM i = 1 TO n - 1
        IF (NOT (i MOD 3)) OR (NOT (i MOD 5)) THEN
            INCR(sum, i)
        END IF
    NEXT
    RETURN sum
END FUNCTION

PRINT sumOfThreeFiveMultiples(1000)
PAUSE

Output

233168

Press any key to continue...

Forth

: main ( n -- )
  0 swap
  3 do
    i 3 mod 0= if
      i +
    else i 5 mod 0= if
      i +
    then then
  loop
  . ;

1000 main    \ 233168  ok

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.

: third  2 pick ;

: >dtriangular ( n -- d )
    dup 1+ m* d2/ ;

: sumdiv ( n m -- d )
    dup >r / >dtriangular r> 1 m*/ ;

: sumdiv_3,5 ( n -- n )
    dup 3 sumdiv third 5 sumdiv d+ rot 15 sumdiv d- ;

: euler1 ( -- n )
    999 sumdiv_3,5 drop ;

: euler1tower ( -- )
    1  \ power of 10
    19 0 DO
        cr dup 19 .r space dup 1- sumdiv_3,5 d.
        10 *
    LOOP drop ;

euler1 . 233168  ok
euler1tower 
                  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  ok

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 END FUNCTION name protocol that F90 does, but such documentation enables compiler checks and not using it makes me wince.

      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.
       INTEGER*8 N	!The number. Possibly large.
        IF (MOD(N,2).EQ.0) THEN	!So, I'm worried about overflow with N*(N + 1)
          SUMI = N/2*(N + 1)		!But since N is even, N/2 is good.
         ELSE			!Otherwise, if N is odd,
          SUMI = (N + 1)/2*N		!(N + 1) must be even.
        END IF			!Either way, the /2 reduces the result.
      END FUNCTION SUMI		!So overflow of intermediate results is avoided.

      INTEGER*8 FUNCTION SUMF(N,F)	!Sum of numbers up to N divisible by F.
       INTEGER*8 N,F		!The selection.
       INTEGER*8 L		!The last in range. N itself is excluded.
       INTEGER*8 SUMI		!Known type of the function.
        L = (N - 1)/F		!Truncates fractional parts.
        SUMF = F*SUMI(L)	!3 + 6 + 9 + ... = 3(1 + 2 + 3 + ...)
      END FUNCTION SUMF		!Could just put SUMF = F*SUMI((N - 1)/F).

      INTEGER*8 FUNCTION SUMBFI(N)	!Brute force and ignorance summation.
       INTEGER*8 N	!The number.
       INTEGER*8 I,S	!Stepper and counter.
        S = 0		!So, here we go.
        DO I = 3,N - 1	!N itself is not a candidate.
          IF (MOD(I,3).EQ.0 .OR. MOD(I,5).EQ.0) S = S + I	!Whee!
        END DO		!On to the next.
        SUMBFI = S		!The result.
      END FUNCTION SUMBFI	!Oh well, computers are fast these days.

      INTEGER*8 SUMF,SUMBFI	!Known type of the function.
      INTEGER*8 N	!The number.
      WRITE (6,*) "Sum multiples of 3 and 5 up to N"
   10 WRITE (6,11)		!Ask nicely.
   11 FORMAT ("Specify N: ",$)	!Obviously, the $ says 'stay on this line'.
      READ (5,*) N		!If blank input is given, further input will be requested.
      IF (N.LE.0) STOP		!Good enough.
      WRITE (6,*) "By Gauss:",SUMF(N,3) + SUMF(N,5) - SUMF(N,15)
      WRITE (6,*) "BFI sum :",SUMBFI(N)		!This could be a bit slow.
      GO TO 10			!Have another go.
      END	!So much for that.

Sample output:

 Sum multiples of 3 and 5 up to N
Specify N: 1000
 By Gauss:                233168
 BFI sum :                233168
Specify N: 1001
 By Gauss:                234168
 BFI sum :                234168
Specify N: 1002
 By Gauss:                234168
 BFI sum :                234168
Specify N: 1003
 By Gauss:                235170
 BFI sum :                235170
Specify N: 1000000000
 By Gauss:    233333333166666668
 BFI sum :    233333333166666668

The result for a thousand million took about a minute for the brute-force-and-ignorance calculation. For much larger values of N, it should be discarded! Integer overflow even for 64-bit integers impends. The calculations could be conducted in double precision (or better, quadruple precision), a trivial modification to the source. Precise results would require the introduction of multi-precision arithmetic.

FreeBASIC

' FB 1.05.0 Win64

Function sum35 (n As UInteger) As UInteger
  If n = 0 Then Return 0
  Dim As UInteger i, sum = 0
  For i = 1 To n
    If (i Mod 3 = 0) OrElse (i Mod 5 = 0) Then sum += i
  Next
  Return sum 
End Function

Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; sum35(999)
Print
Print "Press any key to quit"
Sleep
Output:
Sum of positive integers below 1000 divisible by 3 or 5 is : 233168

Frink

Program has a brute-force approach for n=1000, and also inclusion/exclusion for larger values.

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]]
Output:
The sum of all the multiples of 3 or 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668

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
Output:
233168

Go

package main

import "fmt"

func main() {
    fmt.Println(s35(1000))
}

func s35(n int) int {
    n--
    threes := n / 3
    fives := n / 5
    fifteen := n / 15

    threes = 3 * threes * (threes + 1)
    fives = 5 * fives * (fives + 1)
    fifteen = 15 * fifteen * (fifteen + 1)

    n = (threes + fives - fifteen) / 2
	
    return n
}
Output:
233168

Extra credit:

package main

import (
    "fmt"
    "math/big"
)

var (
    b1  = big.NewInt(1)
    b3  = big.NewInt(3)
    b5  = big.NewInt(5)
    b10 = big.NewInt(10)
    b15 = big.NewInt(15)
    b20 = big.NewInt(20)
)

func main() {
    fmt.Println(s35(new(big.Int).Exp(b10, b3, nil)))
    fmt.Println(s35(new(big.Int).Exp(b10, b20, nil)))
}

func s35(i *big.Int) *big.Int {
    j := new(big.Int).Sub(i, b1)
    sum2 := func(d *big.Int) *big.Int {
        n := new(big.Int).Quo(j, d)
        p := new(big.Int).Add(n, b1)
        return p.Mul(d, p.Mul(p, n))
    }
    s := sum2(b3)
    return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1)
}
Output:
233168
2333333333333333333316666666666666666668

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) }

Test Code:

[(1000): 233168, (10e20): 233333333333333333333166666666666666666668].each { arg, value ->
    println "Checking $arg == $value"
    assert sum35(arg) == value
}
Output:
Checking 1000 == 233168
Checking 1.0E+21 == 233333333333333333333166666666666666666668

Haskell

Also a method for calculating sum of multiples of any list of numbers.

import Data.List (nub)

----------------- SUM MULTIPLES OF 3 AND 5 ---------------

sum35 :: Integer -> Integer
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


--------------------------- TEST -------------------------
main :: IO ()
main =
  mapM_
    print
    [ sum35 1000,
      sum35 100000000000000000000000000000000,
      sumMulS 1000 [3, 5],
      sumMulS 10000000 [2, 3, 5, 7, 11, 13]
    ]

---------------- 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
Output:
233168
2333333333333333333333333333333316666666666666666666666666666668
233168
41426953573049

Icon and Unicon

The following works in both langauges.

procedure main(A)
    n := (integer(A[1]) | 1000)-1
    write(sum(n,3)+sum(n,5)-sum(n,15))
end

procedure sum(n,m)
    return m*((n/m)*(n/m+1)/2)
end

Sample output:

->sm35
233168
->sm35 100000000000000000000
2333333333333333333316666666666666666668
->

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.

NB. Naive method
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.
echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)

NB. slightly less naive: select the numbers which have no remainder when divided by 3 or 5:
echo 'The sum of the multiples of 3 or 5 < 1000 is still ', ": +/I.+./0=3 5|/i.1000



NB. inclusion/exclusion

triangular =: -:@:(*: + 1&*)
sumdiv =: dyad define
    (triangular <. x % y) * y
)

echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
Output:
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

Java

Simple Version

class SumMultiples {
	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));
	}
}
Output:
233168

Extra Credit

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;
    }

}
Output:
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

JavaScript

ES5

JavaScript is better equipped for flexibility than for scale. The value of

 Number.MAX_SAFE_INTEGER

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 …

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:

(function (lstFactors, intExponent) {

    // [n] -> n -> n
    function sumMultiplesBelow(lstIntegers, limit) {
        return range(1, limit - 1).filter(function (x) {
            return isMultiple(lstIntegers, x);
        }).reduce(function (a, n) {
            return a + n;
        }, 0)
    }

    // [n] -> n -> bool
    function isMultiple(lst, n) {
        var i = lng;
        while (i--)
            if (n % (lst[i]) === 0) return true;
        return false;
    }

    // [m..n]
    function range(m, n) {
        var a = Array(n - m + 1),
            i = n + 1;
        while (i--) a[i - 1] = i;
        return a;
    }


    /*      TESTING     */

    // [[a]] -> bool -> s -> s
    function wikiTable(lstRows, blnHeaderRow, strStyle) {
        return '{| class="wikitable" ' + (
            strStyle ? 'style="' + strStyle + '"' : ''
        ) + lstRows.map(function (lstRow, iRow) {
            var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');

            return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
                return typeof v === 'undefined' ? ' ' : v;
            }).join(' ' + strDelim + strDelim + ' ');
        }).join('') + '\n|}';
    }

    var lng = lstFactors.length,
        lstSorted = lstFactors.slice(0).sort();

    var lstTable = [['Below', 'Sum']].concat(
        range(1, intExponent).map(function (x) {
            var pwr = Math.pow(10, x);

            return ['10^' + x, sumMultiplesBelow(lstSorted, pwr)];
        })
    );

    return 'For ' + JSON.stringify(lstFactors) + ':\n\n' +
        wikiTable(lstTable, true) + '\n\n' +
        JSON.stringify(lstTable);

})([3, 5], 8);


For [3,5]:

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
 [["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]]

With wheel increments

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
}

With triangular numbers

function sm35(n){
	return tri(n,3) + tri(n,5) - tri(n,15)
	function tri(n, f) {
		n = Math.floor((n-1) / f)
		return f * n * (n+1) / 2
	}
}

This:

for (var i=1, n=10; i<9; n*=10, i+=1) {
	document.write(10, '<sup>', i, '</sup> ',  sm35(n), '<br>')
}
Output:
101 23
102 2318
103 233168
104 23331668
105 2333316668
106 233333166668
107 23333331666668
108 2333333316666668


ES6

(() => {

    // 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);
    };


    // sumMults :: Int -> Int -> Int
    const sumMults = n =>
        // Area under straight line
        // between first multiple and last.
        factor => {
            const n1 = quot(n - 1)(factor);
            return quot(factor * n1 * (n1 + 1))(2);
        };

    // ------------------------- TEST --------------------------

    // 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 ------------------------

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m =>
        n => !isNaN(m) ? (
            Array.from({
                length: 1 + n - m
            }, (_, i) => m + i)
        ) : enumFromTo_(m)(n);


    // quot :: Int -> Int -> Int
    const quot = n =>
        m => Math.floor(n / m);


    // ------------------------ DISPLAY ------------------------

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        // A function defined by the right-to-left
        // composition of all the functions in fs.
        fs.reduce(
            (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();
})();
Output:
Sums for n = 10^1 thru 10^8:
       10 -> 23
      100 -> 2318
     1000 -> 233168
    10000 -> 23331668
   100000 -> 2333316668
  1000000 -> 233333166668
 10000000 -> 23333331666668
100000000 -> 2333333316666668

Joy

DEFINE divisor == rem 0 = ;
       mul3or5 == [3 divisor] [5 divisor] cleave or ;
       when == swap [] ifte .

"The sum of the multiples of 3 or 5 below 1000 is " putchars

0 999 [0 =] [pop]
[
   [dup rollup + swap] [mul3or5] when
   pred
] tailrec .
Output:
The sum of the multiples of 3 or 5 below 1000 is 233168

jq

def sum_multiples(d):
 ((./d) | floor) |  (d * . * (.+1))/2 ;

# Sum of multiples of a or b that are less than . (the input)
def task(a;b):
 . - 1
 | sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);

Examples:

jq does not (yet) support arbitrary-precision integer arithmetic but converts large integers to floats, so:

1000 | task(3;5)  # => 233168

10e20 | task(3;5) # => 2.333333333333333e+41


Julia

sum multiples of each, minus multiples of the least common multiple (lcm). Similar to MATLAB's version.

multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)

Output:

julia> multsum(3, 5, 1000)
233168

julia> multsum(3, 5, BigInt(10)^20)
2333333333333333333316666666666666666668

julia> @time multsum(3, 5, BigInt(10)^20)
elapsed time: 5.8114e-5 seconds seconds (3968 bytes allocated)
2333333333333333333316666666666666666668

julia> [(BigInt(10)^n, multsum(3, 5, BigInt(10)^n)) for n=0:20]
21-element Array{(BigInt,BigInt),1}:
 (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)

a slightly more efficient version

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)

Kotlin

// version 1.1.2

import java.math.BigInteger

val big2  = BigInteger.valueOf(2)
val big3  = BigInteger.valueOf(3)
val big5  = BigInteger.valueOf(5)
val big15 = big3 * big5

fun sum35(n: Int) = (3 until n).filter { it % 3 == 0 || it % 5 == 0}.sum()

fun sum35(n: BigInteger): BigInteger {
    val nn    = n - BigInteger.ONE
    val num3  = nn / big3
    val end3  = num3 * big3
    val sum3  = (big3 + end3) * num3 / big2
    val num5  = nn / big5
    val end5  = num5 * big5
    val sum5  = (big5 + end5) * num5 / big2
    val num15 = nn / big15
    val end15 = num15 * big15
    val sum15 = (big15 + end15) * num15 / big2
    return sum3 + sum5 - sum15
}

fun main(args: Array<String>) {
    println("The sum of multiples of 3 or 5 below 1000 is ${sum35(1000)}")
    val big100k = BigInteger.valueOf(100_000L)
    val e20 = big100k * big100k * big100k * big100k
    println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
}
Output:
The sum of multiples of 3 or 5 below 1000 is 233168
The sum of multiples of 3 or 5 below 1e20 is 2333333333333333333316666666666666666668

Lasso

local(limit = 1)
while(#limit <= 100000) => {^
	local(s = 0)
	loop(-from=3,-to=#limit-1) => {
		not (loop_count % 3) || not (loop_count % 5) ? #s += loop_count
	}
	'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
	#limit = integer(#limit->asString + '0')
^}
Output:
The sum of multiples of 3 or 5 between 1 and 0 is: 0
The sum of multiples of 3 or 5 between 1 and 9 is: 23
The sum of multiples of 3 or 5 between 1 and 99 is: 2318
The sum of multiples of 3 or 5 between 1 and 999 is: 233168
The sum of multiples of 3 or 5 between 1 and 9999 is: 23331668
The sum of multiples of 3 or 5 between 1 and 99999 is: 2333316668

Limbo

Uses the IPints library when the result will be very large.

implement Sum3and5;

include "sys.m"; sys: Sys;
include "draw.m";
include "ipints.m"; ipints: IPints;
	IPint: import ipints;

Sum3and5: module {
	init: fn(nil: ref Draw->Context, args: list of string);
};

ints: array of ref IPint;

init(nil: ref Draw->Context, args: list of string)
{
	sys = load Sys Sys->PATH;
	ipints = load IPints IPints->PATH;

	# We use 1, 2, 3, 5, and 15:
	ints = array[16] of ref IPint;
	for(i := 0; i < len ints; i++)
		ints[i] = IPint.inttoip(i);

	args = tl args;
	while(args != nil) {
		h := hd args;
		args = tl args;
		# If it's big enough that the result might not
		# fit inside a big, we use the IPint version.
		if(len h > 9) {
			sys->print("%s\n", isum3to5(IPint.strtoip(h, 10)).iptostr(10));
		} else {
			sys->print("%bd\n", sum3to5(big h));
		}
	}
}

triangle(n: big): big
{
	return((n * (n + big 1)) / big 2);
}

sum_multiples(n: big, limit: big): big
{
	return(n * triangle((limit - big 1) / n));
}

sum3to5(limit: big): big
{
	return(
		sum_multiples(big 3, limit) +
		sum_multiples(big 5, limit) -
		sum_multiples(big 15, limit));
}

itriangle(n: ref IPint): ref IPint
{
	return n.mul(n.add(ints[1])).div(ints[2]).t0;
}

isum_multiples(n: ref IPint, limit: ref IPint): ref IPint
{
	return n.mul(itriangle(limit.sub(ints[1]).div(n).t0));
}

isum3to5(limit: ref IPint): ref IPint
{
	return(
		isum_multiples(ints[3], limit).
		add(isum_multiples(ints[5], limit)).
		sub(isum_multiples(ints[15], limit)));
}
Output:
% sum3and5 1000 100000000000000000000
233168
2333333333333333333316666666666666666668

Lingo

on sum35 (n)
  res = 0
  repeat with i = 0 to (n-1)
    if i mod 3=0 OR i mod 5=0 then
      res = res + i
    end if
  end repeat
  return res
end
put sum35(1000)
-- 233168

LiveCode

function sumUntil n
    repeat with i = 0 to (n-1)
        if i mod 3 = 0 or i mod 5 = 0 then
            add i to m
        end if
    end repeat
    return m
end sumUntil

put sumUntil(1000)  // 233168

Lua

Translation of: Tcl
function tri (n) return n * (n + 1) / 2 end

function sum35 (n)
	n = n - 1
	return	(	3 * tri(math.floor(n / 3)) + 
			5 * tri(math.floor(n / 5)) - 
			15 * tri(math.floor(n / 15))
		)
end

print(sum35(1000))
print(sum35(1e+20))
Output:
233168
2.3333333333333e+39

Maple

By using symbolic function sum instead of numeric function add the program F will run O(1) rather than O(n).

F := unapply(  sum(3*i,i=1..floor((n-1)/3))
             + sum(5*i,i=1..floor((n-1)/5))
             - sum(15*i,i=1..floor((n-1)/15)), n);

F(1000);

F(10^20);

Output:

                               2                                      2
               3      /1     2\    3      /1     2\   5      /1     4\ 
     F := n -> - floor|- n + -|  - - floor|- n + -| + - floor|- n + -| 
               2      \3     3/    2      \3     3/   2      \5     5/ 

                                                2                      
          5      /1     4\   15      /1      14\    15      /1      14\
        - - floor|- n + -| - -- floor|-- n + --|  + -- floor|-- n + --|
          2      \5     5/   2       \15     15/    2       \15     15/


                                   233168

                  2333333333333333333316666666666666666668

Mathematica/Wolfram Language

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]
Output:
233168
sum35[10^20]
Output:
233333333333333333333166666666666666666668

Another alternative is

 Union @@ Range[0, 999, {3, 5}] // Tr

MATLAB / Octave

n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0))
ans =  233168

Another alternative is

n=1000; sum(0:3:n-1)+sum(0:5:n-1)-sum(0:15:n-1)

Of course, it's more efficient to use Gauss' approach of adding subsequent integers:

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
ans =  233168

Maxima

sumi(n, inc):= block(
  [kmax],

  /* below n means [1 .. n-1] */
  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);

Output:

(%i4) sum35(1000)
(%o4)                               233168
(%i5) sum35(10^20)
(%o5)              2333333333333333333316666666666666666668

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.

// 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)
Output:
233168

Now the fast version.

Translation of: D
// 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)
Output:
233168

МК-61/52

П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	С/П

Input: n.

Output for n = 1000: 233168.

Nanoquery

Translation of: 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.

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)
Output:
233168

NetRexx

Portions translation of Raku

/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 40

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method summing(maxLimit = 1000) public static
  mult = 0
  loop mv = 0 while mv < maxLimit
    if mv // 3 = 0 | mv // 5 = 0 then
      mult = mult + mv
    end mv
  return mult

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- translation of Raku
method sum_mults(first, limit) public static
  last = limit - 1
  last = last - last // first
  sum = (last / first) * (first + last) % 2
  return sum

method sum35(maxLimit) public static
  return sum_mults(3, maxLimit) + sum_mults(5, maxLimit) - sum_mults(15, maxLimit)

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static

  offset = 30
  incr = 10

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  timing = System.nanoTime
  sum = summing()
  timing = System.nanoTime - timing
  say 1000.format.right(offset)'|'sum
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  tmax = 1e+6
  timing = System.nanoTime
  mm = 1
  loop while mm <= tmax
    say mm.right(offset)'|'summing(mm)
    mm = mm * incr
    end
  timing = System.nanoTime - timing
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  timing = System.nanoTime
  sum = sum35(1000)
  timing = System.nanoTime - timing
  say 1000.format.right(offset)'|'sum
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  tmax = 1e+27
  timing = System.nanoTime
  mm = 1
  loop while mm <= tmax
    say mm.right(offset)'|'sum35(mm)
    mm = mm * incr
    end
  timing = System.nanoTime - timing
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say
  return
Output:
                         Limit|Sum
------------------------------+------------------------------------------------------------
                          1000|233168
Elapsed time:    0.097668s

                         Limit|Sum
------------------------------+------------------------------------------------------------
                             1|0
                            10|23
                           100|2318
                          1000|233168
                         10000|23331668
                        100000|2333316668
                       1000000|233333166668
Elapsed time:   11.593837s

                         Limit|Sum
------------------------------+------------------------------------------------------------
                          1000|233168
Elapsed time:    0.000140s

                         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
   100000000000000000000000000|2333333333333333333333333316666666666666666666666668
  1000000000000000000000000000|233333333333333333333333333166666666666666666666666668
Elapsed time:    0.005545s

Nim

Here is the solution using normal integers.

proc sum35(n: int): int =
  for x in 0 ..< n:
    if x mod 3 == 0 or x mod 5 == 0:
      result += x

echo sum35(1000)
Output:
233168

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".

Translation of: Raku
Library: bigints
import bigints

proc sumMults(first: int32, limit: BigInt): BigInt =
  var last = limit - 1
  last -= last mod first
  (last div first) * (last + first) div 2

proc sum35(n: BigInt): BigInt =
  result = sumMults(3, n)
  result += sumMults(5, n)
  result -= sumMults(15, n)

var x = 1.initBigInt
while x < "1000000000000000000000000000000".initBigInt:
  echo sum35 x
  x *= 10
Output:
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

Objeck

Translation of: Java
class SumMultiples {
  function : native : GetSum(n : Int) ~ Int {
    sum := 0;
    for(i := 3; i < n; i++;) {
      if(i % 3 = 0 | i % 5 = 0) {
        sum += i;
      };
    };

    return sum;
  }

  function : Main(args : String[]) ~ Nil {
    GetSum(1000)->PrintLine();
  }
}

Output:

233168

Odin

Note: 1e19 is the largest sum that can be calculated with 128 bit integers.

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))
}
Output:
The sum of all multiples of 3 and 5 < 1000 is 233168
The sum of all multiples of 3 and 5 < 1e19 is 23333333333333333331666666666666666668

OCaml

let sum_m3m5 n =
  let termial x = (x * x + x) lsr 1 in
  3 * (termial (n / 3) - 5 * termial (n / 15)) + 5 * termial (n / 5)

let () =
  let pow10 x = truncate (10. ** (float x)) in
  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
Output:
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

With wheel increments (slower)

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);;
Output:
The sum of the multiples of 3 or 5 below 1000 is 233168

Oforth

999 seq filter(#[ dup 3 mod 0 == swap 5 mod 0 == or ]) sum println

Output:

233168

Ol

(print
(fold (lambda (s x)
         (+ s (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0)))
   0 (iota 1000)))
; ==> 233168

PARI/GP

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)
Output:
%1 = 233168
%2 = 2333333333333333333316666666666666666668

Pascal

Works with: Free Pascal version 2.6.2
program Sum3sAnd5s;
 
function Multiple(x, y: integer): Boolean;
  { Is X a multiple of Y? }
   begin
      Multiple := (X mod Y) = 0
   end;
 
function SumMultiples(n: integer): longint;
  { Return the sum of all multiples of 3 or 5. }
   var i: integer; sum: longint;
   begin
      sum := 0;
      for i := 1 to pred(n) do
         if Multiple(i, 3) or Multiple(i, 5) then
           sum := sum + i;
      SumMultiples := sum
   end;

begin
   { Show sum of all multiples less than 1000. }
   writeln(SumMultiples(1000))
end.

alternative

using gauss summation formula, but subtract double counted. adapted translation of Tcl

program sum35;
//sum of all positive multiples of 3 or 5 below n

function cntSumdivisibleBelowN(n: Uint64;b:Uint64):Uint64;
var
  cnt : Uint64;
Begin
  cnt := (n-1) DIV b;
// Gauß summation formula * b
  cntSumdivisibleBelowN := (cnt*(cnt+1) DIV 2 ) *b;
end;
const
  n = 1000;

var
  sum: Uint64;
begin
  sum := cntSumdivisibleBelowN(n,3)+cntSumdivisibleBelowN(n,5);
//subtract double counted like 15
  sum := sum-cntSumdivisibleBelowN(n,3*5);
  writeln(sum);
end.

output

233168

Perl

#!/usr/bin/perl
use v5.20;
use experimental qw(signatures);

use List::Util qw( sum ) ;

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

say "The sum is ${\(sum_3_5 1000)}!\n" ;
Output:
The sum is 233168!
Translation of: Tcl

An alternative approach, using the analytical solution from the Tcl example.

use v5.20;
use experimental qw(signatures);

sub tri($n) {
   $n*($n+1) / 2;
}

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

sub sum($n) {
   sum_multiples(3, $n) + sum_multiples(5, $n) - sum_multiples(15, $n);
}

say sum 1e3;
use bigint; # Machine precision was sufficient for the first calculation
say sum 1e20;
Output:
233168
2333333333333333333316666666666666666668

Interestingly, the prime factorization of the second result produces a 35 digit prime number.

Phix

native

note the result of sum35() is inaccurate above 2^53 on 32-bit, 2^64 on 64-bit.

function sumMul(atom n, f)
    n = floor((n-1)/f)
    return f*n*(n+1)/2
end function
 
function sum35(atom n)
    return sumMul(n,3) +
           sumMul(n,5) -
           sumMul(n,15)
end function
 
for i=0 to 8 do
    string sp = repeat(' ',9-i),
           pt = "1"&repeat('0',i)
    printf(1,"%s%s%s %d\n",{sp,pt,sp,sum35(power(10,i))})
end for
Output:
         1          0
        10         23
       100        2318
      1000       233168
     10000      23331668
    100000     2333316668
   1000000    233333166668
  10000000   23333331666668
 100000000  2333333316666668

gmp

Translation of: C
Library: Phix/mpfr

Fast analytical version with arbitrary precision

with javascript_semantics 
include mpfr.e

procedure sum_multiples(mpz result, limit, integer f)
    mpz m = mpz_init()
    mpz_sub_ui(m, limit, 1)
    {} = mpz_fdiv_q_ui(m, m, f)
    mpz_set(result, m)
    mpz_add_ui(result, result, 1);
    mpz_mul(result, result, m)
    mpz_mul_si(result, result, f)
    mpz_fdiv_q_2exp(result, result, 1)
    m = mpz_free(m)
end procedure
 
mpz {res,tmp,limit} = mpz_inits(3)
for i=0 to 20 do
    string sp = repeat(' ',20-i)
    printf(1,sp&"1"&repeat('0',i)&sp)
    mpz_ui_pow_ui(limit,10,i)
    sum_multiples(res, limit, 3)
    sum_multiples(tmp, limit, 5)
    mpz_add(res,res,tmp)
    sum_multiples(tmp, limit, 15)
    mpz_sub(res,res,tmp)
    printf(1," %s\n",mpz_get_str(res))
end for
{res,tmp,limit} = mpz_free({res,tmp,limit})
Output:
                    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

PHP

Naive version (slow) :

$max = 1000;
$sum = 0;
for ($i = 1 ; $i < $max ; $i++) {
    if (($i % 3 == 0) or ($i % 5 == 0)) {
        $sum += $i;
    }
}
echo $sum, PHP_EOL;
Output:
233168

Fast version:

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;
Output:
233168
Library: GMP

Fast version using GNU Multiple Precision library. These functions allow for arbitrary-length integers to be worked with.

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);
}
Output:
                    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

Picat

Uses both the naive method and inclusion/exclusion.

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)).
Output:
The sum of all multiples of 3 and 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668

PicoLisp

(de sumMul (N F)
   (let N1 (/ (dec N) F)
      (*/ F N1 (inc N1) 2) ) )

(for I 20
   (let N (** 10 I)
      (println
         (-
            (+ (sumMul N 3) (sumMul N 5))
            (sumMul N 15) ) ) ) )
Output:
23
2318
233168
23331668
2333316668
233333166668
23333331666668
2333333316666668
233333333166666668
23333333331666666668
2333333333316666666668
233333333333166666666668
23333333333331666666666668
2333333333333316666666666668
233333333333333166666666666668
23333333333333331666666666666668
2333333333333333316666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668
2333333333333333333316666666666666666668

PL/I

threeor5: procedure options (main);      /* 8 June 2014 */
   declare (i, n) fixed(10), sum fixed (31) static initial (0);

   get (n);
   put ('The number of multiples of 3 or 5 below ' || trim(n) || ' is');

   do i = 1 to n-1;
      if mod(i, 3) = 0 | mod(i, 5) = 0 then sum = sum + i;
   end;

   put edit ( trim(sum) ) (A);

end threeor5;

Outputs:

The number of multiples of 3 or 5 below 1000 is 233168
The number of multiples of 3 or 5 below 10000 is 23331668
The number of multiples of 3 or 5 below 100000 is 2333316668
The number of multiples of 3 or 5 below 1000000 is 233333166668
The number of multiples of 3 or 5 below 10000000 is 23333331666668
The number of multiples of 3 or 5 below 100000000 is 2333333316666668

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

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;
Output:
Sum of all multiples of 3 and 5 below    1000
Sum = 233168
Also: 233168

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
    }

#  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 )
Output:
233168

For arbitrarily large integers, simply change the variable type.

function SumMultiples ( [bigint]$Base, [bigint]$Upto )
    {
    $X = ($Upto - ( $Upto % $Base ) ) / $Base + ( [int] ( $Upto % $Base -ne 0 ) )
    $Sum = ( $X * $X - $X ) * $Base / 2
    Return $Sum
    }

#  Calculate the sum of the multiples of 3 and 5 up to 10 ^ 210
$Upto = [bigint]::Pow( 10, 210 )
( SumMultiples -Base 3 -Upto $Upto ) + ( SumMultiples -Base 5 -Upto $Upto ) - ( SumMultiples -Base 15 -Upto $Upto )
Output:
233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666668

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.

function Get-SumOfMultiples
{
    Param
    (
        [Parameter(
        Position=0)]
        $Cap = 1000,

        [Parameter(
        ValueFromRemainingArguments=$True)]
        $Multiplier = (3,5)
    )

    $Multiples = @()
    $Sum = 0
    $multiplier | 
      ForEach-Object {
        For($i = 1; $i -lt $Cap; $i ++)
        {        
          If($i % $_ -eq 0)
          {$Multiples += $i}
        }
      }

     $Multiples | 
         select -Unique | 
         ForEach-Object {
            $Sum += $_
         }
     $Sum
}
Output:
Get-SumOfMultiples
233168
Output:
Get-SumOfMultiples 1500 3 5 7 13
649444

Prolog

Slow version

sum_of_multiples_of_3_and_5_slow(N, TT) :-
	sum_of_multiples_of_3_and_5(N, 1, 0, TT).

sum_of_multiples_of_3_and_5(N, K, S, S) :-
	3 * K >= N.

sum_of_multiples_of_3_and_5(N, K, C, S) :-
	T3 is 3 * K, T3 < N,
	C3 is C + T3,
	T5 is 5 * K,
	(   (T5 < N, K mod 3 =\= 0)
	->  C5 is C3 + T5
	;   C5 = C3),
	K1 is K+1,
	sum_of_multiples_of_3_and_5(N, K1, C5, S).

Fast version

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.

compute_sum(N, N1, Sum) :-
	(   N mod N1 =:= 0
	->  N2 is N div N1 - 1
	;   N2 is N div N1),
	Sum is N1 * N2 * (N2 + 1) / 2.

Output :

 ?- sum_of_multiples_of_3_and_5_slow(1000, TT).
TT = 233168 .

 ?- sum_of_multiples_of_3_and_5_fast(100000000000000000000, TT).
TT = 2333333333333333333316666666666666666668.

PureBasic

EnableExplicit

Procedure.q SumMultiples(Limit.q)
  If Limit < 0 : Limit = -Limit : EndIf; convert negative numbers to positive
  Protected.q i, sum = 0
  For i = 3 To Limit - 1
    If i % 3 = 0 Or i % 5 = 0
      sum + i
    EndIf
  Next  
  ProcedureReturn sum
EndProcedure
  
If OpenConsole()
  PrintN("Sum of numbers below 1000 which are multiples of 3 or 5 is : " + SumMultiples(1000))
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf
Output:
Sum of numbers below 1000 which are multiples of 3 or 5 is : 233168

Python

Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()

def sum35a(n):
    'Direct count'
    # note: ranges go to n-1
    return sum(x for x in range(n) if x%3==0 or x%5==0)

def sum35b(n): 
    "Count all the 3's; all the 5's; minus double-counted 3*5's"
    # note: ranges go to n-1
    return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))
    
def sum35c(n):
    'Sum the arithmetic progressions: sum3 + sum5 - sum15'
    consts = (3, 5, 15)
    # Note: stop at n-1
    divs = [(n-1) // c for c in consts]
    sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]
    return sums[0] + sums[1] - sums[2]

#test
for n in range(1001):
    sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)
    assert sa == sb == sc  # python tests aren't like those of c.

print('For n = %7i -> %i\n' % (n, sc))

# Pretty patterns
for p in range(7):
    print('For n = %7i -> %i' % (10**p, sum35c(10**p)))

# Scalability 
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))
Output:
For n =    1000 -> 233168

For n =       1 -> 0
For n =      10 -> 23
For n =     100 -> 2318
For n =    1000 -> 233168
For n =   10000 -> 23331668
For n =  100000 -> 2333316668
For n = 1000000 -> 233333166668

For n = 100000000000000000000 -> 2333333333333333333316666666666666666668


Or, more generally – taking the area under the straight line between the first multiple and the last:

Works with: Python version 3.7
'''Summed multiples of 3 and 5 up to n'''


# sum35 :: Int -> Int
def sum35(n):
    '''Sum of all positive multiples
       of 3 or 5 below n.
    '''
    f = sumMults(n)
    return f(3) + f(5) - f(15)


# sumMults :: Int -> Int -> Int
def sumMults(n):
    '''Area under a straight line between
       the first multiple and the last.
    '''
    def go(n, m):
        n1 = (n - 1) // m
        return (m * n1 * (n1 + 1)) // 2
    return lambda x: go(n, x)


# TEST ----------------------------------------------------
def main():
    '''Tests for [10^1 .. 10^5], and [10^8 .. 10^25]
    '''
    print(
        fTable(__doc__ + ':\n')(lambda x: '10E' + str(x))(
            str
        )(compose(sum35)(lambda x: 10**x))(
            enumFromTo(1)(5) + enumFromTo(18)(25)
        )
    )


# GENERIC -------------------------------------------------

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    '''Right to left function composition.'''
    return lambda f: lambda x: g(f(x))


# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
    '''Integer enumeration from m to n.'''
    return lambda n: list(range(m, 1 + n))


# fTable :: String -> (a -> String) ->
#                     (b -> String) ->
#        (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
          f -> value list -> tabular string.'''
    def go(xShow, fxShow, f, xs):
        w = max(map(compose(len)(xShow), xs))
        return s + '\n' + '\n'.join([
            xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
        ])
    return lambda xShow: lambda fxShow: (
        lambda f: lambda xs: go(
            xShow, fxShow, f, xs
        )
    )


# MAIN ---
if __name__ == '__main__':
    main()
Output:
Summed multiples of 3 and 5 up to n:

 10E1 -> 23
 10E2 -> 2318
 10E3 -> 233168
 10E4 -> 23331668
 10E5 -> 2333316668
10E18 -> 233333333333333333166666666666666668
10E19 -> 23333333333333333331666666666666666668
10E20 -> 2333333333333333333316666666666666666668
10E21 -> 233333333333333333333166666666666666666668
10E22 -> 23333333333333333333331666666666666666666668
10E23 -> 2333333333333333333333316666666666666666666668
10E24 -> 233333333333333333333333166666666666666666666668
10E25 -> 23333333333333333333333331666666666666666666666668

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

Extra credit, using the summation formula:

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

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
Output:
233168
2333333333333333333316666666666666666668

R

m35 = function(n) sum(unique(c(
    seq(3, n-1, by = 3), seq(5, n-1, by = 5))))
m35(1000)   # 233168

Racket

#lang racket
(require math)

;;; A naive solution
(define (naive k)
  (for/sum ([n (expt 10 k)] 
            #:when (or (divides? 3 n) (divides? 5 n)))
    n))

(for/list ([k 7]) (naive k))


;;; Using the formula for an arithmetic sum
(define (arithmetic-sum a1 n Δa)
  ; returns a1+a2+...+an
  (define an (+ a1 (* (- n 1) Δa)))
  (/ (* n (+ a1 an)) 2))

(define (analytical k)
  (define 10^k (expt 10 k))
  (define (n d) (quotient (- 10^k 1) d))
  (+    (arithmetic-sum  3 (n  3)  3)
        (arithmetic-sum  5 (n  5)  5)
     (- (arithmetic-sum 15 (n 15) 15))))

(for/list ([k 20]) (analytical k))

Output:

'(0 23 2318 233168 23331668 2333316668 233333166668)
'(0
  23
  2318
  233168
  23331668
  2333316668
  233333166668
  23333331666668
  2333333316666668
  233333333166666668
  23333333331666666668
  2333333333316666666668
  233333333333166666666668
  23333333333331666666666668
  2333333333333316666666666668
  233333333333333166666666666668
  23333333333333331666666666666668
  2333333333333333316666666666666668
  233333333333333333166666666666666668
  23333333333333333331666666666666666668)

Raku

(formerly Perl 6)

sub sum35($n) { [+] grep * %% (3|5), ^$n; }

say sum35 1000;
Output:
233168

Here's an analytical approach that scales much better for large values.

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;
Output:
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

REXX

version 1

/* REXX ***************************************************************
* 14.05.2013 Walter Pachl
**********************************************************************/
Say mul35()
exit
mul35:
s=0
Do i=1 To 999
  If i//3=0 | i//5=0 Then
    s=s+i
  End
Return s

Output:

233168

version 2

/* REXX ***************************************************************
* Translation from Raku->NetRexx->REXX
* 15.05.2013 Walter Pachl
**********************************************************************/
Numeric Digits 100
call time 'R'
n=1
Do i=1 To 30
  Say right(n,30) sum35(n)
  n=n*10
  End
Say time('E') 'seconds'
Exit

sum35: Procedure
  Parse Arg maxLimit
  return sum_mults(3, maxLimit) + sum_mults(5, maxLimit) - sum_mults(15, maxLimit)

sum_mults: Procedure
  Parse Arg first, limit
  last = limit - 1
  last = last - last // first
  sum = (last % first) * (first + last) % 2
  return sum

Output:

                             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
0 milliseconds with rexx m35a > m35a.txt
46 millisecond with rexx m35a

version 3

This version automatically adjusts the numeric digits.   A little extra code was added to format the output nicely.

The formula used is a form of the Gauss Summation formula.

/*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                  /*Not specified?  Then use the default.*/
if t=='' | t==","  then t=    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         /*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*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDiv: procedure;  parse arg x,d;       $= x % d;              return d * $ * ($+1) % 2
output   when using the default input:
The sum of all positive integers that are a multiple of  3  and  5  are:

integers from 1 ──► 999  is  233168
output   when using the input of:     1   85

(Shown at three-quarter size.)

The sum of all positive integers that are a multiple of  3  and  5  are:

integers from 1 ──►  1e0-1  is  0
integers from 1 ──►  1e1-1  is  23
integers from 1 ──►  1e2-1  is  2318
integers from 1 ──►  1e3-1  is  233168
integers from 1 ──►  1e4-1  is  23331668
integers from 1 ──►  1e5-1  is  2333316668
integers from 1 ──►  1e6-1  is  233333166668
integers from 1 ──►  1e7-1  is  23333331666668
integers from 1 ──►  1e8-1  is  2333333316666668
integers from 1 ──►  1e9-1  is  233333333166666668
integers from 1 ──► 1e10-1  is  23333333331666666668
integers from 1 ──► 1e11-1  is  2333333333316666666668
integers from 1 ──► 1e12-1  is  233333333333166666666668
integers from 1 ──► 1e13-1  is  23333333333331666666666668
integers from 1 ──► 1e14-1  is  2333333333333316666666666668
integers from 1 ──► 1e15-1  is  233333333333333166666666666668
integers from 1 ──► 1e16-1  is  23333333333333331666666666666668
integers from 1 ──► 1e17-1  is  2333333333333333316666666666666668
integers from 1 ──► 1e18-1  is  233333333333333333166666666666666668
integers from 1 ──► 1e19-1  is  23333333333333333331666666666666666668
integers from 1 ──► 1e20-1  is  2333333333333333333316666666666666666668
integers from 1 ──► 1e21-1  is  233333333333333333333166666666666666666668
integers from 1 ──► 1e22-1  is  23333333333333333333331666666666666666666668
integers from 1 ──► 1e23-1  is  2333333333333333333333316666666666666666666668
integers from 1 ──► 1e24-1  is  233333333333333333333333166666666666666666666668
integers from 1 ──► 1e25-1  is  23333333333333333333333331666666666666666666666668
integers from 1 ──► 1e26-1  is  2333333333333333333333333316666666666666666666666668
integers from 1 ──► 1e27-1  is  233333333333333333333333333166666666666666666666666668
integers from 1 ──► 1e28-1  is  23333333333333333333333333331666666666666666666666666668
integers from 1 ──► 1e29-1  is  2333333333333333333333333333316666666666666666666666666668
integers from 1 ──► 1e30-1  is  233333333333333333333333333333166666666666666666666666666668
integers from 1 ──► 1e31-1  is  23333333333333333333333333333331666666666666666666666666666668
integers from 1 ──► 1e32-1  is  2333333333333333333333333333333316666666666666666666666666666668
integers from 1 ──► 1e33-1  is  233333333333333333333333333333333166666666666666666666666666666668
integers from 1 ──► 1e34-1  is  23333333333333333333333333333333331666666666666666666666666666666668
integers from 1 ──► 1e35-1  is  2333333333333333333333333333333333316666666666666666666666666666666668
integers from 1 ──► 1e36-1  is  233333333333333333333333333333333333166666666666666666666666666666666668
integers from 1 ──► 1e37-1  is  23333333333333333333333333333333333331666666666666666666666666666666666668
integers from 1 ──► 1e38-1  is  2333333333333333333333333333333333333316666666666666666666666666666666666668
integers from 1 ──► 1e39-1  is  233333333333333333333333333333333333333166666666666666666666666666666666666668
integers from 1 ──► 1e40-1  is  23333333333333333333333333333333333333331666666666666666666666666666666666666668
integers from 1 ──► 1e41-1  is  2333333333333333333333333333333333333333316666666666666666666666666666666666666668
integers from 1 ──► 1e42-1  is  233333333333333333333333333333333333333333166666666666666666666666666666666666666668
integers from 1 ──► 1e43-1  is  23333333333333333333333333333333333333333331666666666666666666666666666666666666666668
integers from 1 ──► 1e44-1  is  2333333333333333333333333333333333333333333316666666666666666666666666666666666666666668
integers from 1 ──► 1e45-1  is  233333333333333333333333333333333333333333333166666666666666666666666666666666666666666668
integers from 1 ──► 1e46-1  is  23333333333333333333333333333333333333333333331666666666666666666666666666666666666666666668
integers from 1 ──► 1e47-1  is  2333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666668
integers from 1 ──► 1e48-1  is  233333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666668
integers from 1 ──► 1e49-1  is  23333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666668
integers from 1 ──► 1e50-1  is  2333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666668
integers from 1 ──► 1e51-1  is  233333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666668
integers from 1 ──► 1e52-1  is  23333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e53-1  is  2333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e54-1  is  233333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e55-1  is  23333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e56-1  is  2333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e57-1  is  233333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e58-1  is  23333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e59-1  is  2333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e60-1  is  233333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e61-1  is  23333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e62-1  is  2333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e63-1  is  233333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e64-1  is  23333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e65-1  is  2333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e66-1  is  233333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e67-1  is  23333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e68-1  is  2333333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e69-1  is  233333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e70-1  is  23333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e71-1  is  2333333333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e72-1  is  233333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e73-1  is  23333333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e74-1  is  2333333333333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e75-1  is  233333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e76-1  is  23333333333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e77-1  is  2333333333333333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e78-1  is  233333333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e79-1  is  23333333333333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e80-1  is  2333333333333333333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e81-1  is  233333333333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e82-1  is  23333333333333333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e83-1  is  2333333333333333333333333333333333333333333333333333333333333333333333333333333333316666666666666666666666666666666666666666666666666666666666666666666666666666666668
integers from 1 ──► 1e84-1  is  233333333333333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666666666666668

Ring

see sum35(1000) + nl
 
func sum35 n
     n = n - 1
     return(3 * tri(floor(n / 3)) + 
	    5 * tri(floor(n / 5)) - 
	    15 * tri(floor(n / 15)))

func tri n
     return n * (n + 1) / 2

RPL

Works with: Halcyon Calc version 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:

  1. 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
  2. the sum of multiples of m being < n is equal to m*(1+2+ ... k) with k =[n/m]
  3. 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
Output:
1: 233168

Ruby

Simple Version (Slow):

def sum35(n)
  (1...n).select{|i|i%3==0 or i%5==0}.sum
end
puts sum35(1000)      #=> 233168

Fast Version:

# Given two integers n1,n2 return sum of multiples upto n3
#
#  Nigel_Galloway
#  August 24th., 2013.
def g(n1, n2, n3)
   g1 = n1*n2
   (1..g1).select{|x| x%n1==0 or x%n2==0}.collect{|x| g2=(n3-x)/g1; (x+g1*g2+x)*(g2+1)}.inject{|sum,x| sum+x}/2
end

puts g(3,5,999)

# For extra credit
puts g(3,5,100000000000000000000-1)
Output:
233168
2333333333333333333316666666666666666668

Other way:

Translation of: D
def sumMul(n, f)
  n1 = (n - 1) / f
  f * n1 * (n1 + 1) / 2
end

def sum35(n)
  sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15)
end

for i in 1..20
  puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)]
end
Output:
 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

Run BASIC

print multSum35(1000)
end
function multSum35(n)
    for i = 1 to n - 1
        If (i mod 3 = 0) or (i mod 5 = 0) then  multSum35 = multSum35 + i
    next i
end function
233168

Rust

extern crate rug;

use rug::Integer;
use rug::ops::Pow;

fn main() {
    for i in [3, 20, 100, 1_000].iter() {
        let ten = Integer::from(10);
        let mut limit = Integer::from(Integer::from(&ten.pow(*i as u32)) - 1);
        let mut aux_3_1 = &limit.mod_u(3u32);
        let mut aux_3_2 = Integer::from(&limit - aux_3_1);
        let mut aux_3_3 = Integer::from(&aux_3_2/3);
        let mut aux_3_4 = Integer::from(3 + aux_3_2);
        let mut aux_3_5 = Integer::from(&aux_3_3*&aux_3_4);
        let mut aux_3_6 = Integer::from(&aux_3_5/2);
 
        let mut aux_5_1 = &limit.mod_u(5u32);
        let mut aux_5_2 = Integer::from(&limit - aux_5_1); 
        let mut aux_5_3 = Integer::from(&aux_5_2/5);
        let mut aux_5_4 = Integer::from(5 + aux_5_2); 
        let mut aux_5_5 = Integer::from(&aux_5_3*&aux_5_4);
        let mut aux_5_6 = Integer::from(&aux_5_5/2); 

        let mut aux_15_1 = &limit.mod_u(15u32);
        let mut aux_15_2 = Integer::from(&limit - aux_15_1); 
        let mut aux_15_3 = Integer::from(&aux_15_2/15);
        let mut aux_15_4 = Integer::from(15 + aux_15_2);
        let mut aux_15_5 = Integer::from(&aux_15_3*&aux_15_4);
        let mut aux_15_6 = Integer::from(&aux_15_5/2); 

        let mut result_aux_1 = Integer::from(&aux_3_6 + &aux_5_6); 
        let mut result = Integer::from(&result_aux_1 - &aux_15_6);
 
        println!("Sum for 10^{} : {}",i,result);
    }
}

Output :

Sum for 10^3 : 233168
Sum for 10^20 : 2333333333333333333316666666666666666668
Sum for 10^100 : 23333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666668
Sum for 10^1000 : 23333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666668

real	0m0.002s
user	0m0.002s
sys	0m0.000s

S-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
Output:
Sum = 233168


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)) )
}
Output:
                     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

Scheme

(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000))

Output:

233168

Or, more clearly by decomposition:

(define (fac35? x)
    (or (zero? (remainder x 3)) 
        (zero? (remainder x 5))))

(define (fac35filt x tot)
    (+ tot (if (fac35? x) x 0)))

(fold fac35filt 0 (iota 1000))

Output:

233168

For larger numbers iota can take quite a while just to build the list -- forget about waiting for all the computation to finish!

(define (trisum n fac)
    (let* ((n1 (quotient (- n 1) fac)) 
           (n2 (+ n1 1)))
        (quotient (* fac n1 n2) 2)))

(define (fast35sum n)
    (- (+ (trisum n 5) (trisum n 3)) (trisum n 15)))

(fast35sum 1000)
(fast35sum 100000000000000000000)

Output:

233168
2333333333333333333316666666666666666668

Seed7

$ include "seed7_05.s7i";
  include "bigint.s7i";

const func bigInteger: sum35 (in bigInteger: n) is func
  result
    var bigInteger: sum35 is 0_;
  local
    const func bigInteger: sumMul (in bigInteger: n, in bigInteger: f) is func
      result
        var bigInteger: sumMul is 0_;
      local
        var bigInteger: n1 is 0_;
      begin
        n1 := pred(n) div f;
        sumMul := f * n1 * succ(n1) div 2_;
      end func;
   begin
     sum35 := sumMul(n, 3_) + sumMul(n, 5_) - sumMul(n, 15_);
   end func;
 
const proc: main is func
  begin
    writeln(sum35(1000_));
    writeln(sum35(10_ ** 20));
  end func;
Output:
233168
2333333333333333333316666666666666666668

Sidef

Translation of: Ruby
func sumMul(n, f) {
    var m = int((n - 1) / f)
    f * m * (m + 1) / 2
}

func sum35(n) {
    sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15)
}

for i in (1..20) {
    printf("%2s:%22s %s\n", i, 10**i, sum35(10**i))
}
Output:
 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

Simula

(referenced from Greatest common divisor)

! 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
    INTEGER PROCEDURE GCD(a, b); INTEGER a, b;
        GCD := IF b = 0 THEN a ELSE GCD(b, MOD(a, b));

    ! sum of multiples of n up to limit;
    INTEGER PROCEDURE multiples(n, limit); INTEGER n, limit;
    BEGIN
        INTEGER m;
        m := limit // n;
    ! moving //2 to sumMultiples() looked just too silly    ;
        multiples := n*((m*(m+1)) // 2) ! and risks overflow;
    END
    ! sum of multiples of n or m below limit;
    INTEGER PROCEDURE sumMultiples(n, m, limit);
        INTEGER n, m, limit;
    BEGIN
        INTEGER LCM;
        LCM:= (n // GCD(n, m)) * m;
        limit := limit-1;
        sumMultiples := multiples(n, limit) + multiples(m, limit)
                        - multiples(LCM, limit)
    END sumMultiples;
    
    ! Extra creditable: math is about avoiding calculation tedium;
    TEXT PROCEDURE repeat(c, n); CHARACTER c; INTEGER n; BEGIN
        TEXT r; r :- BLANKS(n);
        FOR n := n STEP -1 UNTIL 1 DO r.PUTCHAR(c);
        repeat :- r;
    END;
    TEXT PROCEDURE sumOfMultiplesOf3or5below10toThePowerOf(e);
        INTEGER e;
    sumOfMultiplesOf3or5below10toThePowerOf :-
        IF e < 1 THEN "0" ELSE IF e = 1 THEN "23"
        ELSE "23" & repeat('3', e-2)
            & "1" & repeat('6', e-2) & "8";

    INTEGER factor, n;
    FOR factor := 5 !, 2, 6;
                    DO BEGIN
        OUTTEXT("sum of positive multiples of 3 and");
        OUTINT(factor, 2); OUTCHAR(':');
        FOR n := ! 1 STEP 1 UNTIL 15, 100,;
                 1000 DO BEGIN
            OUTCHAR(' '); OUTINT(sumMultiples(3, factor, n), 0)
        END;
        OUTIMAGE
    END;
    FOR n := 0, 1, 3, 5, 10, 20, 40 DO BEGIN
        OUTTEXT(sumOfMultiplesOf3or5below10toThePowerOf(n));
        OUTIMAGE
    END
END
Output:

sum of positive multiples of 3 and 5: 233168
0
23
233168
2333316668
23333333331666666668
2333333333333333333316666666666666666668
23333333333333333333333333333333333333331666666666666666666666666666666666666668

Stata

With a dataset

clear all
set obs 999
gen a=_n
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)

With Mata

mata
a=1..999
sum(a:*(mod(a,3):==0 :| mod(a,5):==0))

Swift

var n:Int=1000

func sum(x:Int)->Int{
	
	var s:Int=0
	for i in 0...x{
		if i%3==0 || i%5==0
		{
			s=s+i
		}
		
	}
	return s
}

var sumofmult:Int=sum(x:n)
print(sumofmult)

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} {} {
	if {$threes<$fives} {
	    incr total $threes
	    incr threes 3
	} elseif {$threes>$fives} {
	    incr total $fives
	    incr fives 5
	} else {
	    incr total $threes
	    incr threes 3
	    incr fives 5
	}
    }
    return $total
}

However, that's pretty dumb. We can do much better by observing that the sum of the multiples of below some is , where is the 'th triangular number, for which there exists a trivial formula. Then we simply use an overall formula of (that is, summing the multiples of three and the multiples of five, and then subtracting the multiples of 15 which were double-counted).

# Smart version; no iteration so very scalable!
proc tcl::mathfunc::triangle {n} {expr {
    $n * ($n+1) / 2
}}
# Note that the rounding on integer division is exactly what we need here.
proc sum35 {n} {
    incr n -1
    expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
}

Demonstrating:

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]
Output:
233168,233168
23333331666668,23333331666668
2333333333333333333316666666666666666668

TI SR-56

Iterative solution

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.

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:

// 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

Usage:

Input:
1000 RST R/S
Output:
233168

This took between 20 and 30 minutes to run.

Efficient closed-form solution

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.

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:

// 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.

Usage:

Input:
1000 RST R/S
Output:
233168

Completed in 4 seconds.

Input:
1 EE 20 RST R/S
Output:
2.333333333 39

Completed in 4 seconds.

Uiua

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
Output:

233168

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.

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
Output:
         1	                 0
        10	                23
       100	              2318
      1000	            233168
     10000	          23331668
    100000	        2333316668
   1000000	      233333166668
  10000000	    23333331666668
 100000000	  2333333316666668
1000000000	233333333166666668

VBA

Translation of: VBScript
Private Function SumMult3and5VBScript(n As Double) As Double
Dim i As Double
    For i = 1 To n - 1
        If i Mod 3 = 0 Or i Mod 5 = 0 Then
            SumMult3and5VBScript = SumMult3and5VBScript + i
        End If
    Next
End Function

Other way :

Private Function SumMult3and5(n As Double) As Double
Dim i As Double
    For i = 3 To n - 1 Step 3
        SumMult3and5 = SumMult3and5 + i
    Next
    For i = 5 To n - 1 Step 5
        If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
    Next
End Function

Better way :

Private Function SumMult3and5BETTER(n As Double) As Double
Dim i As Double
    For i = 3 To n - 1 Step 3
        SumMult3and5BETTER = SumMult3and5BETTER + i
    Next
    For i = 5 To n - 1 Step 5
        SumMult3and5BETTER = SumMult3and5BETTER + i
    Next
    For i = 15 To n - 1 Step 15
        SumMult3and5BETTER = SumMult3and5BETTER - i
    Next
End Function

Call :

Option Explicit

Sub Main()
Dim T#
    T = Timer
    Debug.Print SumMult3and5VBScript(100000000) & "   " & Format(Timer - T, "0.000 sec.")
    T = Timer
    Debug.Print SumMult3and5(100000000) & "   " & Format(Timer - T, "0.000 sec.")
    T = Timer
    Debug.Print SumMult3and5BETTER(100000000) & "   " & Format(Timer - T, "0.000 sec.")
    Debug.Print "-------------------------"
    Debug.Print SumMult3and5BETTER(1000)
End Sub
Output:
2,33333331666667E+15   9,059 sec.
2,33333331666667E+15   2,107 sec.
2,33333331666667E+15   1,799 sec.
-------------------------
233168

VBScript

Translation of: Run BASIC
Function multsum35(n)
	For i = 1 To n - 1
		If i Mod 3 = 0 Or i Mod 5 = 0 Then
			multsum35 = multsum35 + i
		End If
	Next
End Function

WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.WriteLine
Output:
F:\>cscript /nologo multsum35.vbs 1000
233168


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

V (Vlang)

Translation of: 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))
}
Output:
233168

Wortel

@let {
  sum35 ^(@sum \!-@(\~%%3 || \~%%5) @til)
	
  !sum35 1000 ; returns 233168
}

Wren

Simple version

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))
Output:
233168


Fast version with arbitrary precision

Translation of: C
Library: Wren-gmp
Library: Wren-fmt
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)
}
Output:
                     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

XPL0

include c:\cxpl\stdlib;

func Sum1;      \Return sum the straightforward way
int  N, S;
[S:= 0;
for N:= 1 to 999 do
    if rem(N/3)=0 or rem(N/5)=0 then S:= S+N;
return S;
];

func Sum2(D);   \Return sum of sequence using N*(N+1)/2
int  D;
int  Q;
[Q:= (1000-1)/D;
return Q*(Q+1)/2*D;
];

func Sum3(D);   \Return sum of sequence for really big number
string 0;       \don't terminate strings by setting most significant bit
int  D;         \divisor
int  I;
char P(40), Q(40), R(40);       \product, quotient, result
[StrNDiv("99999999999999999999", D, Q, 20);     \Q:= (1E20-1)/D
for I:= 0 to 17 do R(I):= ^0;                   \R:= D
R(18):= D/10 +^0;
R(19):= rem(0) +^0;
StrNMul(Q, R, P, 20);                           \P:= Q*R = Q*D
StrNAdd("00000000000000000001", Q, 20);         \Q:= Q+1
StrNMul(P+20, Q, R, 20);                        \R:= P*Q = Q*D*(Q+1)
StrNDiv(R, 2, Q, 40);                           \Q:= P/2 = Q*D*(Q+1)/2
return Q;                                       \(very temporary location)
];

char S(40), T;
[IntOut(0, Sum1);  CrLf(0);
 IntOut(0, Sum2(3) + Sum2(5) - Sum2(3*5));  CrLf(0);
StrNCopy(Sum3(3), S, 40);
StrNAdd(Sum3(5), S, 40);
T:= Sum3(3*5);
StrNSub(S, T, 40);
TextN(0, T, 40);  CrLf(0);
]
Output:
233168
233168
2333333333333333333316666666666666666668

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.

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)});
}
Output:
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

zkl

Brute force:

[3..999,3].reduce('+,0) + [5..999,5].reduce('+,0) - [15..999,15].reduce('+,0)
233168
Translation of: 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).

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)}
Output:
zkl: sum35(1000)  // int-->int
233168

zkl: var BN=Import("zklBigNum");
zkl: sum35(BN("1"+"0"*21))  // 1 with 21 zeros, BigNum-->BigNum
233333333333333333333166666666666666666668
sum35(BN("1"+"0"*15)) : "%,d".fmt(_)// 1e15, BigNum don't like float format input
233,333,333,333,333,166,666,666,666,668