Sum multiples of 3 and 5: Difference between revisions
→{{header|UIUA}}
m (Phix/mpfr) |
|||
(73 intermediate revisions by 35 users not shown) | |||
Line 6:
Show output for ''n'' = 1000.
This is is the same as [https://projecteuler.net/problem=1 Project Euler problem 1].
'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
<br><br>
=={{header|11l}}==
<syntaxhighlight lang="11l">F sum35(limit)
V sum = 0
L(i) 1 .< limit
I i % 3 == 0 | i % 5 == 0
sum += i
R sum
print(sum35(1000))</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
=={{header|8th}}==
Implements both the naive method and inclusion/exclusion.
<syntaxhighlight lang="8th">
needs combinators/bi
: mul3or5? ( 3 mod 0 = ) ( 5 mod 0 = ) bi or ;
"The sum of the multiples of 3 or 5 below 1000 is " .
0 ( mul3or5? if I n:+ then ) 1 999 loop . cr
with: n
: >triangular SED: n -- n
dup 1+ * 2 / ;
: sumdiv SED: n n -- n
dup >r /mod nip >triangular r> * ;
: sumdiv_3,5 SED: n -- n
( swap sumdiv ) curry [3, 5, 15] swap a:map a:open neg + + ;
;with
"For 10^20 - 1, the sum is " . 10 20 ^ 1- sumdiv_3,5 . cr
bye
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 below 1000 is 233168
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668
</pre>
=={{header|360 Assembly}}==
<
SUM35 CSECT
USING SUM35,R13 base register
Line 56 ⟶ 103:
PG DC CL80'123456789012 : 1234567890123456'
YREGS
END SUM35</
{{out}}
<pre>
Line 66 ⟶ 113:
1000000 : 233333166668
10000000 : 23333331666668
</pre>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Main()
REAL sum,r
INT i
Put(125) PutE() ;clear the screen
IntToReal(0,sum)
FOR i=0 TO 999
DO
IF i MOD 3=0 OR i MOD 5=0 THEN
IntToReal(i,r)
RealAdd(sum,r,sum)
FI
OD
PrintRE(sum)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_multiples_of_3_and_5.png Screenshot from Atari 8-bit computer]
<pre>
233168
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO;
procedure Sum_Multiples is
type Natural is range 0 .. 2**63 - 1;
function Sum_3_5 (Limit : in Natural) return Natural is
Sum : Natural := 0;
begin
for N in 1 .. Limit - 1 loop
if N mod 3 = 0 or else N mod 5 = 0 then
Sum := Sum + N;
end if;
end loop;
return Sum;
end Sum_3_5;
begin
Ada.Text_IO.Put_Line ("n=1000: " & Sum_3_5 (1000)'Image);
Ada.Text_IO.Put_Line ("n=5e9 : " & Sum_3_5 (5e9)'Image);
end Sum_Multiples;</syntaxhighlight>
{{out}}
<pre>n=1000: 233168
n=5e9 : 5833333329166666668</pre>
===Extra Credit===
Requires upcoming Ada 202x with big integer package.
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Numerics.Big_Numbers.Big_Integers;
procedure Sum_Multiples_Big is
use Ada.Numerics.Big_Numbers.Big_Integers;
use Ada.Text_IO;
type Natural is new Big_Natural;
function Sum_Mults (First, Last : Natural) return Natural is
High : constant Natural := Last - Last mod First;
Sum : constant Natural := (High / First) * (First + High) / 2;
begin
return Sum;
end Sum_Mults;
function Sum_35 (Limit : in Natural) return Natural is
Last : constant Natural := Limit - 1;
Mult_3 : constant Natural := Sum_Mults (3, Last);
Mult_5 : constant Natural := Sum_Mults (5, Last);
Mult_15 : constant Natural := Sum_Mults (15, Last);
begin
return Mult_3 + Mult_5 - Mult_15;
end Sum_35;
begin
Put_Line (" n : Sum_35 (n)");
Put_Line ("-----------------------------------------------------------------");
for E in 0 .. 30 loop
declare
N : constant Natural := 10**E;
begin
Put (To_String (N, Width => 32));
Put (" : ");
Put (Sum_35 (N)'Image);
New_Line;
end;
end loop;
end Sum_Multiples_Big;</syntaxhighlight>
{{out}}
<pre> n : Sum_35 (n)
-----------------------------------------------------------------
1 : 0
10 : 23
100 : 2318
1000 : 233168
10000 : 23331668
100000 : 2333316668
1000000 : 233333166668
10000000 : 23333331666668
100000000 : 2333333316666668
1000000000 : 233333333166666668
10000000000 : 23333333331666666668
100000000000 : 2333333333316666666668
1000000000000 : 233333333333166666666668
10000000000000 : 23333333333331666666666668
100000000000000 : 2333333333333316666666666668
1000000000000000 : 233333333333333166666666666668
10000000000000000 : 23333333333333331666666666666668
100000000000000000 : 2333333333333333316666666666666668
1000000000000000000 : 233333333333333333166666666666666668
10000000000000000000 : 23333333333333333331666666666666666668
100000000000000000000 : 2333333333333333333316666666666666666668
1000000000000000000000 : 233333333333333333333166666666666666666668
10000000000000000000000 : 23333333333333333333331666666666666666666668
100000000000000000000000 : 2333333333333333333333316666666666666666666668
1000000000000000000000000 : 233333333333333333333333166666666666666666666668
10000000000000000000000000 : 23333333333333333333333331666666666666666666666668
100000000000000000000000000 : 2333333333333333333333333316666666666666666666666668
1000000000000000000000000000 : 233333333333333333333333333166666666666666666666666668
10000000000000000000000000000 : 23333333333333333333333333331666666666666666666666666668
100000000000000000000000000000 : 2333333333333333333333333333316666666666666666666666666668
1000000000000000000000000000000 : 233333333333333333333333333333166666666666666666666666666668</pre>
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="ALGOL">
begin
comment - return n mod m;
integer procedure mod(n,m);
value n, m; integer n, m;
begin
mod := n - m * entier(n / m);
end;
integer i, limit;
real sum;
limit := 1000;
sum := 0;
for i := 1 step 1 until (limit - 1) do
if mod(i, 3) = 0 or mod(i, 5) = 0 then
sum := sum + i;
outreal(1,sum);
end
</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
Line 71 ⟶ 275:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT to handle large numbers.
<
PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT:
BEGIN
Line 96 ⟶ 300:
, newline
)
)</
{{out}}
<pre>
Line 103 ⟶ 307:
</pre>
==
=== Dyalog APL ===
<syntaxhighlight lang="apl">
Sum ← +/∘⍸1<15∨⍳
</syntaxhighlight>
{{out}}
<pre> Sum 999
233168</pre>
=== ngn/APL ===
<syntaxhighlight lang="apl">⎕IO←0
{+/((0=3|a)∨0=5|a)/a←⍳⍵} 1000</syntaxhighlight>[http://ngn.github.io/apl/web/index.html#code=%7B+/%28%280%3D3%7Ca%29%u22280%3D5%7Ca%29/a%u2190%u2373%u2375%7D%201000,run=1 run]
{{out}}
<pre>233168</pre>
==
{{Trans|JavaScript}}
<
-- 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
-- enumFromTo :: Int -> Int -> [Int]
Line 186 ⟶ 401:
end script
end if
end mReturn</
{{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>
Line 192 ⟶ 407:
=={{header|Arturo}}==
<syntaxhighlight lang
sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]
print
{{out}}
Line 202 ⟶ 419:
=={{header|AutoHotkey}}==
<
msgbox % "Sum is " . Sum3_5(n) . " for n = " . n
Line 236 ⟶ 453:
}
return sum
}</
'''Output:''' <pre>Sum is 233168 for n = 1000
Sum is 233168 for n = 1000</pre>
Line 242 ⟶ 459:
=={{header|AWK}}==
Save this into file "sum_multiples_of3and5.awk"
<
{
n = $1-1;
Line 250 ⟶ 467:
m = int(n/d);
return (d*m*(m+1)/2);
}</
{{Out}}
Line 264 ⟶ 481:
2333333333333333333316666666666666666668</pre>
==
{{works with|FreeBASIC}}
<
Function mulsum35(n as integer) as integer
Dim s as integer
Line 278 ⟶ 495:
Print mulsum35(1000)
Sleep
End</
{{out}}
<pre>233168</pre>
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 10 INPUT N
20 LET SUM = 0
30 FOR I = 3 TO N - 1
40 IF I / 3 = INT (I / 3) OR I / 5 = INT (I / 5) THEN SUM = SUM + I
50 NEXT I
60 PRINT SUM</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">function multSum35(n)
if n = 0 then return 0
suma = 0
for i = 1 to n
if (i mod 3 = 0) or (i mod 5 = 0) then suma += i
next i
return suma
end function
print multSum35(999)
end</syntaxhighlight>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 cls
20 print multsum35(1000)
30 end
40 function multsum35(n)
50 suma = 0
60 for i = 1 to n-1
70 if (i mod 3 = 0) or (i mod 5 = 0) then suma = suma+i
80 next i
90 multsum35 = suma
100 end function</syntaxhighlight>
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; multSum35(999)
End
Function multSum35(n As Integer) As Integer
If n = 0 Then Return 0
Dim suma As Integer = 0
For i As Integer = 1 To n
If (i Mod 3 = 0) Or (i Mod 5 = 0) Then suma += i
Next
Return suma
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|MSX BASIC|any}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 CLS : REM 10 HOME for Applesoft BASIC
20 LET N = 1000
30 GOSUB 60
40 PRINT S
50 END
60 REM multsum35
70 LET S = 0
80 FOR I = 1 TO N-1
90 IF I/3 = INT(I/3) OR I/5 = INT(I/5) THEN LET S = S+I : REM for Applesoft BASIC & Quite BASIC
90 IF (I MOD 3 = 0) OR (I MOD 5 = 0) THEN LET S = S+I : REM for MSX Basic & Chipmunk Basic
100 NEXT I
110 RETURN</syntaxhighlight>
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 INPUT N
20 LET S = 0
30 FOR I = 3 TO N - 1
40 IF I / 3 = INT (I / 3) THEN 70
50 IF I / 5 = INT (I / 5) THEN 70
60 GOTO 80
70 LET S = S + I
80 NEXT I
90 PRINT S
100 END</syntaxhighlight>
==={{header|MSX Basic}}===
See [[#GW-BASIC|GW-BASIC]].
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">FUNCTION multSum35 (n)
IF n = 0 THEN multSum35 = 0
suma = 0
FOR i = 1 TO n
IF (i MOD 3 = 0) OR (i MOD 5 = 0) THEN suma = suma + i
NEXT i
multSum35 = suma
END FUNCTION
PRINT multSum35(999)</syntaxhighlight>
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION multSum35(n)
IF n = 0 THEN LET multSum35 = 0
LET suma = 0
FOR i = 1 TO n
IF MOD(i, 3) = 0 OR MOD(i, 5) = 0 THEN LET suma = suma + i
NEXT i
LET multSum35 = suma
END FUNCTION
PRINT multSum35(999)
END</syntaxhighlight>
==={{header|Quite BASIC}}===
See [[#GW-BASIC|GW-BASIC]].
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub multSum35(n)
if n = 0 then return 0 : fi
suma = 0
for i = 1 to n
if mod(i, 3) = 0 or mod(i, 5) = 0 then suma = suma + i : fi
next i
return suma
end sub
print multSum35(999)
end</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 DEF MULTSUM35(N)
120 LET S=0
Line 290 ⟶ 636:
150 NEXT
160 LET MULTSUM35=S
170 END DEF</
==={{header|Sinclair ZX81 BASIC}}===
Line 296 ⟶ 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.
<
20 FAST
30 LET SUM=0
Line 305 ⟶ 651:
80 NEXT I
90 SLOW
100 PRINT SUM</
{{in}}
<pre>1000</pre>
Line 313 ⟶ 659:
=={{header|bc}}==
{{trans|Groovy}}
<
auto m
Line 325 ⟶ 671:
s(1000)
s(10 ^ 20)</
{{Out}}
<pre>233168
2333333333333333333316666666666666666668</pre>
==
There is both the naive method and the fast inclusion/exclusion method demonstrated. The code is limited to values that don't overflow a 64 bit integer.
<syntaxhighlight lang="bcpl">
GET "libhdr"
LET sumdiv(n, d) = VALOF {
LET m = n/d
RESULTIS m*(m + 1)/2 * d
}
LET sum3or5(n) = sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)
LET start() = VALOF {
LET sum = 0
LET n = 1
FOR k = 1 TO 999 DO
IF k MOD 3 = 0 | k MOD 5 = 0 THEN sum +:= k
writef("The sum of the multiples of 3 and 5 < 1000 is %d *n", sum)
writef("Next, the awesome power of inclusion/exclusion...*n");
FOR i = 1 TO 10 {
writef("%11d %d *n", n, sum3or5(n - 1))
n *:= 10
}
RESULTIS 0
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 and 5 < 1000 is 233168
Next, the awesome power of inclusion/exclusion...
1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668
</pre>
=={{header|Befunge}}==
Slow (iterative) version:
<
>+\:v >:5%#v_^
@.$_^#! < > ^</
{{Out}}
<pre>233168</pre>
Fast (analytic) version:
<
{{Out}}
<pre>233168</pre>
=={{header|BQN}}==
A naive solution:
<syntaxhighlight lang="bqn">Sum ← +´·(0=3⊸|⌊5⊸|)⊸/↕</syntaxhighlight>
A much faster solution:
<syntaxhighlight lang="bqn">Sum ← {
m ← (0=3⊸|⌊5⊸|)↕15 ⋄ h‿l ← 15(⌊∘÷˜∾|)𝕩
(+´l↑m×15(×+↕∘⊣)h) + (15×(+´m)×2÷˜h×h-1) + h×+´m×↕15
}</syntaxhighlight>
{{out}}
<pre>
Sum 1000
233168
</pre>
([https://mlochbaum.github.io/BQN/try.html#code=U3VtIOKGkCB7CiAgbSDihpAgKDA9M+KKuHzijIo14oq4fCnihpUxNSDii4QgaOKAv2wg4oaQIDE1KOKMiuKImMO3y5ziiL58KfCdlakKICAoK8K0bOKGkW3DlzE1KMOXK+KGleKImOKKoyloKSArICgxNcOXKCvCtG0pw5cyw7fLnGjDl2gtMSkgKyBow5crwrRtw5fihpUxNQp9CgpTdW0gMTAwMAo= online REPL])
=={{header|C}}==
===Simple version===
<
#include <stdlib.h>
Line 367 ⟶ 777:
printf("%lld\n", sum35(limit));
return 0;
}</
{{Out}}
<pre>$ ./a.out
Line 376 ⟶ 786:
===Fast version with arbitrary precision===
{{libheader|GMP}}
<
#include <gmp.h>
Line 428 ⟶ 838:
mpz_clear(limit);
return 0;
}</
{{Out}}
<pre>$ ./a.out
Line 438 ⟶ 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.
<
using System;
using System.Collections.Generic;
Line 479 ⟶ 889:
}
}
</syntaxhighlight>
{{out}}
The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168
Line 494 ⟶ 904:
=={{header|C++}}==
<
#include <iostream>
Line 537 ⟶ 947:
return system( "pause" );
}
</syntaxhighlight>
{{out}}
<pre>
Sum is 233168 for n = 1000
</pre>
===Fast version with arbitrary precision===
{{libheader|Boost}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
template <typename T> T sum_multiples(T n, T m) {
n -= T(1);
n -= n % m;
return (n / m) * (m + n) / T(2);
}
template <typename T> T sum35(T n) {
return sum_multiples(n, T(3)) + sum_multiples(n, T(5)) -
sum_multiples(n, T(15));
}
int main() {
using big_int = boost::multiprecision::cpp_int;
std::cout << sum35(1000) << '\n';
std::cout << sum35(big_int("100000000000000000000")) << '\n';
}</syntaxhighlight>
{{out}}
<pre>
233168
2333333333333333333316666666666666666668
</pre>
=={{header|Clojure}}==
Quick, concise way:
<
(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:
<syntaxhighlight lang="clojure">(defn sum-mults [n & mults]
(transduce (filter (fn [x] (some (fn [mult] (zero? (mod x mult))) mults)))
+ (range n)))
(println (sum-mults 1000 3 5))</syntaxhighlight>
Or optimized (translated from Groovy):
<
(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))</
=={{header|COBOL}}==
Line 561 ⟶ 1,010:
Using OpenCOBOL.
<
Identification division.
Program-id. three-five-sum.
Line 585 ⟶ 1,034:
or function mod(ws-the-number, 5) = zero
then add ws-the-number to ws-the-sum.
</syntaxhighlight>
Output:
Line 593 ⟶ 1,042:
Using triangular numbers:
<
Identification division.
Program-id. three-five-sum-fast.
Line 641 ⟶ 1,090:
Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2.
goback.
</syntaxhighlight>
Output:
Line 651 ⟶ 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)
<
IDENTIFICATION DIVISION.
PROGRAM-ID. SUM35.
Line 692 ⟶ 1,141:
EXIT.
END PROGRAM SUM35.
</syntaxhighlight>
Output
<pre>+00233333333166666668</pre>
Line 698 ⟶ 1,147:
=={{header|Common Lisp}}==
Slow, naive version:
<
(loop for x below limit
when (or (zerop (rem x 3)) (zerop (rem x 5)))
sum x))</
Fast version (adapted translation of [[#Tcl|Tcl]]):
<
(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)))))))</
{{Out}}
Line 720 ⟶ 1,169:
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE Sum3_5;
IMPORT StdLog, Strings, Args;
Line 747 ⟶ 1,196:
END Sum3_5.
</syntaxhighlight>
Execute: ^Q Sum3_5.Compute 1000 ~ <br/>
Output:
Line 753 ⟶ 1,202:
Sum: 233168
</pre>
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
# sum multiples up to given input
interface SumMulTo(mul: uint32, to: uint32): (rslt: uint32);
# naive implementation
sub naiveSumMulTo implements SumMulTo is
rslt := 0;
var cur := mul;
while cur < to loop
rslt := rslt + cur;
cur := cur + mul;
end loop;
end sub;
# number theoretical implementation
sub fastSumMulTo implements SumMulTo is
to := (to - 1)/mul;
rslt := mul * to * (to + 1)/2;
end sub;
# sum multiples of 3 and 5 up to given number using given method
sub sum35(to: uint32, sum: SumMulTo): (rslt: uint32) is
rslt := sum(3, to) + sum(5, to) - sum(15, to);
end sub;
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method: "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
</syntaxhighlight>
{{out}}
<pre>Naive method: 233168
Fast method: 233168</pre>
=={{header|Crystal}}==
{{trans|Ruby}}
Short, but not optimized.
<
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end
puts sum_3_5_multiples(1000)</
{{out}}
<pre>
Line 771 ⟶ 1,256:
To conform to task requirements, and other versions,
modified to find sums below n.
<
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)
Line 783 ⟶ 1,268:
# For extra credit
puts g(3,5,"100000000000000000000".to_big_i - 1)
puts g(3,5,"100000000000000000000".to_big_i)</
{{out}}
<pre>
232169
233168
2333333333333333333216666666666666666669
2333333333333333333316666666666666666668
</pre>
Alternative faster version 2.
<
def sumMul(n, f)
Line 806 ⟶ 1,291:
(1..20).each do |e| limit = 10.to_big_i ** e
puts "%2d:%22d %s" % [e, limit, sum35(limit)]
end</
{{out}}
<pre>
Line 832 ⟶ 1,317:
=={{header|D}}==
<
BigInt sum35(in BigInt n) pure nothrow {
Line 849 ⟶ 1,334:
1000.BigInt.sum35.writeln;
(10.BigInt ^^ 20).sum35.writeln;
}</
{{out}}
<pre>
Line 858 ⟶ 1,343:
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}}==
<
{$APPTYPE CONSOLE}
Line 880 ⟶ 1,398:
end;
writeln(sum);
end.</
{{out}}
<pre>233168</pre>
=={{header|Déjà Vu}}==
<
0
for i range 1 -- n:
Line 891 ⟶ 1,409:
+ i
!. sum-divisible 1000</
{{out}}
<pre>233168</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func msum35 n .
for i = 1 to n
if i mod 3 = 0 or i mod 5 = 0
sum += i
.
.
return sum
.
print msum35 999
</syntaxhighlight>
=={{header|EchoLisp}}==
<
(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when
Line 930 ⟶ 1,461:
❌ error: expected coprimes (42 666)
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
Line 962 ⟶ 1,493:
end
</syntaxhighlight>
{{out}}
<pre>
Line 970 ⟶ 1,501:
=={{header|Elixir}}==
Simple (but slow)
<
233168</
Fast version:
{{trans|Ruby}}
<
def sumMul(n, f) do
n1 = div(n - 1, f)
Line 989 ⟶ 1,520:
n = round(:math.pow(10, i))
IO.puts RC.sum35(n)
end)</
{{out}}
Line 1,016 ⟶ 1,547:
=={{header|Emacs Lisp}}==
Vanilla:
<syntaxhighlight lang="lisp">(defun sum-3-5 (n)
(let ((sum 0))
(setq sum (+ sum x))))
sum))</syntaxhighlight>
{{libheader|seq.el}}
<syntaxhighlight lang="lisp">(defun sum-3-5 (n)
(apply #'+ (seq-filter
(
(number-sequence 1 (- n 1)))))</syntaxhighlight>
=={{header|Erlang}}==
<
sum_3_5(X, Total) when X < 3 -> Total;
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
Line 1,050 ⟶ 1,571:
sum_3_5(X-1, Total).
io:format("~B~n", [sum_3_5(1000)]).</
{{out}}
Line 1,056 ⟶ 1,577:
=={{header|F_Sharp|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)
Line 1,069 ⟶ 1,590:
[for i = 0 to 30 do yield i]
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))</
{{out}}
<pre style="height:5em">233168
Line 1,114 ⟶ 1,635:
<br>
{{works with|Factor|0.99 2019-10-06}}
<
: sum-multiples ( m n upto -- sum )
Line 1,122 ⟶ 1,643:
3 5 1000 sum-multiples .
3 5 1e20 sum-multiples .</
{{out}}
<pre>
Line 1,131 ⟶ 1,652:
=={{header|FBSL}}==
Derived from BASIC version
<
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
Line 1,145 ⟶ 1,666:
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
</syntaxhighlight>
Output
<pre>233168
Line 1,153 ⟶ 1,674:
=={{header|Forth}}==
<
0 swap
3 do
Line 1,164 ⟶ 1,685:
. ;
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.
<
: >dtriangular ( n -- d )
Line 1,210 ⟶ 1,731:
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668 ok
</syntaxhighlight>
=={{header|Fortran}}==
Line 1,216 ⟶ 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.
<syntaxhighlight lang="fortran">
INTEGER*8 FUNCTION SUMI(N) !Sums the integers 1 to N inclusive.
Calculates as per the young Gauss: N*(N + 1)/2 = 1 + 2 + 3 + ... + N.
Line 1,256 ⟶ 1,777:
GO TO 10 !Have another go.
END !So much for that.
</syntaxhighlight>
Sample output:
<pre>
Line 1,279 ⟶ 1,800:
=={{header|FreeBASIC}}==
<
Function sum35 (n As UInteger) As UInteger
Line 1,293 ⟶ 1,814:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,302 ⟶ 1,823:
=={{header|Frink}}==
Program has a brute-force approach for n=1000, and also inclusion/exclusion for larger values.
<syntaxhighlight lang="frink">
sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]
Line 1,315 ⟶ 1,836:
println["The sum of all the multiples of 3 or 5 below 1000 is $sum999"]
println["The sum of all multiples less than 1e20 is " + sum35big[1_00000_00000_00000_00000 - 1]]
</syntaxhighlight>
{{Out}}
<pre>
The sum of all the multiples of 3 or 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
_n = 1000
void local fn DoIt
long i, sum = 0
for i = 0 to _n - 1
if ( i mod 3 == 0 or i mod 5 == 0 )
sum += i
end if
next
NSLog(@"%ld",sum)
end fn
fn Doit
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
=={{header|Go}}==
<
import "fmt"
Line 1,344 ⟶ 1,892:
return n
}</
{{out}}
<pre>
Line 1,350 ⟶ 1,898:
</pre>
Extra credit:
<
import (
Line 1,380 ⟶ 1,928:
s := sum2(b3)
return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1)
}</
{{out}}
<pre>
Line 1,388 ⟶ 1,936:
=={{header|Groovy}}==
<
def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }</
Test Code:
<
println "Checking $arg == $value"
assert sum35(arg) == value
}</
{{out}}
<pre>Checking 1000 == 233168
Line 1,401 ⟶ 1,949:
=={{header|Haskell}}==
Also a method for calculating sum of multiples of any list of numbers.
<
----------------- 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,
]
---------------- FOR VARIABLE LENGTH INPUTS --------------
pairLCM :: [Integer] -> [Integer]
pairLCM [] = []
pairLCM (x : xs) = (lcm x <$> xs) <> pairLCM xs
sumMulS :: Integer -> [Integer] -> Integer
sumMulS _ [] = 0
sumMulS n s =
( ((-) . sum . fmap f)
<*> (g . pairLCM)
)
(nub s)
where
f = sumMul n
g = sumMulS n</syntaxhighlight>
{{out}}
<pre>233168
Line 1,442 ⟶ 2,001:
The following works in both langauges.
<
n := (integer(A[1]) | 1000)-1
write(sum(n,3)+sum(n,5)-sum(n,15))
Line 1,449 ⟶ 2,008:
procedure sum(n,m)
return m*((n/m)*(n/m+1)/2)
end</
Sample output:
Line 1,463 ⟶ 2,022:
=={{header|J}}==
The problem can also be solved with a simple use of inclusion/exclusion; this solution is more in keeping with how one could approach the problem from a more traditional language.
<syntaxhighlight lang="j">
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
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 < 1000 is 233168
The sum of the multiples of 3 or 5 < 1000 is still 233168
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668
</pre>
=={{header|Java}}==
===Simple Version===
<
public static long getSum(long n) {
long sum = 0;
Line 1,520 ⟶ 2,063:
System.out.println(getSum(1000));
}
}</
{{out}}
<pre>233168</pre>
===Extra Credit===
<syntaxhighlight lang="java">
import java.math.BigInteger;
Line 1,565 ⟶ 2,108:
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,599 ⟶ 2,142:
===ES5===
JavaScript is better equipped for flexibility than for scale. The value of <syntaxhighlight lang
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,605 ⟶ 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:
<
// [n] -> n -> n
Line 1,663 ⟶ 2,206:
JSON.stringify(lstTable);
})([3, 5], 8);</
Line 1,689 ⟶ 2,232:
|}
<
["10^4",23331668],["10^5",2333316668],["10^6",233333166668],
["10^7",23333331666668],["10^8",2333333316666668]]</
====With wheel increments====
<
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====
<
return tri(n,3) + tri(n,5) - tri(n,15)
function tri(n, f) {
Line 1,705 ⟶ 2,248:
return f * n * (n+1) / 2
}
}</
'''This:'''
<
document.write(10, '<sup>', i, '</sup> ', sm35(n), '<br>')
}</
{{out}}
10<sup>1</sup> 23
Line 1,723 ⟶ 2,266:
===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 =
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))
);
//
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo =
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
// quot :: Int -> Int -> Int
const quot = n =>
m => Math.floor(n / m);
// ------------------------ DISPLAY ------------------------
// compose (<<<) ::
const compose =
// A function defined
// 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();
})();</syntaxhighlight>
{{Out}}
<pre>Sums for n = 10^1 thru 10^8:
10 -> 23
100 -> 2318
1000 -> 233168
10000 -> 23331668
100000 -> 2333316668
1000000 -> 233333166668
10000000 -> 23333331666668
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}}==
<syntaxhighlight lang="jq">
def sum_multiples(d):
((./d) | floor) | (d * . * (.+1))/2 ;
Line 1,772 ⟶ 2,444:
def task(a;b):
. - 1
| sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);</
jq does not (yet) support arbitrary-precision integer arithmetic but converts large integers to floats, so:
<syntaxhighlight lang="jq">
1000 | task(3;5) # => 233168
10e20 | task(3;5) # => 2.333333333333333e+41</
=={{header|Julia}}==
sum multiples of each, minus multiples of the least common multiple (lcm). Similar to MATLAB's version.
<
Output:
<pre>julia> multsum(3, 5, 1000)
Line 1,818 ⟶ 2,491:
(100000000000000000000,2333333333333333333316666666666666666668)</pre>
a slightly more efficient version
<
multsum(n, m, lim) = multsum(n, lim) + multsum(m, lim) - multsum(lcm(n,m), lim)</
=={{header|Kotlin}}==
<
import java.math.BigInteger
Line 1,852 ⟶ 2,525:
val e20 = big100k * big100k * big100k * big100k
println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
}</
{{out}}
Line 1,861 ⟶ 2,534:
=={{header|Lasso}}==
<
while(#limit <= 100000) => {^
local(s = 0)
Line 1,869 ⟶ 2,542:
'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
#limit = integer(#limit->asString + '0')
^}</
{{out}}
<pre>The sum of multiples of 3 or 5 between 1 and 0 is: 0
Line 1,882 ⟶ 2,555:
Uses the IPints library when the result will be very large.
<
include "sys.m"; sys: Sys;
Line 1,954 ⟶ 2,627:
sub(isum_multiples(ints[15], limit)));
}
</syntaxhighlight>
{{out}}
Line 1,962 ⟶ 2,635:
=={{header|Lingo}}==
<
res = 0
repeat with i = 0 to (n-1)
Line 1,970 ⟶ 2,643:
end repeat
return res
end</
<
-- 233168</
=={{header|LiveCode}}==
<
repeat with i = 0 to (n-1)
if i mod 3 = 0 or i mod 5 = 0 then
Line 1,985 ⟶ 2,658:
end sumUntil
put sumUntil(1000) // 233168</
=={{header|Lua}}==
{{trans|Tcl}}
<syntaxhighlight lang="lua">
function tri (n) return n * (n + 1) / 2 end
Line 2,002 ⟶ 2,675:
print(sum35(1000))
print(sum35(1e+20))
</syntaxhighlight>
{{out}}
<pre>
Line 2,011 ⟶ 2,684:
=={{header|Maple}}==
By using symbolic function <code>sum</code> instead of numeric function <code>add</code> the program <code>F</code> will run O(1) rather than O(n).
<syntaxhighlight lang="maple">
F := unapply( sum(3*i,i=1..floor((n-1)/3))
+ sum(5*i,i=1..floor((n-1)/5))
Line 2,019 ⟶ 2,692:
F(10^20);
</syntaxhighlight>
Output:
<pre>
Line 2,038 ⟶ 2,711:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] -
Sum[k, {k, 15, n - 1, 15}]
sum35[1000]</syntaxhighlight>
{{out}}
<pre>233168</pre>
<syntaxhighlight lang
{{out}}
<pre>233333333333333333333166666666666666666668</pre>
Another alternative is
<
=={{header|MATLAB}} / {{header|Octave}}==
<
<pre>ans = 233168</pre>
Another alternative is
<
Of course, it's more efficient to use [http://mathforum.org/library/drmath/view/57919.html Gauss' approach] of adding subsequent integers:
<
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</
<pre>ans = 233168</pre>
=={{header|Maxima}}==
<
[kmax],
Line 2,080 ⟶ 2,751:
sum35(1000);
sum35(10^20);</
Output:
<pre>
Line 2,090 ⟶ 2,761:
=={{header|MiniScript}}==
First, the simple implementation. It loops by threes and fives, and in the second loop, skips any multiples of five that are also divisible by three.
<
sum35 = function(n)
sum = 0
Line 2,106 ⟶ 2,775:
end function
print sum35(1000)</
{{out}}
<pre>
Now the fast version.
{{trans|D}}
<
sumMul = function(n, f)
n1 = floor((n - 1) / f)
Line 2,122 ⟶ 2,791:
end function
print sum35fast(1000)</
{{out}}
<pre>
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 0 П0 3 П4 ИП4 3 / {x} x#0
17 ИП4 5 / {x} x=0 21 ИП0 ИП4 +
П0 КИП4 ИП1 ИП4 - x=0 05 ИП0 С/П</
Input: ''n''.
Line 2,138 ⟶ 2,807:
{{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.
<
sum = 0
for i in range(3, n - 1)
Line 2,148 ⟶ 2,817:
end
println getSum(1000)</
{{out}}
<pre>233168</pre>
Line 2,154 ⟶ 2,823:
=={{header|NetRexx}}==
Portions translation of [[#Raku|Raku]]
<
options replace format comments java crossref symbols nobinary
numeric digits 40
Line 2,231 ⟶ 2,900:
say
return
</syntaxhighlight>
{{out}}
<pre>
Line 2,289 ⟶ 2,958:
=={{header|Nim}}==
Here is the solution using normal integers.
<syntaxhighlight lang="nim">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)</
{{out}}
<pre>233168</pre>
To compute until 1e20, we have to use big integers. As Nim doesn’t provided them in its library, we have to use a third party library, either "bigints" or "bignum".
{{trans|Raku}}
<syntaxhighlight lang="nim">import bigints
proc sumMults(first: int32, limit: BigInt): BigInt =
Line 2,313 ⟶ 2,988:
while x < "1000000000000000000000000000000".initBigInt:
echo sum35 x
x *= 10</
{{out}}
<pre>0
23
2318
Line 2,348 ⟶ 3,024:
=={{header|Objeck}}==
{{trans|Java}}
<
function : native : GetSum(n : Int) ~ Int {
sum := 0;
Line 2,364 ⟶ 3,040:
}
}
</syntaxhighlight>
Output:
Line 2,371 ⟶ 3,047:
</pre>
=={{header|Odin}}==
Note: 1e19 is the largest sum that can be calculated with 128 bit integers.
<syntaxhighlight lang="odin">
package main
import "core:fmt"
sumdiv :: proc(n, d: i128) -> i128 {
m := n / d
return (m % 2 == 0)? \
m/2 * (m + 1) * d : \
(m + 1)/2 * m * d
}
sum3or5 :: proc(n: i128) -> i128 {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)
}
main :: proc() {
sum := 0
for n in 1..=999 {
if n % 3 == 0 || n % 5 == 0 {
sum += n
}
}
fmt.println("The sum of all multiples of 3 and 5 < 1000 is", sum)
fmt.println("The sum of all multiples of 3 and 5 < 1e19 is", sum3or5(1e19 - 1))
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of all multiples of 3 and 5 < 1000 is 233168
The sum of all multiples of 3 and 5 < 1e19 is 23333333333333333331666666666666666668
</pre>
=={{header|OCaml}}==
<
let termial x = (x *
3 * (termial (n / 3)
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</syntaxhighlight>
{{out}}
<
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}}==
<
Output:
Line 2,395 ⟶ 3,134:
=={{header|Ol}}==
<
(print
(fold (lambda (s x)
Line 2,401 ⟶ 3,140:
0 (iota 1000)))
; ==> 233168
</syntaxhighlight>
=={{header|PARI/GP}}==
<
a(n)=ct(n,3)+ct(n,5)-ct(n,15);
a(1000)
a(1e20)</
{{output}}
<pre>
Line 2,418 ⟶ 3,157:
{{works with|Free Pascal|2.6.2}}
<
function Multiple(x, y: integer): Boolean;
Line 2,440 ⟶ 3,179:
{ 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|Tcl]]
<
//sum of all positive multiples of 3 or 5 below n
Line 2,465 ⟶ 3,204:
sum := sum-cntSumdivisibleBelowN(n,3*5);
writeln(sum);
end.</
output
<pre>233168</pre>
=={{header|Perl}}==
<
use
use experimental qw(signatures);
use List::Util qw( sum ) ;
sub sum_3_5($limit) {
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}
{{Out}}
<pre>The sum is 233168
{{Trans|Tcl}}
An alternative approach, using the analytical solution from the Tcl example.
<syntaxhighlight lang
use experimental qw(signatures);
sub tri($n) {
}
sub sum_multiples($n, $limit) {
$n * tri( int( ($limit - 1) / $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
{{Out}}
<pre>233168
Line 2,510 ⟶ 3,251:
===native===
note the result of sum35() is inaccurate above 2^53 on 32-bit, 2^64 on 64-bit.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sum35</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span>
<span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">-</span>
<span style="color: #000000;">sumMul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">sp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s%s%s %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sum35</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,542 ⟶ 3,285:
{{libheader|Phix/mpfr}}
Fast analytical version with arbitrary precision
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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;">procedure</span> <span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpz</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">mpz_sub_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">);</span>
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_fdiv_q_2exp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">mpz</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">sp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"1"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sum_multiples</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %s\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,598 ⟶ 3,344:
Naive version (slow) :
<
$sum = 0;
for ($i = 1 ; $i < $max ; $i++) {
Line 2,606 ⟶ 3,352:
}
echo $sum, PHP_EOL;
</syntaxhighlight>
{{out}}
Line 2,613 ⟶ 3,359:
Fast version:
<
// Number of multiples of $divisor <= $max
$num = floor($max / $divisor);
Line 2,624 ⟶ 3,370:
+ sum_multiples($max - 1, 5)
- sum_multiples($max - 1, 15);
echo $sum, PHP_EOL;</
{{out}}
Line 2,634 ⟶ 3,380:
These functions allow for arbitrary-length integers to be worked with.
<
// Number of multiples of $divisor <= $max
$num = gmp_div($max, $divisor);
Line 2,652 ⟶ 3,398:
);
printf('%22s : %s' . PHP_EOL, gmp_strval($n), $sum);
}</
{{out}}
Line 2,678 ⟶ 3,424:
</pre>
=={{header|Picat}}==
Uses both the naive method and inclusion/exclusion.
<syntaxhighlight lang="picat">
sumdiv(N, D) = S =>
M = N div D,
S = (M*(M + 1) div 2) * D.
sum35big(N) = sumdiv(N, 3) + sumdiv(N, 5) - sumdiv(N, 15).
main =>
Upto1K = [N: N in 1..999, (N mod 3 = 0; N mod 5 = 0)].sum,
writef("The sum of all multiples of 3 and 5 below 1000 is %w%n", Upto1K),
writef("The sum of all multiples less than 1e20 is %w%n", sum35big(99999_99999_99999_99999)).
</syntaxhighlight>
{{Out}}
<pre>
The sum of all multiples of 3 and 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668
</pre>
=={{header|PicoLisp}}==
<
(let N1 (/ (dec N) F)
(*/ F N1 (inc N1) 2) ) )
Line 2,688 ⟶ 3,453:
(-
(+ (sumMul N 3) (sumMul N 5))
(sumMul N 15) ) ) ) )</
{{out}}
<pre>
Line 2,714 ⟶ 3,479:
=={{header|PL/I}}==
<
declare (i, n) fixed(10), sum fixed (31) static initial (0);
Line 2,726 ⟶ 3,491:
put edit ( trim(sum) ) (A);
end threeor5;</
Outputs:
<pre>
Line 2,735 ⟶ 3,500:
The number of multiples of 3 or 5 below 10000000 is 23333331666668
The number of multiples of 3 or 5 below 100000000 is 2333333316666668</pre>
==={{header|PL/I-80}}===
Although a brute-force approach gets the job done with a minimum
of fuss, and would generally be the preferred first choice, the use of Gauss's
summation formula will significantly speed up running time if
summing to higher limits than required by the problem. The solution
here demonstrates both approaches
<syntaxhighlight lang = "PL/I">
sum35_demo: proc options (main);
dcl limit fixed bin;
limit = 1000;
put skip list ('Sum of all multiples of 3 and 5 below', limit);
put skip edit ('Sum = ', sum35(limit)) ((a),(f(6)));
put skip edit ('Also: ', sum35alt(limit)) ((a),(f(6)));
stop;
sum35:
proc(limit) returns (float bin);
dcl
(limit, i) fixed bin,
sum float bin;
sum = 0;
do i=1 to (limit-1);
if mod(i,3) = 0 | mod(i,5) = 0 then
sum = sum + i;
end;
return (sum);
end sum35;
sum35alt:
proc(limit) returns (float bin);
dcl
limit fixed bin,
sum float bin;
sum = sum_of_multiples(3, limit) +
sum_of_multiples(5, limit) -
sum_of_multiples(15, limit);
return (sum);
end sum35alt;
sum_of_multiples:
proc(n, limit) returns (float bin);
dcl
(n, limit, i) fixed bin,
m float bin;
m = (limit - 1) / n;
return (n * m * (m + 1) / 2);
end sum_of_multiples;
end sum35_demo;
</syntaxhighlight>
{{out}}
<pre>
Sum of all multiples of 3 and 5 below 1000
Sum = 233168
Also: 233168
</pre>
=={{header|PowerShell}}==
<
function SumMultiples ( [int]$Base, [int]$Upto )
{
Line 2,747 ⟶ 3,570:
# Calculate the sum of the multiples of 3 and 5 up to 1000
( SumMultiples -Base 3 -Upto 1000 ) + ( SumMultiples -Base 5 -Upto 1000 ) - ( SumMultiples -Base 15 -Upto 1000 )
</syntaxhighlight>
{{out}}
<pre>
Line 2,753 ⟶ 3,576:
</pre>
For arbitrarily large integers, simply change the variable type.
<
function SumMultiples ( [bigint]$Base, [bigint]$Upto )
{
Line 2,764 ⟶ 3,587:
$Upto = [bigint]::Pow( 10, 210 )
( SumMultiples -Base 3 -Upto $Upto ) + ( SumMultiples -Base 5 -Upto $Upto ) - ( SumMultiples -Base 15 -Upto $Upto )
</syntaxhighlight>
{{out}}
<pre>
Line 2,770 ⟶ 3,593:
</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.
<
{
Param
Line 2,800 ⟶ 3,623:
}
$Sum
}</
{{out}}
<pre>Get-SumOfMultiples</pre>
Line 2,810 ⟶ 3,633:
=={{header|Prolog}}==
===Slow version===
<
sum_of_multiples_of_3_and_5(N, 1, 0, TT).
Line 2,826 ⟶ 3,649:
sum_of_multiples_of_3_and_5(N, K1, C5, S).
</syntaxhighlight>
===Fast version===
<
maplist(compute_sum(N), [3,5,15], [TT3, TT5, TT15]),
TT is TT3 + TT5 - TT15.
Line 2,838 ⟶ 3,661:
; N2 is N div N1),
Sum is N1 * N2 * (N2 + 1) / 2.
</syntaxhighlight>
Output :
Line 2,849 ⟶ 3,672:
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
EnableExplicit
Line 2,870 ⟶ 3,693:
CloseConsole()
EndIf
</syntaxhighlight>
{{out}}
Line 2,879 ⟶ 3,702:
=={{header|Python}}==
Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()
<
'Direct count'
# note: ranges go to n-1
Line 2,910 ⟶ 3,733:
# Scalability
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))</
{{out}}
Line 2,928 ⟶ 3,751:
Or, more generally – taking the area under the straight line between the first multiple and the last:
{{Works with|Python|3.7}}
<
Line 2,998 ⟶ 3,821:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Summed multiples of 3 and 5 up to n:
Line 3,017 ⟶ 3,840:
=={{header|Q}}==
<
s35 each 10 100 1000 10000 1000000</
Extra credit, using the summation formula:
<
s35:{a:x-1; (3*sn floor a%3) + (5*sn floor a%5) - (15*sn floor a%15)}
s35 e+10</
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ dup 1+ * 2 / ] is triangulared ( n --> n )
[ 1 -
dup 3 / triangulared 3 *
over 5 / triangulared 5 * +
swap 15 / triangulared 15 * - ] is sum-of-3s&5s ( n --> n )
1000 sum-of-3s&5s echo cr
10 20 ** sum-of-3s&5s echo cr</syntaxhighlight>
{{out}}
<pre>233168
2333333333333333333316666666666666666668
</pre>
=={{header|R}}==
<
seq(3, n-1, by = 3), seq(5, n-1, by = 5))))
m35(1000) # 233168</
=={{header|Racket}}==
<
#lang racket
(require math)
Line 3,060 ⟶ 3,902:
(for/list ([k 20]) (analytical k))
</syntaxhighlight>
Output:
<
'(0 23 2318 233168 23331668 2333316668 233333166668)
'(0
Line 3,084 ⟶ 3,926:
233333333333333333166666666666666668
23333333333333333331666666666666666668)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say sum35 1000;</
{{out}}
<pre>233168</pre>
Here's an analytical approach that scales much better for large values.
<syntaxhighlight lang="raku"
(my $last = $limit - 1) -= $last % $first;
($last div $first) * ($first + $last) div 2;
Line 3,103 ⟶ 3,945:
}
say sum35($_) for 1,10,100...10**30;</
{{out}}
<pre>0
Line 3,139 ⟶ 3,981:
=={{header|REXX}}==
===version 1===
<
* 14.05.2013 Walter Pachl
**********************************************************************/
Line 3,150 ⟶ 3,992:
s=s+i
End
Return s</
Output:
<pre>233168</pre>
===version 2===
<
* Translation from Raku->NetRexx->REXX
* 15.05.2013 Walter Pachl
Line 3,178 ⟶ 4,020:
last = last - last // first
sum = (last % first) * (first + last) % 2
return sum</
Output:
<pre> 1 0
Line 3,214 ⟶ 4,056:
===version 3===
This version automatically adjusts the numeric digits.
The formula used is a form of the Gauss Summation formula.
<
parse arg N t . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=
if t=='' | t=="," then t=
numeric digits 1000; w= 2 + length(t)
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' _ .
y= right( (m/1)'e' || (_+0), w)"-1"
z= n - 1; if t==1 then y=
say 'integers from 1 ──►' y " is " sumDiv(z,3) + sumDiv(z,5) - sumDiv(z,3*5)
N= N'0'
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</
<pre>
The sum of all positive integers that are a multiple of 3 and 5 are:
Line 3,239 ⟶ 4,081:
integers from 1 ──► 999 is 233168
</pre>
(Shown at three-quarter size.)
<pre style="font-size:75%;height:188ex">
The sum of all positive integers that are a multiple of 3 and 5 are:
Line 3,331 ⟶ 4,176:
=={{header|Ring}}==
<
see sum35(1000) + nl
Line 3,342 ⟶ 4,187:
func tri n
return n * (n + 1) / 2
</syntaxhighlight>
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
===Simple solution===
Just counting...
≪ 0 1 DO
1 +
IF DUP 3 MOD NOT OVER 5 MOD NOT OR THEN SWAP OVER + SWAP END
UNTIL DUP 4 PICK == END
ROT DROP2
≫
===Efficient solution===
This is a fast approach to calculate the sum for higher values of n, taking into account that:
# the sum of multiples of 3 and 5 is the sum of multiples of 3 plus the sum of multiples of 5, minus the sum of multiples of 15 to remove double counting
# the sum of multiples of m being < n is equal to m*(1+2+ ... k) with k =[n/m]
# 1+2+...k = k*(k+1)/2
Unfortunately, RPL can only handle double precision numbers, which prevents from precisely calculating the sum for n > 1E+15
≪ → n
≪ 0 1 3 FOR j
{ 3 5 -15 } j GET
n OVER / ABS IP
DUP 1 + * 2 / * +
NEXT
≫ ≫
‘SUM35’ STO
999 SUM35
{{out}}
<pre>
1: 233168
</pre>
=={{header|Ruby}}==
Simple Version (Slow):
<
(1...n).select{|i|i%3==0 or i%5==0}.
end
puts sum35(1000) #=> 233168</
Fast Version:
<
#
# Nigel_Galloway
Line 3,364 ⟶ 4,240:
# For extra credit
puts g(3,5,100000000000000000000-1)</
{{out}}
Line 3,374 ⟶ 4,250:
Other way:
{{trans|D}}
<
n1 = (n - 1) / f
f * n1 * (n1 + 1) / 2
Line 3,385 ⟶ 4,261:
for i in 1..20
puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)]
end</
{{out}}
Line 3,412 ⟶ 4,288:
=={{header|Run BASIC}}==
<
end
function multSum35(n)
Line 3,418 ⟶ 4,294:
If (i mod 3 = 0) or (i mod 5 = 0) then multSum35 = multSum35 + i
next i
end function</
=={{header|Rust}}==
<
extern crate rug;
Line 3,458 ⟶ 4,334:
}
}
</syntaxhighlight>
Output :
<pre>
Line 3,471 ⟶ 4,347:
</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}}==
<
// Simplest solution but limited to Ints only
Line 3,493 ⟶ 4,394:
{
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
}</
{{out}}
<pre> 1 => 0
Line 3,518 ⟶ 4,419:
=={{header|Scheme}}==
<
Output:
Line 3,527 ⟶ 4,428:
Or, more clearly by decomposition:
<
(or (zero? (remainder x 3))
(zero? (remainder x 5))))
Line 3,534 ⟶ 4,435:
(+ tot (if (fac35? x) x 0)))
(fold fac35filt 0 (iota 1000))</
Output:
Line 3,543 ⟶ 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!
<
(let* ((n1 (quotient (- n 1) fac))
(n2 (+ n1 1)))
Line 3,553 ⟶ 4,454:
(fast35sum 1000)
(fast35sum 100000000000000000000)
</syntaxhighlight>
Output:
Line 3,562 ⟶ 4,463:
=={{header|Seed7}}==
<
include "bigint.s7i";
Line 3,586 ⟶ 4,487:
writeln(sum35(1000_));
writeln(sum35(10_ ** 20));
end func;</
{{out}}
Line 3,596 ⟶ 4,497:
=={{header|Sidef}}==
{{trans|Ruby}}
<
var m = int((n - 1) / f)
f * m * (m + 1) / 2
Line 3,607 ⟶ 4,508:
for i in (1..20) {
printf("%2s:%22s %s\n", i, 10**i, sum35(10**i))
}</
{{out}}
<pre>
Line 3,634 ⟶ 4,535:
=={{header|Simula}}==
(referenced from [[Greatest common divisor#Simula|Greatest common divisor]])
<
! Project Euler problem 1: multiples of 3 or 5 below 1000 & 10**20;
BEGIN
Line 3,687 ⟶ 4,588:
OUTIMAGE
END
END</
{{out}}
sum of positive multiples of 3 and 5: 233168<br />
Line 3,700 ⟶ 4,601:
=={{header|Stata}}==
=== With a dataset ===
<
set obs 999
gen a=_n
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)</
=== With Mata ===
<
a=1..999
sum(a:*(mod(a,3):==0 :| mod(a,5):==0))</
=={{header|Swift}}==
<
Line 3,732 ⟶ 4,633:
print(sumofmult)
</syntaxhighlight>
=={{header|Tcl}}==
<
proc mul35sum {n} {
for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} {
Line 3,751 ⟶ 4,652:
}
return $total
}</
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).
<
proc tcl::mathfunc::triangle {n} {expr {
$n * ($n+1) / 2
Line 3,761 ⟶ 4,662:
incr n -1
expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
}</
Demonstrating:
<
puts [mul35sum 10000000],[sum35 10000000]
# Just the quick one; waiting for the other would get old quickly...
puts [sum35 100000000000000000000]</
{{out}}
<pre>233168,233168
Line 3,773 ⟶ 4,674:
</pre>
=={{header|TI SR-56}}==
=== Iterative solution ===
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Sum Multiples" (Iterative)
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 33 || STO || 50 || || 75 ||
|-
| 01 04 || 4 || 26 00 || 0 || 51 || || 76 ||
|-
| 02 04 || 4 || 27 57 || *subr || 52 || || 77 ||
|-
| 03 52 || ( || 28 00 || 0 || 53 || || 78 ||
|-
| 04 52 || ( || 29 03 || 3 || 54 || || 79 ||
|-
| 05 34 || RCL || 30 12 || INV || 55 || || 80 ||
|-
| 06 00 || 0 || 31 37 || *x=t || 56 || || 81 ||
|-
| 07 54 || / || 32 03 || 3 || 57 || || 82 ||
|-
| 08 05 || 5 || 33 08 || 8 || 58 || || 83 ||
|-
| 09 53 || ) || 34 34 || RCL || 59 || || 84 ||
|-
| 10 12 || INV || 35 00 || 0 || 60 || || 85 ||
|-
| 11 29 || *Int || 36 35 || SUM || 61 || || 86 ||
|-
| 12 64 || x || 37 01 || 1 || 62 || || 87 ||
|-
| 13 52 || ( || 38 27 || *dsz || 63 || || 88 ||
|-
| 14 34 || RCL || 39 02 || 2 || 64 || || 89 ||
|-
| 15 00 || 0 || 40 07 || 7 || 65 || || 90 ||
|-
| 16 54 || / || 41 34 || RCL || 66 || || 91 ||
|-
| 17 03 || 3 || 42 01 || 1 || 67 || || 92 ||
|-
| 18 53 || ) || 43 41 || R/S || 68 || || 93 ||
|-
| 19 12 || INV || 44 74 || - || 69 || || 94 ||
|-
| 20 29 || *Int || 45 01 || 1 || 70 || || 95 ||
|-
| 21 53 || ) || 46 94 || = || 71 || || 96 ||
|-
| 22 58 || *rtn || 47 22 || GTO || 72 || || 97 ||
|-
| 23 56 || *CP || 48 02 || 2 || 73 || || 98 ||
|-
| 24 38 || *CMs || 49 03 || 3 || 74 || || 99 ||
|}
Asterisk denotes 2nd function key.
{| class="wikitable"
|+ Register allocation
|-
| 0: Current Term || 1: Sum Of Terms || 2: Unused || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point.
GTO 4 4
// Address 03: Subroutine
// If R0 is divisible by 3 and 5, return 0, else nonzero
( ( RCL 0 / 5 ) INV *Int x ( RCL 0 / 3 ) INV *Int ) *rtn
// Address 23: Main program
*CP *CMs // Zero all registers and T register.
STO 0 // R0 := Maximum number to consider.
*subr 0 3 // Check divisibility by 3 and 5.
INV *x=t 3 8 // Divisible?
RCL 0
SUM 1 // R1 += R0
*dsz 2 7 // R0--, repeat while nonzero.
RCL 1 // Retrieve answer.
R/S // End.
// Address 44: Input parsing
- 1 = // Consider all numbers *less than* N.
GTO 2 3
</syntaxhighlight>
'''Usage:'''
{{in}}
<pre>1000 RST R/S</pre>
{{out}}
<pre>233168</pre>
This took between 20 and 30 minutes to run.
=== Efficient closed-form solution ===
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Sum Multiples" (Closed-form)
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 29 || *Int || 50 54 || / || 75 ||
|-
| 01 01 || 1 || 26 57 || *subr || 51 01 || 1 || 76 ||
|-
| 02 06 || 6 || 27 00 || 0 || 52 05 || 5 || 77 ||
|-
| 03 33 || STO || 28 03 || 3 || 53 94 || = || 78 ||
|-
| 04 01 || 1 || 29 64 || x || 54 29 || *Int || 79 ||
|-
| 05 54 || / || 30 05 || 5 || 55 57 || *subr || 80 ||
|-
| 06 02 || 2 || 31 94 || = || 56 00 || 0 || 81 ||
|-
| 07 64 || x || 32 35 || SUM || 57 03 || 3 || 82 ||
|-
| 08 52 || ( || 33 02 || 2 || 58 64 || x || 83 ||
|-
| 09 34 || RCL || 34 34 || RCL || 59 01 || 1 || 84 ||
|-
| 10 01 || 1 || 35 00 || 0 || 60 05 || 5 || 85 ||
|-
| 11 84 || + || 36 54 || / || 61 94 || = || 86 ||
|-
| 12 01 || 1 || 37 03 || 3 || 62 12 || INV || 87 ||
|-
| 13 53 || ) || 38 94 || = || 63 35 || SUM || 88 ||
|-
| 14 53 || ) || 39 29 || *Int || 64 02 || 2 || 89 ||
|-
| 15 58 || *rtn || 40 57 || *subr || 65 34 || RCL || 90 ||
|-
| 16 38 || *CMs || 41 00 || 0 || 66 02 || 2 || 91 ||
|-
| 17 74 || - || 42 03 || 3 || 67 41 || R/S || 92 ||
|-
| 18 01 || 1 || 43 64 || x || 68 || || 93 ||
|-
| 19 94 || = || 44 03 || 3 || 69 || || 94 ||
|-
| 20 33 || STO || 45 94 || = || 70 || || 95 ||
|-
| 21 00 || 0 || 46 35 || SUM || 71 || || 96 ||
|-
| 22 54 || / || 47 02 || 2 || 72 || || 97 ||
|-
| 23 05 || 5 || 48 34 || RCL || 73 || || 98 ||
|-
| 24 94 || = || 49 00 || 0 || 74 || || 99 ||
|}
Asterisk denotes 2nd function key.
{| class="wikitable"
|+ Register allocation
|-
| 0: Maximum Term || 1: Parameter || 2: Answer || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point.
GTO 1 6
// Address 03: Subroutine
// Calculates sum of nums 1-N as (N/2)(N+1).
STO 1
/ 2 x ( RCL 1 + 1 ) ) *rtn
// Address 16: Main program
*CMs // Clear registers.
- 1 = STO 0 // R0 := N-1
/ 5 = *Int *subr 0 3 x 5 = SUM 2 // R2 += fives
RCL 0 / 3 = *Int *subr 0 3 x 3 = SUM 2 // R2 += threes
RCL 0 / 1 5 = *Int *subr 0 3 x 1 5 = INV SUM 2 // R2 -= fifteens
RCL 2 // Retrieve answer.
R/S // End.
</syntaxhighlight>
'''Usage:'''
{{in}}
<pre>1000 RST R/S</pre>
{{out}}
<pre>233168</pre>
Completed in 4 seconds.
{{in}}
<pre>1 EE 20 RST R/S</pre>
{{out}}
<pre>2.333333333 39</pre>
Completed in 4 seconds.
=={{header|Uiua}}==
<syntaxhighlight>
End ← 1000
MultOfthree ← ⊚=0◿3 # indices where divisible by 3
Indicesthree ← MultOfthree ↘1⇡End
MultOffive ← ⊚=0◿5 # indices where divisible by 5
IndicesFive ← MultOffive ↘1⇡End
/+ ⊏⊂ Indicesthree IndicesFive ↘1⇡End # join, select and sum
</syntaxhighlight>
{{out}}
233168
</pre>
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
Only works up to 1000000000 due to limits of shell integer representation.
<syntaxhighlight lang="sh">function sum_multiples {
typeset -i n=$1 limit=$2
typeset -i max=limit-1
(( max -= max % n ))
printf '%d\n' $(( max / n * (n+max)/2 ))
}
function sum35 {
typeset -i limit=$1
printf '%d\n' $(( $(sum_multiples 3 $limit)
+ $(sum_multiples 5 $limit)
- $(sum_multiples 15 $limit) ))
}
for (( l=1; l<=1000000000; l*=10 )); do
printf '%10d\t%18d\n' "$l" "$(sum35 "$l")"
done</syntaxhighlight>
{{Out}}
<pre> 1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668</pre>
=={{header|VBA}}==
{{trans|VBScript}}
<
Dim i As Double
For i = 1 To n - 1
Line 3,782 ⟶ 4,948:
End If
Next
End Function</
Other way :
<
Dim i As Double
For i = 3 To n - 1 Step 3
Line 3,792 ⟶ 4,958:
If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
Next
End Function</
Better way :
<
Dim i As Double
For i = 3 To n - 1 Step 3
Line 3,805 ⟶ 4,971:
SumMult3and5BETTER = SumMult3and5BETTER - i
Next
End Function</
Call :
<
Sub Main()
Line 3,820 ⟶ 4,986:
Debug.Print "-------------------------"
Debug.Print SumMult3and5BETTER(1000)
End Sub</
{{Out}}
<pre>2,33333331666667E+15 9,059 sec.
Line 3,831 ⟶ 4,997:
=={{header|VBScript}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">
Function multsum35(n)
For i = 1 To n - 1
Line 3,842 ⟶ 5,008:
WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.WriteLine
</syntaxhighlight>
{{Out}}
<pre>
F:\>cscript /nologo multsum35.vbs 1000
233168
</pre>
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">module main;
integer i, suma;
initial begin
suma = 0;
for(i = 1; i <= 999; i=i+1)
begin
if(i % 3 == 0) suma = suma + i;
else if(i % 5 == 0) suma = suma + i;
end
$display(suma);
$finish ;
end
endmodule</syntaxhighlight>
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="go">fn s35(n int) int {
mut nn := n-1
mut threes := nn/3
mut fives := nn/5
mut fifteen := nn/15
threes = 3 * threes * (threes + 1)
fives = 5 * fives * (fives + 1)
fifteen = 15 * fifteen * (fifteen + 1)
nn = (threes + fives - fifteen) / 2
return nn
}
fn main(){
println(s35(1000))
}</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
=={{header|Wortel}}==
<
sum35 ^(@sum \!-@(\~%%3 || \~%%5) @til)
!sum35 1000 ; returns 233168
}</
=={{header|Wren}}==
===Simple version===
<syntaxhighlight lang="wren">var sum35 = Fn.new { |n|
n = n - 1
var s3 = (n/3).floor
Line 3,869 ⟶ 5,078:
}
System.print(sum35.call(1000))</
{{out}}
<pre>
233168
</pre>
<br>
===Fast version with arbitrary precision===
{{trans|C}}
{{libheader|Wren-gmp}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./gmp" for Mpz
import "./fmt" for Fmt
var sumMultiples = Fn.new { |result, limit, f|
var m = Mpz.from(limit).sub(1).fdiv(f)
result.set(m).inc.mul(m).mul(f).rsh(1)
}
var limit = Mpz.one
var tempSum = Mpz.new()
var sum35 = Mpz.new()
var max = 25
Fmt.print("$*s $s", max + 1, "limit", "sum")
for (i in 0..max) {
Fmt.write("$*s ", max + 1, limit)
sumMultiples.call(tempSum, limit, 3)
sum35.set(tempSum)
sumMultiples.call(tempSum, limit, 5)
sum35.add(tempSum)
sumMultiples.call(tempSum, limit, 15)
sum35.sub(tempSum)
System.print(sum35)
limit.mul(10)
}</syntaxhighlight>
{{out}}
<pre>
limit sum
1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668
10000000000 23333333331666666668
100000000000 2333333333316666666668
1000000000000 233333333333166666666668
10000000000000 23333333333331666666666668
100000000000000 2333333333333316666666666668
1000000000000000 233333333333333166666666666668
10000000000000000 23333333333333331666666666666668
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668
10000000000000000000 23333333333333333331666666666666666668
100000000000000000000 2333333333333333333316666666666666666668
1000000000000000000000 233333333333333333333166666666666666666668
10000000000000000000000 23333333333333333333331666666666666666666668
100000000000000000000000 2333333333333333333333316666666666666666666668
1000000000000000000000000 233333333333333333333333166666666666666666666668
10000000000000000000000000 23333333333333333333333331666666666666666666666668
</pre>
=={{header|XPL0}}==
<
func Sum1; \Return sum the straightforward way
Line 3,918 ⟶ 5,187:
StrNSub(S, T, 40);
TextN(0, T, 40); CrLf(0);
]</
{{out}}
Line 3,927 ⟶ 5,196:
</pre>
=={{header|Zig}}==
Note that solving for 1e20 requires numbers > 128 bits. However, Zig supports fixed size integers up to 65,556 bits, and with Zig, it's possible to figure out at compile-time what the maximum width of an integer should be at run-time.
<syntaxhighlight lang="zig">
const std = @import("std");
fn DoubleWide(comptime n: anytype) type {
const Signedness = std.builtin.Signedness;
switch (@typeInfo(@TypeOf(n))) {
.Int => |t|
return std.meta.Int(t.signedness, t.bits * 2),
.ComptimeInt => {
const sz = @as(u16, @intFromFloat(@log2(@as(f64, @floatFromInt(n))))) + 1;
return std.meta.Int(Signedness.signed, sz * 2);
},
else =>
@compileError("must have integral type for DoubleWide")
}
}
fn sumdiv(n: anytype, d: anytype) DoubleWide(n) {
var m: DoubleWide(n) = @divFloor(n, d);
return @divExact(m * (m + 1), 2) * d;
}
fn sum3or5(n: anytype) DoubleWide(n) {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var s: usize = 0;
for (1..1000) |n| {
if (n % 3 == 0 or n % 5 == 0)
s += n;
}
try stdout.print("The sum of the multiples of 3 and 5 below 1000 is {}\n", .{s});
try stdout.print("The sum of the multiples of 3 and 5 below 1e20 is {}\n", .{sum3or5(99_999_999_999_999_999_999)});
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1e20 is 2333333333333333333316666666666666666668
</pre>
=={{header|zkl}}==
Brute force:
<
233168</
{{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).
<
fcn sum35(N){sumMul(N,3) + sumMul(N,5) - sumMul(N,15)}</
{{out}}
<pre>
|