Sum multiples of 3 and 5: Difference between revisions

 
(44 intermediate revisions by 22 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.
Line 11 ⟶ 12:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F sum35(limit)
V sum = 0
L(i) 1 .< limit
Line 18 ⟶ 19:
R sum
 
print(sum35(1000))</langsyntaxhighlight>
 
{{out}}
Line 25 ⟶ 26:
</pre>
 
=={{header|8th}}==
Implements both the naive method and inclusion/exclusion.
<syntaxhighlight lang="8th">
needs combinators/bi
 
: mul3or5? ( 3 mod 0 = ) ( 5 mod 0 = ) bi or ;
 
"The sum of the multiples of 3 or 5 below 1000 is " .
0 ( mul3or5? if I n:+ then ) 1 999 loop . cr
 
with: n
 
: >triangular SED: n -- n
dup 1+ * 2 / ;
: sumdiv SED: n n -- n
dup >r /mod nip >triangular r> * ;
: sumdiv_3,5 SED: n -- n
( swap sumdiv ) curry [3, 5, 15] swap a:map a:open neg + + ;
 
;with
 
"For 10^20 - 1, the sum is " . 10 20 ^ 1- sumdiv_3,5 . cr
bye
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 below 1000 is 233168
For 10^20 - 1, the sum is 2333333333333333333316666666666666666668
</pre>
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Sum multiples of 3 and 5
SUM35 CSECT
USING SUM35,R13 base register
Line 71 ⟶ 103:
PG DC CL80'123456789012 : 1234567890123456'
YREGS
END SUM35</langsyntaxhighlight>
{{out}}
<pre>
Line 81 ⟶ 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}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Sum_Multiples is
Line 104 ⟶ 162:
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;</langsyntaxhighlight>
{{out}}
<pre>n=1000: 233168
Line 111 ⟶ 169:
===Extra Credit===
Requires upcoming Ada 202x with big integer package.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Numerics.Big_Numbers.Big_Integers;
 
Line 149 ⟶ 207:
end;
end loop;
end Sum_Multiples_Big;</langsyntaxhighlight>
{{out}}
<pre> n : Sum_35 (n)
Line 184 ⟶ 242:
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>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT to handle large numbers.
<langsyntaxhighlight lang="algol68"># returns the sum of the multiples of 3 and 5 below n #
PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT:
BEGIN
Line 213 ⟶ 300:
, newline
)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 221 ⟶ 308:
 
=={{header|APL}}==
=== Dyalog APL ===
<lang apl>⎕IO←0
<syntaxhighlight lang="apl">
{+/((0=3|a)∨0=5|a)/a←⍳⍵} 1000</lang>[http://ngn.github.io/apl/web/index.html#code=%7B+/%28%280%3D3%7Ca%29%u22280%3D5%7Ca%29/a%u2190%u2373%u2375%7D%201000,run=1 run]
Sum ← +/∘⍸1<15∨⍳
</syntaxhighlight>
{{out}}
<pre> Sum 999
233168</pre>
 
=== ngn/APL ===
<syntaxhighlight lang="apl">⎕IO←0
{+/((0=3|a)∨0=5|a)/a←⍳⍵} 1000</syntaxhighlight>[http://ngn.github.io/apl/web/index.html#code=%7B+/%28%280%3D3%7Ca%29%u22280%3D5%7Ca%29/a%u2190%u2373%u2375%7D%201000,run=1 run]
{{out}}
<pre>233168</pre>
Line 228 ⟶ 324:
=={{header|AppleScript}}==
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">----------------- SUM MULTIPLES OF 3 AND 5 -----------------
 
-- sum35 :: Int -> Int
Line 305 ⟶ 401:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
10<sup>1</sup> -> 23<br>10<sup>2</sup> -> 2318<br>10<sup>3</sup> -> 233168<br>10<sup>4</sup> -> 23331668<br>10<sup>5</sup> -> 2.333316668E+9<br>10<sup>6</sup> -> 2.33333166668E+11<br>10<sup>7</sup> -> 2.333333166667E+13<br>10<sup>8</sup> -> 2.333333316667E+15<br>
Line 311 ⟶ 407:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">sumMul35: function [n][
sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]
 
print sumMul35 1000</langsyntaxhighlight>
 
{{out}}
Line 323 ⟶ 419:
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">n := 1000
 
msgbox % "Sum is " . Sum3_5(n) . " for n = " . n
Line 357 ⟶ 453:
}
return sum
}</langsyntaxhighlight>
'''Output:''' <pre>Sum is 233168 for n = 1000
Sum is 233168 for n = 1000</pre>
Line 363 ⟶ 459:
=={{header|AWK}}==
Save this into file "sum_multiples_of3and5.awk"
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
{
n = $1-1;
Line 371 ⟶ 467:
m = int(n/d);
return (d*m*(m+1)/2);
}</langsyntaxhighlight>
 
{{Out}}
Line 387 ⟶ 483:
=={{header|BASIC}}==
{{works with|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">Declare function mulsum35(n as integer) as integer
Function mulsum35(n as integer) as integer
Dim s as integer
Line 399 ⟶ 495:
Print mulsum35(1000)
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 10 INPUT N
20 LET SUM = 0
30 FOR I = 3 TO N - 1
40 IF I / 3 = INT (I / 3) OR I / 5 = INT (I / 5) THEN SUM = SUM + I
50 NEXT I
60 PRINT SUM</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">function multSum35(n)
if n = 0 then return 0
suma = 0
for i = 1 to n
if (i mod 3 = 0) or (i mod 5 = 0) then suma += i
next i
return suma
end function
 
print multSum35(999)
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 cls
20 print multsum35(1000)
30 end
40 function multsum35(n)
50 suma = 0
60 for i = 1 to n-1
70 if (i mod 3 = 0) or (i mod 5 = 0) then suma = suma+i
80 next i
90 multsum35 = suma
100 end function</syntaxhighlight>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; multSum35(999)
End
 
Function multSum35(n As Integer) As Integer
 
If n = 0 Then Return 0
Dim suma As Integer = 0
For i As Integer = 1 To n
If (i Mod 3 = 0) Or (i Mod 5 = 0) Then suma += i
Next
Return suma
 
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|MSX BASIC|any}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 CLS : REM 10 HOME for Applesoft BASIC
20 LET N = 1000
30 GOSUB 60
40 PRINT S
50 END
60 REM multsum35
70 LET S = 0
80 FOR I = 1 TO N-1
90 IF I/3 = INT(I/3) OR I/5 = INT(I/5) THEN LET S = S+I : REM for Applesoft BASIC & Quite BASIC
90 IF (I MOD 3 = 0) OR (I MOD 5 = 0) THEN LET S = S+I : REM for MSX Basic & Chipmunk Basic
100 NEXT I
110 RETURN</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 INPUT N
20 LET S = 0
30 FOR I = 3 TO N - 1
40 IF I / 3 = INT (I / 3) THEN 70
50 IF I / 5 = INT (I / 5) THEN 70
60 GOTO 80
70 LET S = S + I
80 NEXT I
90 PRINT S
100 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
See [[#GW-BASIC|GW-BASIC]].
 
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">FUNCTION multSum35 (n)
IF n = 0 THEN multSum35 = 0
suma = 0
FOR i = 1 TO n
IF (i MOD 3 = 0) OR (i MOD 5 = 0) THEN suma = suma + i
NEXT i
multSum35 = suma
END FUNCTION
 
PRINT multSum35(999)</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION multSum35(n)
IF n = 0 THEN LET multSum35 = 0
LET suma = 0
FOR i = 1 TO n
IF MOD(i, 3) = 0 OR MOD(i, 5) = 0 THEN LET suma = suma + i
NEXT i
LET multSum35 = suma
END FUNCTION
 
PRINT multSum35(999)
END</syntaxhighlight>
 
==={{header|Quite BASIC}}===
See [[#GW-BASIC|GW-BASIC]].
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub multSum35(n)
if n = 0 then return 0 : fi
suma = 0
for i = 1 to n
if mod(i, 3) = 0 or mod(i, 5) = 0 then suma = suma + i : fi
next i
return suma
end sub
 
print multSum35(999)
end</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PRINT MULTSUM35(1000)
110 DEF MULTSUM35(N)
120 LET S=0
Line 411 ⟶ 636:
150 NEXT
160 LET MULTSUM35=S
170 END DEF</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 417 ⟶ 642:
 
The ZX81 doesn't offer enough numeric precision to try for the extra credit. This program is pretty unsophisticated; the only optimization is that we skip testing whether <math>i</math> is divisible by 5 if we already know it's divisible by 3. (ZX81 BASIC doesn't do this automatically: both sides of an <code>OR</code> are evaluated, even if we don't need the second one.) Even so, with <math>n</math> = 1000 the performance is pretty acceptable.
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 FAST
30 LET SUM=0
Line 426 ⟶ 651:
80 NEXT I
90 SLOW
100 PRINT SUM</langsyntaxhighlight>
{{in}}
<pre>1000</pre>
Line 434 ⟶ 659:
=={{header|bc}}==
{{trans|Groovy}}
<langsyntaxhighlight lang="bc">define t(n, f) {
auto m
 
Line 446 ⟶ 671:
 
s(1000)
s(10 ^ 20)</langsyntaxhighlight>
{{Out}}
<pre>233168
Line 453 ⟶ 678:
=={{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.
<syntaxhighlight lang="bcpl">
<lang BCPL>
GET "libhdr"
 
Line 479 ⟶ 704:
RESULTIS 0
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 498 ⟶ 723:
=={{header|Befunge}}==
Slow (iterative) version:
<langsyntaxhighlight Befungelang="befunge">&1-:!#v_:3%#v_ >:>#
>+\:v >:5%#v_^
@.$_^#! < > ^</langsyntaxhighlight>
{{Out}}
<pre>233168</pre>
Fast (analytic) version:
<langsyntaxhighlight Befungelang="befunge">&1-::3/:1+*3*2/\5/:1+*5*2/+\96+/:1+*96+*2/-.@</langsyntaxhighlight>
{{Out}}
<pre>233168</pre>
 
=={{header|BQN}}==
A naive solution:
<syntaxhighlight lang="bqn">Sum ← +´·(0=3⊸|⌊5⊸|)⊸/↕</syntaxhighlight>
 
A much faster solution:
<syntaxhighlight lang="bqn">Sum ← {
m ← (0=3⊸|⌊5⊸|)↕15 ⋄ h‿l ← 15(⌊∘÷˜∾|)𝕩
(+´l↑m×15(×+↕∘⊣)h) + (15×(+´m)×2÷˜h×h-1) + h×+´m×↕15
}</syntaxhighlight>
 
{{out}}
 
<pre>
Sum 1000
233168
</pre>
 
([https://mlochbaum.github.io/BQN/try.html#code=U3VtIOKGkCB7CiAgbSDihpAgKDA9M+KKuHzijIo14oq4fCnihpUxNSDii4QgaOKAv2wg4oaQIDE1KOKMiuKImMO3y5ziiL58KfCdlakKICAoK8K0bOKGkW3DlzE1KMOXK+KGleKImOKKoyloKSArICgxNcOXKCvCtG0pw5cyw7fLnGjDl2gtMSkgKyBow5crwrRtw5fihpUxNQp9CgpTdW0gMTAwMAo= online REPL])
 
=={{header|C}}==
===Simple version===
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 533 ⟶ 777:
printf("%lld\n", sum35(limit));
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>$ ./a.out
Line 542 ⟶ 786:
===Fast version with arbitrary precision===
{{libheader|GMP}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <gmp.h>
 
Line 594 ⟶ 838:
mpz_clear(limit);
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>$ ./a.out
Line 604 ⟶ 848:
The following C# 5 / .Net 4 code is an <i>efficient solution</i> in that it does not iterate through the numbers 1 ... n - 1 in order to calculate the answer. On the other hand, the System.Numerics.BigInteger class (.Net 4 and upwards) is not itself efficient because calculations take place in software instead of hardware. Consequently, it may be <i>faster</i> to conduct the calculation for smaller values with native ("primitive") types using a 'brute force' iteration approach.
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 645 ⟶ 889:
}
}
</syntaxhighlight>
</lang>
{{out}}
The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168
Line 660 ⟶ 904:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
 
Line 703 ⟶ 947:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Sum is 233168 for n = 1000
Sum is 233168 for n = 1000
</pre>
 
===Fast version with arbitrary precision===
{{libheader|Boost}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
 
template <typename T> T sum_multiples(T n, T m) {
n -= T(1);
n -= n % m;
return (n / m) * (m + n) / T(2);
}
 
template <typename T> T sum35(T n) {
return sum_multiples(n, T(3)) + sum_multiples(n, T(5)) -
sum_multiples(n, T(15));
}
 
int main() {
using big_int = boost::multiprecision::cpp_int;
 
std::cout << sum35(1000) << '\n';
std::cout << sum35(big_int("100000000000000000000")) << '\n';
}</syntaxhighlight>
 
{{out}}
<pre>
233168
2333333333333333333316666666666666666668
</pre>
 
=={{header|Clojure}}==
Quick, concise way:
<langsyntaxhighlight lang="clojure">(defn sum-mults [n & mults]
(let [pred (apply some-fn
(map #(fn [x] (zero? (mod x %))) mults))]
(->> (range n) (filter pred) (reduce +))))
 
(println (sum-mults 1000 3 5))</langsyntaxhighlight>
 
Transducers approach:
<langsyntaxhighlight 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))</langsyntaxhighlight>
 
Or optimized (translated from Groovy):
<langsyntaxhighlight lang="clojure">(defn sum-mul [n f]
(let [n1 (/' (inc' n) f)]
(*' f n1 (inc' n1) 1/2)))
 
(def sum-35 #(-> % (sum-mul 3) (+ (sum-mul % 5)) (- (sum-mul % 15))))
(println (sum-35 1000000000))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 735 ⟶ 1,010:
Using OpenCOBOL.
 
<langsyntaxhighlight lang="cobol">
Identification division.
Program-id. three-five-sum.
Line 759 ⟶ 1,034:
or function mod(ws-the-number, 5) = zero
then add ws-the-number to ws-the-sum.
</syntaxhighlight>
</lang>
 
Output:
Line 767 ⟶ 1,042:
 
Using triangular numbers:
<langsyntaxhighlight lang="cobol">
Identification division.
Program-id. three-five-sum-fast.
Line 815 ⟶ 1,090:
Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2.
goback.
</syntaxhighlight>
</lang>
 
Output:
Line 825 ⟶ 1,100:
A brute-method using only comparisons and adds. Compiles and runs as is in GnuCOBOL 2.0 and Micro Focus Visual COBOL 2.3. Takes about 7.3 seconds to calculate 1,000,000,000 iterations (AMD A6 quadcore 64bit)
 
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. SUM35.
Line 866 ⟶ 1,141:
EXIT.
END PROGRAM SUM35.
</syntaxhighlight>
</lang>
Output
<pre>+00233333333166666668</pre>
Line 872 ⟶ 1,147:
=={{header|Common Lisp}}==
Slow, naive version:
<langsyntaxhighlight lang="lisp">(defun sum-3-5-slow (limit)
(loop for x below limit
when (or (zerop (rem x 3)) (zerop (rem x 5)))
sum x))</langsyntaxhighlight>
 
Fast version (adapted translation of [[#Tcl|Tcl]]):
<langsyntaxhighlight lang="lisp">(defun sum-3-5-fast (limit)
(flet ((triangular (n) (truncate (* n (1+ n)) 2)))
(let ((n (1- limit))) ; Sum multiples *below* the limit
(- (+ (* 3 (triangular (truncate n 3)))
(* 5 (triangular (truncate n 5))))
(* 15 (triangular (truncate n 15)))))))</langsyntaxhighlight>
 
{{Out}}
Line 894 ⟶ 1,169:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Sum3_5;
IMPORT StdLog, Strings, Args;
Line 921 ⟶ 1,196:
 
END Sum3_5.
</syntaxhighlight>
</lang>
Execute: ^Q Sum3_5.Compute 1000 ~ <br/>
Output:
Line 929 ⟶ 1,204:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# sum multiples up to given input
Line 957 ⟶ 1,232:
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method: "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
</syntaxhighlight>
</lang>
 
{{out}}
Line 967 ⟶ 1,242:
{{trans|Ruby}}
Short, but not optimized.
<langsyntaxhighlight lang="ruby">def sum_3_5_multiples(n)
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end
 
puts sum_3_5_multiples(1000)</langsyntaxhighlight>
{{out}}
<pre>
Line 981 ⟶ 1,256:
To conform to task requirements, and other versions,
modified to find sums below n.
<langsyntaxhighlight lang="ruby">require "big"
 
def g(n1, n2, n3)
Line 993 ⟶ 1,268:
# For extra credit
puts g(3,5,"100000000000000000000".to_big_i - 1)
puts g(3,5,"100000000000000000000".to_big_i)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,003 ⟶ 1,278:
 
Alternative faster version 2.
<langsyntaxhighlight lang="ruby">require "big"
 
def sumMul(n, f)
Line 1,016 ⟶ 1,291:
(1..20).each do |e| limit = 10.to_big_i ** e
puts "%2d:%22d %s" % [e, limit, sum35(limit)]
end</langsyntaxhighlight>
{{out}}
<pre>
Line 1,042 ⟶ 1,317:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.bigint;
 
BigInt sum35(in BigInt n) pure nothrow {
Line 1,059 ⟶ 1,334:
1000.BigInt.sum35.writeln;
(10.BigInt ^^ 20).sum35.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,068 ⟶ 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}}==
<langsyntaxhighlight lang="delphi">program sum35;
 
{$APPTYPE CONSOLE}
Line 1,090 ⟶ 1,398:
end;
writeln(sum);
end.</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">sum-divisible n:
0
for i range 1 -- n:
Line 1,101 ⟶ 1,409:
+ i
 
!. sum-divisible 1000</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func msum35 n .
for i = 1 to n
if i mod 3 = 0 or i mod 5 = 0
sum += i
.
.
return sum
.
print msum35 999
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when
Line 1,140 ⟶ 1,461:
❌ error: expected coprimes (42 666)
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 1,172 ⟶ 1,493:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,180 ⟶ 1,501:
=={{header|Elixir}}==
Simple (but slow)
<langsyntaxhighlight lang="elixir">iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum
233168</langsyntaxhighlight>
 
Fast version:
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def sumMul(n, f) do
n1 = div(n - 1, f)
Line 1,199 ⟶ 1,520:
n = round(:math.pow(10, i))
IO.puts RC.sum35(n)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,226 ⟶ 1,547:
 
=={{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) ))
(dotimes (x 0) n)
(number-sequencewhen 1(or (-zerop n(% 1x 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-sequencelambda 1(x) (-or n(zerop (% x 1)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}}==
<langsyntaxhighlight lang="erlang">sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0).
sum_3_5(X, Total) when X < 3 -> Total;
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
Line 1,260 ⟶ 1,571:
sum_3_5(X-1, Total).
 
io:format("~B~n", [sum_3_5(1000)]).</langsyntaxhighlight>
 
{{out}}
Line 1,266 ⟶ 1,577:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)
 
Line 1,279 ⟶ 1,590:
 
[for i = 0 to 30 do yield i]
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))</langsyntaxhighlight>
{{out}}
<pre style="height:5em">233168
Line 1,324 ⟶ 1,635:
<br>
{{works with|Factor|0.99 2019-10-06}}
<langsyntaxhighlight lang="factor">USING: kernel math prettyprint ;
 
: sum-multiples ( m n upto -- sum )
Line 1,332 ⟶ 1,643:
 
3 5 1000 sum-multiples .
3 5 1e20 sum-multiples .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,341 ⟶ 1,652:
=={{header|FBSL}}==
Derived from BASIC version
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
Line 1,355 ⟶ 1,666:
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
</syntaxhighlight>
</lang>
Output
<pre>233168
Line 1,363 ⟶ 1,674:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: main ( n -- )
0 swap
3 do
Line 1,374 ⟶ 1,685:
. ;
 
1000 main \ 233168 ok</langsyntaxhighlight>
 
Another FORTH version using the Inclusion/Exclusion Principle. The result is a double precision integer (128 bits on a 64 bit computer) which lets us calculate up to 10^18 (the max precision of a single precision 64 bit integer) Since this is Project Euler problem 1, the name of the main function is named euler1tower.
 
<langsyntaxhighlight lang="forth">: third 2 pick ;
 
: >dtriangular ( n -- d )
Line 1,420 ⟶ 1,731:
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668 ok
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Line 1,426 ⟶ 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">
<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,466 ⟶ 1,777:
GO TO 10 !Have another go.
END !So much for that.
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 1,489 ⟶ 1,800:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function sum35 (n As UInteger) As UInteger
Line 1,503 ⟶ 1,814:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,512 ⟶ 1,823:
=={{header|Frink}}==
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}]]
 
Line 1,525 ⟶ 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>
</lang>
{{Out}}
<pre>
The sum of all the multiples of 3 or 5 below 1000 is 233168
The sum of all multiples less than 1e20 is 2333333333333333333316666666666666666668
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
_n = 1000
 
void local fn DoIt
long i, sum = 0
for i = 0 to _n - 1
if ( i mod 3 == 0 or i mod 5 == 0 )
sum += i
end if
next
NSLog(@"%ld",sum)
end fn
 
fn Doit
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
233168
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,554 ⟶ 1,892:
return n
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,560 ⟶ 1,898:
</pre>
Extra credit:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,590 ⟶ 1,928:
s := sum2(b3)
return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,598 ⟶ 1,936:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 }
def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }</langsyntaxhighlight>
Test Code:
<langsyntaxhighlight lang="groovy">[(1000): 233168, (10e20): 233333333333333333333166666666666666666668].each { arg, value ->
println "Checking $arg == $value"
assert sum35(arg) == value
}</langsyntaxhighlight>
{{out}}
<pre>Checking 1000 == 233168
Line 1,611 ⟶ 1,949:
=={{header|Haskell}}==
Also a method for calculating sum of multiples of any list of numbers.
<langsyntaxhighlight lang="haskell">import Data.List (nub)
 
----------------- SUM MULTIPLES OF 3 AND 5 ---------------
Line 1,652 ⟶ 1,990:
where
f = sumMul n
g = sumMulS n</langsyntaxhighlight>
{{out}}
<pre>233168
Line 1,663 ⟶ 2,001:
The following works in both langauges.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
n := (integer(A[1]) | 1000)-1
write(sum(n,3)+sum(n,5)-sum(n,15))
Line 1,670 ⟶ 2,008:
procedure sum(n,m)
return m*((n/m)*(n/m+1)/2)
end</langsyntaxhighlight>
 
Sample output:
Line 1,683 ⟶ 2,021:
 
=={{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.
<syntaxhighlight lang="j">
<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
 
echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)
 
 
Line 1,743 ⟶ 2,041:
 
echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
exit ''
 
</syntaxhighlight>
</lang>
{{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>
Line 1,754 ⟶ 2,052:
=={{header|Java}}==
===Simple Version===
<langsyntaxhighlight Javalang="java">class SumMultiples {
public static long getSum(long n) {
long sum = 0;
Line 1,765 ⟶ 2,063:
System.out.println(getSum(1000));
}
}</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
===Extra Credit===
<syntaxhighlight lang="java">
<lang Java>
import java.math.BigInteger;
 
Line 1,810 ⟶ 2,108:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,844 ⟶ 2,142:
===ES5===
 
JavaScript is better equipped for flexibility than for scale. The value of <syntaxhighlight lang JavaScript="javascript"> Number.MAX_SAFE_INTEGER</langsyntaxhighlight> is 9007199254740991, or 2^53 - 1 – resulting from an IEEE 754 double-precision floating point representation of numeric values).
 
As ''Number.MAX_SAFE_INTEGER < 1E20'' evaluates to ''true'', the most obvious JS attack on a solution for 1E20 might involve some string processing …
Line 1,850 ⟶ 2,148:
At more modest scales, however, we can generalise a little to allow for an arbitrary list of integer factors, and write a simple generate, filter and sum approach:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (lstFactors, intExponent) {
 
// [n] -> n -> n
Line 1,908 ⟶ 2,206:
JSON.stringify(lstTable);
 
})([3, 5], 8);</langsyntaxhighlight>
 
 
Line 1,934 ⟶ 2,232:
|}
 
<langsyntaxhighlight JavaScriptlang="javascript"> [["Below","Sum"],["10^1",23],["10^2",2318],["10^3",233168],
["10^4",23331668],["10^5",2333316668],["10^6",233333166668],
["10^7",23333331666668],["10^8",2333333316666668]]</langsyntaxhighlight>
====With wheel increments====
<langsyntaxhighlight JavaScriptlang="javascript">function sm35(n){
var s=0, inc=[3,2,1,3,1,2,3]
for (var j=6, i=0; i<n; j+=j==6?-j:1, i+=inc[j]) s+=i
return s
}</langsyntaxhighlight>
====With triangular numbers====
<langsyntaxhighlight JavaScriptlang="javascript">function sm35(n){
return tri(n,3) + tri(n,5) - tri(n,15)
function tri(n, f) {
Line 1,950 ⟶ 2,248:
return f * n * (n+1) / 2
}
}</langsyntaxhighlight>
'''This:'''
<langsyntaxhighlight JavaScriptlang="javascript">for (var i=1, n=10; i<9; n*=10, i+=1) {
document.write(10, '<sup>', i, '</sup> ', sm35(n), '<br>')
}</langsyntaxhighlight>
{{out}}
10<sup>1</sup> 23
Line 1,968 ⟶ 2,266:
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// sum35 :: Int -> Int
Line 2,108 ⟶ 2,406:
// ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Sums for n = 10^1 thru 10^8:
Line 2,120 ⟶ 2,418:
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">
<lang jq>
def sum_multiples(d):
((./d) | floor) | (d * . * (.+1))/2 ;
Line 2,128 ⟶ 2,444:
def task(a;b):
. - 1
| sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);</langsyntaxhighlight>Examples:
 
jq does not (yet) support arbitrary-precision integer arithmetic but converts large integers to floats, so:
<syntaxhighlight lang="jq">
<lang jq>
1000 | task(3;5) # => 233168
 
10e20 | task(3;5) # => 2.333333333333333e+41</langsyntaxhighlight>
 
 
=={{header|Julia}}==
sum multiples of each, minus multiples of the least common multiple (lcm). Similar to MATLAB's version.
<langsyntaxhighlight Julialang="julia">multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)</langsyntaxhighlight>
Output:
<pre>julia> multsum(3, 5, 1000)
Line 2,174 ⟶ 2,491:
(100000000000000000000,2333333333333333333316666666666666666668)</pre>
a slightly more efficient version
<langsyntaxhighlight Julialang="julia">multsum(n, lim) = (occ = div(lim-1, n); div(n*occ*(occ+1), 2))
multsum(n, m, lim) = multsum(n, lim) + multsum(m, lim) - multsum(lcm(n,m), lim)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 2,208 ⟶ 2,525:
val e20 = big100k * big100k * big100k * big100k
println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,217 ⟶ 2,534:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(limit = 1)
while(#limit <= 100000) => {^
local(s = 0)
Line 2,225 ⟶ 2,542:
'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
#limit = integer(#limit->asString + '0')
^}</langsyntaxhighlight>
{{out}}
<pre>The sum of multiples of 3 or 5 between 1 and 0 is: 0
Line 2,238 ⟶ 2,555:
Uses the IPints library when the result will be very large.
 
<langsyntaxhighlight Limbolang="limbo">implement Sum3and5;
 
include "sys.m"; sys: Sys;
Line 2,310 ⟶ 2,627:
sub(isum_multiples(ints[15], limit)));
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,318 ⟶ 2,635:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on sum35 (n)
res = 0
repeat with i = 0 to (n-1)
Line 2,326 ⟶ 2,643:
end repeat
return res
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">put sum35(1000)
-- 233168</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function sumUntil n
repeat with i = 0 to (n-1)
if i mod 3 = 0 or i mod 5 = 0 then
Line 2,341 ⟶ 2,658:
end sumUntil
 
put sumUntil(1000) // 233168</langsyntaxhighlight>
 
=={{header|Lua}}==
{{trans|Tcl}}
<syntaxhighlight lang="lua">
<lang Lua>
function tri (n) return n * (n + 1) / 2 end
 
Line 2,358 ⟶ 2,675:
print(sum35(1000))
print(sum35(1e+20))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,367 ⟶ 2,684:
=={{header|Maple}}==
By using symbolic function <code>sum</code> instead of numeric function <code>add</code> the program <code>F</code> will run O(1) rather than O(n).
<syntaxhighlight lang="maple">
<lang Maple>
F := unapply( sum(3*i,i=1..floor((n-1)/3))
+ sum(5*i,i=1..floor((n-1)/5))
Line 2,375 ⟶ 2,692:
 
F(10^20);
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,395 ⟶ 2,712:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">sum35[n_] :=
Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] -
Sum[k, {k, 15, n - 1, 15}]
sum35[1000]</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
<syntaxhighlight lang ="mathematica">sum35[10^20]</langsyntaxhighlight>
{{out}}
<pre>233333333333333333333166666666666666666668</pre>
Another alternative is
<langsyntaxhighlight lang="mathematica"> Union @@ Range[0, 999, {3, 5}] // Tr </langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0))</langsyntaxhighlight>
<pre>ans = 233168</pre>
Another alternative is
<langsyntaxhighlight MATLABlang="matlab">n=1000; sum(0:3:n-1)+sum(0:5:n-1)-sum(0:15:n-1)</langsyntaxhighlight>
Of course, it's more efficient to use [http://mathforum.org/library/drmath/view/57919.html Gauss' approach] of adding subsequent integers:
<langsyntaxhighlight MATLABlang="matlab">n=999;
n3=floor(n/3);
n5=floor(n/5);
n15=floor(n/15);
(3*n3*(n3+1) + 5*n5*(n5+1) - 15*n15*(n15+1))/2</langsyntaxhighlight>
<pre>ans = 233168</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">sumi(n, inc):= block(
[kmax],
 
Line 2,434 ⟶ 2,751:
 
sum35(1000);
sum35(10^20);</langsyntaxhighlight>
Output:
<pre>
Line 2,446 ⟶ 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.
<langsyntaxhighlight MiniScriptlang="miniscript">// simple version:
sum35 = function(n)
sum = 0
Line 2,458 ⟶ 2,775:
end function
 
print sum35(1000)</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
Line 2,464 ⟶ 2,781:
Now the fast version.
{{trans|D}}
<langsyntaxhighlight MiniScriptlang="miniscript">// fast version:
sumMul = function(n, f)
n1 = floor((n - 1) / f)
Line 2,474 ⟶ 2,791:
end function
 
print sum35fast(1000)</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 0 П0 3 П4 ИП4 3 / {x} x#0
17 ИП4 5 / {x} x=0 21 ИП0 ИП4 +
П0 КИП4 ИП1 ИП4 - x=0 05 ИП0 С/П</langsyntaxhighlight>
 
Input: ''n''.
Line 2,490 ⟶ 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.
<langsyntaxhighlight lang="nanoquery">def getSum(n)
sum = 0
for i in range(3, n - 1)
Line 2,500 ⟶ 2,817:
end
 
println getSum(1000)</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
Line 2,506 ⟶ 2,823:
=={{header|NetRexx}}==
Portions translation of [[#Raku|Raku]]
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 40
Line 2,583 ⟶ 2,900:
say
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,642 ⟶ 2,959:
=={{header|Nim}}==
Here is the solution using normal integers.
<langsyntaxhighlight 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)</langsyntaxhighlight>
 
{{out}}
Line 2,656 ⟶ 2,973:
{{trans|Raku}}
{{libheader|bigints}}
<langsyntaxhighlight lang="nim">import bigints
 
proc sumMults(first: int32, limit: BigInt): BigInt =
Line 2,671 ⟶ 2,988:
while x < "1000000000000000000000000000000".initBigInt:
echo sum35 x
x *= 10</langsyntaxhighlight>
 
{{out}}
Line 2,707 ⟶ 3,024:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class SumMultiples {
function : native : GetSum(n : Int) ~ Int {
sum := 0;
Line 2,723 ⟶ 3,040:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 2,730 ⟶ 3,047:
</pre>
 
=={{header|Odin}}==
Note: 1e19 is the largest sum that can be calculated with 128 bit integers.
<syntaxhighlight lang="odin">
package main
 
import "core:fmt"
 
sumdiv :: proc(n, d: i128) -> i128 {
m := n / d
return (m % 2 == 0)? \
m/2 * (m + 1) * d : \
(m + 1)/2 * m * d
}
 
sum3or5 :: proc(n: i128) -> i128 {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)
}
 
main :: proc() {
sum := 0
for n in 1..=999 {
if n % 3 == 0 || n % 5 == 0 {
sum += n
}
}
fmt.println("The sum of all multiples of 3 and 5 < 1000 is", sum)
fmt.println("The sum of all multiples of 3 and 5 < 1e19 is", sum3or5(1e19 - 1))
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of all multiples of 3 and 5 < 1000 is 233168
The sum of all multiples of 3 and 5 < 1e19 is 23333333333333333331666666666666666668
</pre>
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sum_multssum_m3m5 n =
let termial x = (x * letx sum+ =x) reflsr 01 in
3 * (termial (n / 3) for- i5 =* 3 totermial (n -/ 115)) do+ 5 * termial (n / 5)
if (i mod 3) = 0 || (i mod 5) = 0 then
sum := !sum + i;
done;
!sum;;
 
let () =
print_endline (string_of_int (sum_mults 1000));;
let pow10 x = truncate (10. ** (float x)) in
</lang>
for i = 1 to 9 do
let u = pred (pow10 i) in
Printf.printf "Summing multiples of 3 or 5 in 1..%u: %u\n" u (sum_m3m5 u)
done</syntaxhighlight>
{{out}}
<pre>233168</pre>
Summing multiples of 3 or 5 in 1..9: 23
Summing multiples of 3 or 5 in 1..99: 2318
Summing multiples of 3 or 5 in 1..999: 233168
Summing multiples of 3 or 5 in 1..9999: 23331668
Summing multiples of 3 or 5 in 1..99999: 2333316668
Summing multiples of 3 or 5 in 1..999999: 233333166668
Summing multiples of 3 or 5 in 1..9999999: 23333331666668
Summing multiples of 3 or 5 in 1..99999999: 2333333316666668
Summing multiples of 3 or 5 in 1..999999999: 233333333166666668
</pre>
=== With wheel increments (slower) ===
<syntaxhighlight lang="ocaml">
open Printf;;
 
let mul3or5 =
let rec wheel = 3 :: 2 :: 1 :: 3 :: 1 :: 2 :: 3 :: wheel in
Seq.scan (+) 0 (List.to_seq wheel);;
 
let sum3or5 upto =
mul3or5
|> Seq.take_while (fun n -> n < upto)
|> Seq.fold_left (+) 0;;
 
printf "The sum of the multiples of 3 or 5 below 1000 is %d\n" (sum3or5 1000);;
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 or 5 below 1000 is 233168
</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">999 seq filter(#[ dup 3 mod 0 == swap 5 mod 0 == or ]) sum println</langsyntaxhighlight>
 
Output:
Line 2,754 ⟶ 3,134:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(print
(fold (lambda (s x)
Line 2,760 ⟶ 3,140:
0 (iota 1000)))
; ==> 233168
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">ct(n,k)=n=n--\k;k*n*(n+1)/2;
a(n)=ct(n,3)+ct(n,5)-ct(n,15);
a(1000)
a(1e20)</langsyntaxhighlight>
{{output}}
<pre>
Line 2,777 ⟶ 3,157:
{{works with|Free Pascal|2.6.2}}
 
<langsyntaxhighlight Pascallang="pascal">program Sum3sAnd5s;
function Multiple(x, y: integer): Boolean;
Line 2,799 ⟶ 3,179:
{ Show sum of all multiples less than 1000. }
writeln(SumMultiples(1000))
end.</langsyntaxhighlight>
===alternative===
using gauss summation formula, but subtract double counted.
adapted translation of [[#Tcl|Tcl]]
<langsyntaxhighlight Pascallang="pascal">program sum35;
//sum of all positive multiples of 3 or 5 below n
 
Line 2,824 ⟶ 3,204:
sum := sum-cntSumdivisibleBelowN(n,3*5);
writeln(sum);
end.</langsyntaxhighlight>
output
<pre>233168</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict v5.20;
use experimental qw(signatures);
use warnings ;
 
use List::Util qw( sum ) ;
 
sub sum_3_5($limit) {
my $limit = shift ;
return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}
 
printsay "The sum is " . ${\(sum_3_5( 1000 ) . " }!\n" ;</langsyntaxhighlight>
{{Out}}
<pre>The sum is 233168 !</pre>
 
{{Trans|Tcl}}
An alternative approach, using the analytical solution from the Tcl example.
<syntaxhighlight lang Perl="perl">use feature 'say'v5.20;
use experimental qw(signatures);
sub tri
 
{
sub tri($n) {
my $n = shift;
return $n*($n+1) / 2;
}
 
sub sum_multiples($n, $limit) {
sub sum
$n * tri( int( ($limit - 1) / $n ) )
{
}
my $n = (shift) - 1;
 
(3 * tri( int($n/3) ) + 5 * tri( int($n/5) ) - 15 * tri( int($n/15) ) );
sub sum($n) {
sum_multiples(3, $n) + sum_multiples(5, $n) - sum_multiples(15, $n);
}
 
say sum( 1e3);
use bigint; # Machine precision was sufficient for the first calculation
say sum( 1e20);</langsyntaxhighlight>
{{Out}}
<pre>233168
Line 2,869 ⟶ 3,251:
===native===
note the result of sum35() is inaccurate above 2^53 on 32-bit, 2^64 on 64-bit.
<!--<langsyntaxhighlight Phixlang="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>
Line 2,886 ⟶ 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: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,903 ⟶ 3,285:
{{libheader|Phix/mpfr}}
Fast analytical version with arbitrary precision
<!--<langsyntaxhighlight Phixlang="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>
Line 2,932 ⟶ 3,314:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 2,962 ⟶ 3,344:
Naive version (slow) :
 
<langsyntaxhighlight PHPlang="php">$max = 1000;
$sum = 0;
for ($i = 1 ; $i < $max ; $i++) {
Line 2,970 ⟶ 3,352:
}
echo $sum, PHP_EOL;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,977 ⟶ 3,359:
Fast version:
 
<langsyntaxhighlight PHPlang="php">function sum_multiples($max, $divisor) {
// Number of multiples of $divisor <= $max
$num = floor($max / $divisor);
Line 2,988 ⟶ 3,370:
+ sum_multiples($max - 1, 5)
- sum_multiples($max - 1, 15);
echo $sum, PHP_EOL;</langsyntaxhighlight>
 
{{out}}
Line 2,998 ⟶ 3,380:
These functions allow for arbitrary-length integers to be worked with.
 
<langsyntaxhighlight PHPlang="php">function sum_multiples_gmp($max, $divisor) {
// Number of multiples of $divisor <= $max
$num = gmp_div($max, $divisor);
Line 3,016 ⟶ 3,398:
);
printf('%22s : %s' . PHP_EOL, gmp_strval($n), $sum);
}</langsyntaxhighlight>
 
{{out}}
Line 3,044 ⟶ 3,426:
=={{header|Picat}}==
Uses both the naive method and inclusion/exclusion.
<syntaxhighlight lang="picat">
<lang Picat>
sumdiv(N, D) = S =>
M = N div D,
Line 3,055 ⟶ 3,437:
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>
</lang>
{{Out}}
<pre>
Line 3,062 ⟶ 3,444:
</pre>
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de sumMul (N F)
(let N1 (/ (dec N) F)
(*/ F N1 (inc N1) 2) ) )
Line 3,071 ⟶ 3,453:
(-
(+ (sumMul N 3) (sumMul N 5))
(sumMul N 15) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,097 ⟶ 3,479:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">threeor5: procedure options (main); /* 8 June 2014 */
declare (i, n) fixed(10), sum fixed (31) static initial (0);
 
Line 3,109 ⟶ 3,491:
put edit ( trim(sum) ) (A);
 
end threeor5;</langsyntaxhighlight>
Outputs:
<pre>
Line 3,118 ⟶ 3,500:
The number of multiples of 3 or 5 below 10000000 is 23333331666668
The number of multiples of 3 or 5 below 100000000 is 2333333316666668</pre>
 
==={{header|PL/I-80}}===
Although a brute-force approach gets the job done with a minimum
of fuss, and would generally be the preferred first choice, the use of Gauss's
summation formula will significantly speed up running time if
summing to higher limits than required by the problem. The solution
here demonstrates both approaches
<syntaxhighlight lang = "PL/I">
sum35_demo: proc options (main);
dcl limit fixed bin;
limit = 1000;
put skip list ('Sum of all multiples of 3 and 5 below', limit);
put skip edit ('Sum = ', sum35(limit)) ((a),(f(6)));
put skip edit ('Also: ', sum35alt(limit)) ((a),(f(6)));
 
stop;
 
sum35:
proc(limit) returns (float bin);
dcl
(limit, i) fixed bin,
sum float bin;
sum = 0;
do i=1 to (limit-1);
if mod(i,3) = 0 | mod(i,5) = 0 then
sum = sum + i;
end;
return (sum);
end sum35;
 
sum35alt:
proc(limit) returns (float bin);
dcl
limit fixed bin,
sum float bin;
sum = sum_of_multiples(3, limit) +
sum_of_multiples(5, limit) -
sum_of_multiples(15, limit);
return (sum);
end sum35alt;
 
sum_of_multiples:
proc(n, limit) returns (float bin);
dcl
(n, limit, i) fixed bin,
m float bin;
m = (limit - 1) / n;
return (n * m * (m + 1) / 2);
end sum_of_multiples;
 
end sum35_demo;
</syntaxhighlight>
{{out}}
<pre>
Sum of all multiples of 3 and 5 below 1000
Sum = 233168
Also: 233168
</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
function SumMultiples ( [int]$Base, [int]$Upto )
{
Line 3,130 ⟶ 3,570:
# Calculate the sum of the multiples of 3 and 5 up to 1000
( SumMultiples -Base 3 -Upto 1000 ) + ( SumMultiples -Base 5 -Upto 1000 ) - ( SumMultiples -Base 15 -Upto 1000 )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,136 ⟶ 3,576:
</pre>
For arbitrarily large integers, simply change the variable type.
<langsyntaxhighlight lang="powershell">
function SumMultiples ( [bigint]$Base, [bigint]$Upto )
{
Line 3,147 ⟶ 3,587:
$Upto = [bigint]::Pow( 10, 210 )
( SumMultiples -Base 3 -Upto $Upto ) + ( SumMultiples -Base 5 -Upto $Upto ) - ( SumMultiples -Base 15 -Upto $Upto )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,153 ⟶ 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.
<langsyntaxhighlight Powershelllang="powershell">function Get-SumOfMultiples
{
Param
Line 3,183 ⟶ 3,623:
}
$Sum
}</langsyntaxhighlight>
{{out}}
<pre>Get-SumOfMultiples</pre>
Line 3,193 ⟶ 3,633:
=={{header|Prolog}}==
===Slow version===
<langsyntaxhighlight Prologlang="prolog">sum_of_multiples_of_3_and_5_slow(N, TT) :-
sum_of_multiples_of_3_and_5(N, 1, 0, TT).
 
Line 3,209 ⟶ 3,649:
sum_of_multiples_of_3_and_5(N, K1, C5, S).
 
</syntaxhighlight>
</lang>
 
===Fast version===
<langsyntaxhighlight Pologlang="polog">sum_of_multiples_of_3_and_5_fast(N, TT):-
maplist(compute_sum(N), [3,5,15], [TT3, TT5, TT15]),
TT is TT3 + TT5 - TT15.
Line 3,221 ⟶ 3,661:
; N2 is N div N1),
Sum is N1 * N2 * (N2 + 1) / 2.
</syntaxhighlight>
</lang>
 
Output :
Line 3,232 ⟶ 3,672:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
 
Line 3,253 ⟶ 3,693:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,262 ⟶ 3,702:
=={{header|Python}}==
Three ways of performing the calculation are shown including direct calculation of the value without having to do explicit sums in sum35c()
<langsyntaxhighlight lang="python">def sum35a(n):
'Direct count'
# note: ranges go to n-1
Line 3,293 ⟶ 3,733:
# Scalability
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))</langsyntaxhighlight>
 
{{out}}
Line 3,311 ⟶ 3,751:
Or, more generally – taking the area under the straight line between the first multiple and the last:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Summed multiples of 3 and 5 up to n'''
 
 
Line 3,381 ⟶ 3,821:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Summed multiples of 3 and 5 up to n:
Line 3,400 ⟶ 3,840:
 
=={{header|Q}}==
<langsyntaxhighlight lang="q">s35:{sum {?[(0=x mod 3) | 0=x mod 5;x;0]} each 1+til x - 1}
s35 each 10 100 1000 10000 1000000</langsyntaxhighlight>
 
Extra credit, using the summation formula:
 
<langsyntaxhighlight lang="q">sn:{x*(x+1)%2} / Sum of 1 to n
s35:{a:x-1; (3*sn floor a%3) + (5*sn floor a%5) - (15*sn floor a%15)}
s35 e+10</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ dup 1+ * 2 / ] is triangulared ( n --> n )
[ 1 -
Line 3,420 ⟶ 3,860:
1000 sum-of-3s&5s echo cr
10 20 ** sum-of-3s&5s echo cr</langsyntaxhighlight>
 
{{out}}
Line 3,430 ⟶ 3,870:
=={{header|R}}==
 
<langsyntaxhighlight lang="rsplus">m35 = function(n) sum(unique(c(
seq(3, n-1, by = 3), seq(5, n-1, by = 5))))
m35(1000) # 233168</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 3,462 ⟶ 3,902:
 
(for/list ([k 20]) (analytical k))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
'(0 23 2318 233168 23331668 2333316668 233333166668)
'(0
Line 3,486 ⟶ 3,926:
233333333333333333166666666666666668
23333333333333333331666666666666666668)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub sum35($n) { [+] grep * %% (3|5), ^$n; }
 
say sum35 1000;</langsyntaxhighlight>
{{out}}
<pre>233168</pre>
Here's an analytical approach that scales much better for large values.
<syntaxhighlight lang="raku" perl6line>sub sum-mults($first, $limit) {
(my $last = $limit - 1) -= $last % $first;
($last div $first) * ($first + $last) div 2;
Line 3,505 ⟶ 3,945:
}
 
say sum35($_) for 1,10,100...10**30;</langsyntaxhighlight>
{{out}}
<pre>0
Line 3,541 ⟶ 3,981:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 14.05.2013 Walter Pachl
**********************************************************************/
Line 3,552 ⟶ 3,992:
s=s+i
End
Return s</langsyntaxhighlight>
Output:
<pre>233168</pre>
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Translation from Raku->NetRexx->REXX
* 15.05.2013 Walter Pachl
Line 3,580 ⟶ 4,020:
last = last - last // first
sum = (last % first) * (first + last) % 2
return sum</langsyntaxhighlight>
Output:
<pre> 1 0
Line 3,619 ⟶ 4,059:
 
The formula used is a form of the Gauss Summation formula.
<langsyntaxhighlight lang="rexx">/*REXX program counts all integers from 1 ──► N─1 that are multiples of 3 or 5. */
parse arg N t . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 1000 /*Not specified? Then use the default.*/
Line 3,634 ⟶ 4,074:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDiv: procedure; parse arg x,d; $= x % d; return d * $ * ($+1) % 2</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,736 ⟶ 4,176:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see sum35(1000) + nl
Line 3,747 ⟶ 4,187:
func tri n
return n * (n + 1) / 2
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
===Simple solution===
Just counting...
≪ 0 1 DO
1 +
IF DUP 3 MOD NOT OVER 5 MOD NOT OR THEN SWAP OVER + SWAP END
UNTIL DUP 4 PICK == END
ROT DROP2
===Efficient solution===
This is a fast approach to calculate the sum for higher values of n, taking into account that:
# the sum of multiples of 3 and 5 is the sum of multiples of 3 plus the sum of multiples of 5, minus the sum of multiples of 15 to remove double counting
# the sum of multiples of m being < n is equal to m*(1+2+ ... k) with k =[n/m]
# 1+2+...k = k*(k+1)/2
Unfortunately, RPL can only handle double precision numbers, which prevents from precisely calculating the sum for n > 1E+15
≪ → n
≪ 0 1 3 FOR j
{ 3 5 -15 } j GET
n OVER / ABS IP
DUP 1 + * 2 / * +
NEXT
≫ ≫
‘SUM35’ STO
 
999 SUM35
{{out}}
<pre>
1: 233168
</pre>
 
=={{header|Ruby}}==
Simple Version (Slow):
<langsyntaxhighlight lang="ruby">def sum35(n)
(1...n).select{|i|i%3==0 or i%5==0}.sum
end
puts sum35(1000) #=> 233168</langsyntaxhighlight>
 
Fast Version:
<langsyntaxhighlight lang="ruby"># Given two integers n1,n2 return sum of multiples upto n3
#
# Nigel_Galloway
Line 3,769 ⟶ 4,240:
 
# For extra credit
puts g(3,5,100000000000000000000-1)</langsyntaxhighlight>
 
{{out}}
Line 3,779 ⟶ 4,250:
Other way:
{{trans|D}}
<langsyntaxhighlight lang="ruby">def sumMul(n, f)
n1 = (n - 1) / f
f * n1 * (n1 + 1) / 2
Line 3,790 ⟶ 4,261:
for i in 1..20
puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)]
end</langsyntaxhighlight>
 
{{out}}
Line 3,817 ⟶ 4,288:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print multSum35(1000)
end
function multSum35(n)
Line 3,823 ⟶ 4,294:
If (i mod 3 = 0) or (i mod 5 = 0) then multSum35 = multSum35 + i
next i
end function</langsyntaxhighlight><pre>233168</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
extern crate rug;
 
Line 3,863 ⟶ 4,334:
}
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 3,876 ⟶ 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}}==
<langsyntaxhighlight lang="scala">def sum35( max:BigInt ) : BigInt = max match {
 
// Simplest solution but limited to Ints only
Line 3,898 ⟶ 4,394:
{
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
}</langsyntaxhighlight>
{{out}}
<pre> 1 => 0
Line 3,923 ⟶ 4,419:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000))</langsyntaxhighlight>
 
Output:
Line 3,932 ⟶ 4,428:
Or, more clearly by decomposition:
 
<langsyntaxhighlight lang="scheme">(define (fac35? x)
(or (zero? (remainder x 3))
(zero? (remainder x 5))))
Line 3,939 ⟶ 4,435:
(+ tot (if (fac35? x) x 0)))
 
(fold fac35filt 0 (iota 1000))</langsyntaxhighlight>
 
Output:
Line 3,948 ⟶ 4,444:
For larger numbers iota can take quite a while just to build the list -- forget about waiting for all the computation to finish!
 
<langsyntaxhighlight lang="scheme">(define (trisum n fac)
(let* ((n1 (quotient (- n 1) fac))
(n2 (+ n1 1)))
Line 3,958 ⟶ 4,454:
(fast35sum 1000)
(fast35sum 100000000000000000000)
</syntaxhighlight>
</lang>
 
Output:
Line 3,967 ⟶ 4,463:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 3,991 ⟶ 4,487:
writeln(sum35(1000_));
writeln(sum35(10_ ** 20));
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,001 ⟶ 4,497:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func sumMul(n, f) {
var m = int((n - 1) / f)
f * m * (m + 1) / 2
Line 4,012 ⟶ 4,508:
for i in (1..20) {
printf("%2s:%22s %s\n", i, 10**i, sum35(10**i))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,039 ⟶ 4,535:
=={{header|Simula}}==
(referenced from [[Greatest common divisor#Simula|Greatest common divisor]])
<langsyntaxhighlight lang="algol68">! Find the sum of multiples of two factors below a limit -
! Project Euler problem 1: multiples of 3 or 5 below 1000 & 10**20;
BEGIN
Line 4,092 ⟶ 4,588:
OUTIMAGE
END
END</langsyntaxhighlight>
{{out}}
sum of positive multiples of 3 and 5: 233168<br />
Line 4,105 ⟶ 4,601:
=={{header|Stata}}==
=== With a dataset ===
<langsyntaxhighlight lang="stata">clear all
set obs 999
gen a=_n
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)</langsyntaxhighlight>
 
=== With Mata ===
<langsyntaxhighlight lang="stata">mata
a=1..999
sum(a:*(mod(a,3):==0 :| mod(a,5):==0))</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
 
 
Line 4,137 ⟶ 4,633:
print(sumofmult)
 
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># Fairly simple version; only counts by 3 and 5, skipping intermediates
proc mul35sum {n} {
for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} {
Line 4,156 ⟶ 4,652:
}
return $total
}</langsyntaxhighlight>
However, that's pretty dumb. We can do much better by observing that the sum of the multiples of <math>k</math> below some <math>n+1</math> is <math>k T_{n/k}</math>, where <math>T_i</math> is the <math>i</math>'th [[wp:Triangular number|triangular number]], for which there exists a trivial formula. Then we simply use an overall formula of <math>3T_{n/3} + 5T_{n/5} - 15T_{n/15}</math> (that is, summing the multiples of three and the multiples of five, and then subtracting the multiples of 15 which were double-counted).
<langsyntaxhighlight lang="tcl"># Smart version; no iteration so very scalable!
proc tcl::mathfunc::triangle {n} {expr {
$n * ($n+1) / 2
Line 4,166 ⟶ 4,662:
incr n -1
expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts [mul35sum 1000],[sum35 1000]
puts [mul35sum 10000000],[sum35 10000000]
# Just the quick one; waiting for the other would get old quickly...
puts [sum35 100000000000000000000]</langsyntaxhighlight>
{{out}}
<pre>233168,233168
Line 4,178 ⟶ 4,674:
</pre>
 
=={{header|TI SR-56}}==
=== Iterative solution ===
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Sum Multiples" (Iterative)
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 33 || STO || 50 || || 75 ||
|-
| 01 04 || 4 || 26 00 || 0 || 51 || || 76 ||
|-
| 02 04 || 4 || 27 57 || *subr || 52 || || 77 ||
|-
| 03 52 || ( || 28 00 || 0 || 53 || || 78 ||
|-
| 04 52 || ( || 29 03 || 3 || 54 || || 79 ||
|-
| 05 34 || RCL || 30 12 || INV || 55 || || 80 ||
|-
| 06 00 || 0 || 31 37 || *x=t || 56 || || 81 ||
|-
| 07 54 || / || 32 03 || 3 || 57 || || 82 ||
|-
| 08 05 || 5 || 33 08 || 8 || 58 || || 83 ||
|-
| 09 53 || ) || 34 34 || RCL || 59 || || 84 ||
|-
| 10 12 || INV || 35 00 || 0 || 60 || || 85 ||
|-
| 11 29 || *Int || 36 35 || SUM || 61 || || 86 ||
|-
| 12 64 || x || 37 01 || 1 || 62 || || 87 ||
|-
| 13 52 || ( || 38 27 || *dsz || 63 || || 88 ||
|-
| 14 34 || RCL || 39 02 || 2 || 64 || || 89 ||
|-
| 15 00 || 0 || 40 07 || 7 || 65 || || 90 ||
|-
| 16 54 || / || 41 34 || RCL || 66 || || 91 ||
|-
| 17 03 || 3 || 42 01 || 1 || 67 || || 92 ||
|-
| 18 53 || ) || 43 41 || R/S || 68 || || 93 ||
|-
| 19 12 || INV || 44 74 || - || 69 || || 94 ||
|-
| 20 29 || *Int || 45 01 || 1 || 70 || || 95 ||
|-
| 21 53 || ) || 46 94 || = || 71 || || 96 ||
|-
| 22 58 || *rtn || 47 22 || GTO || 72 || || 97 ||
|-
| 23 56 || *CP || 48 02 || 2 || 73 || || 98 ||
|-
| 24 38 || *CMs || 49 03 || 3 || 74 || || 99 ||
|}
 
Asterisk denotes 2nd function key.
 
{| class="wikitable"
|+ Register allocation
|-
| 0: Current Term || 1: Sum Of Terms || 2: Unused || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
 
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point.
GTO 4 4
 
// Address 03: Subroutine
// If R0 is divisible by 3 and 5, return 0, else nonzero
( ( RCL 0 / 5 ) INV *Int x ( RCL 0 / 3 ) INV *Int ) *rtn
 
// Address 23: Main program
*CP *CMs // Zero all registers and T register.
STO 0 // R0 := Maximum number to consider.
*subr 0 3 // Check divisibility by 3 and 5.
INV *x=t 3 8 // Divisible?
RCL 0
SUM 1 // R1 += R0
*dsz 2 7 // R0--, repeat while nonzero.
RCL 1 // Retrieve answer.
R/S // End.
 
// Address 44: Input parsing
- 1 = // Consider all numbers *less than* N.
GTO 2 3
</syntaxhighlight>
 
'''Usage:'''
 
{{in}}
 
<pre>1000 RST R/S</pre>
 
{{out}}
 
<pre>233168</pre>
 
This took between 20 and 30 minutes to run.
 
=== Efficient closed-form solution ===
 
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Sum Multiples" (Closed-form)
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 29 || *Int || 50 54 || / || 75 ||
|-
| 01 01 || 1 || 26 57 || *subr || 51 01 || 1 || 76 ||
|-
| 02 06 || 6 || 27 00 || 0 || 52 05 || 5 || 77 ||
|-
| 03 33 || STO || 28 03 || 3 || 53 94 || = || 78 ||
|-
| 04 01 || 1 || 29 64 || x || 54 29 || *Int || 79 ||
|-
| 05 54 || / || 30 05 || 5 || 55 57 || *subr || 80 ||
|-
| 06 02 || 2 || 31 94 || = || 56 00 || 0 || 81 ||
|-
| 07 64 || x || 32 35 || SUM || 57 03 || 3 || 82 ||
|-
| 08 52 || ( || 33 02 || 2 || 58 64 || x || 83 ||
|-
| 09 34 || RCL || 34 34 || RCL || 59 01 || 1 || 84 ||
|-
| 10 01 || 1 || 35 00 || 0 || 60 05 || 5 || 85 ||
|-
| 11 84 || + || 36 54 || / || 61 94 || = || 86 ||
|-
| 12 01 || 1 || 37 03 || 3 || 62 12 || INV || 87 ||
|-
| 13 53 || ) || 38 94 || = || 63 35 || SUM || 88 ||
|-
| 14 53 || ) || 39 29 || *Int || 64 02 || 2 || 89 ||
|-
| 15 58 || *rtn || 40 57 || *subr || 65 34 || RCL || 90 ||
|-
| 16 38 || *CMs || 41 00 || 0 || 66 02 || 2 || 91 ||
|-
| 17 74 || - || 42 03 || 3 || 67 41 || R/S || 92 ||
|-
| 18 01 || 1 || 43 64 || x || 68 || || 93 ||
|-
| 19 94 || = || 44 03 || 3 || 69 || || 94 ||
|-
| 20 33 || STO || 45 94 || = || 70 || || 95 ||
|-
| 21 00 || 0 || 46 35 || SUM || 71 || || 96 ||
|-
| 22 54 || / || 47 02 || 2 || 72 || || 97 ||
|-
| 23 05 || 5 || 48 34 || RCL || 73 || || 98 ||
|-
| 24 94 || = || 49 00 || 0 || 74 || || 99 ||
|}
 
Asterisk denotes 2nd function key.
 
{| class="wikitable"
|+ Register allocation
|-
| 0: Maximum Term || 1: Parameter || 2: Answer || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
 
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point.
GTO 1 6
 
// Address 03: Subroutine
// Calculates sum of nums 1-N as (N/2)(N+1).
STO 1
/ 2 x ( RCL 1 + 1 ) ) *rtn
 
// Address 16: Main program
*CMs // Clear registers.
- 1 = STO 0 // R0 := N-1
/ 5 = *Int *subr 0 3 x 5 = SUM 2 // R2 += fives
RCL 0 / 3 = *Int *subr 0 3 x 3 = SUM 2 // R2 += threes
RCL 0 / 1 5 = *Int *subr 0 3 x 1 5 = INV SUM 2 // R2 -= fifteens
RCL 2 // Retrieve answer.
R/S // End.
</syntaxhighlight>
 
'''Usage:'''
 
{{in}}
 
<pre>1000 RST R/S</pre>
 
{{out}}
 
<pre>233168</pre>
 
Completed in 4 seconds.
 
{{in}}
 
<pre>1 EE 20 RST R/S</pre>
 
{{out}}
 
<pre>2.333333333 39</pre>
 
Completed in 4 seconds.
 
=={{header|Uiua}}==
<syntaxhighlight>
End ← 1000
 
MultOfthree ← ⊚=0◿3 # indices where divisible by 3
Indicesthree ← MultOfthree ↘1⇡End
MultOffive ← ⊚=0◿5 # indices where divisible by 5
IndicesFive ← MultOffive ↘1⇡End
 
/+ ⊏⊂ Indicesthree IndicesFive ↘1⇡End # join, select and sum
</syntaxhighlight>
{{out}}
233168
</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
Only works up to 1000000000 due to limits of shell integer representation.
 
<syntaxhighlight lang="sh">function sum_multiples {
typeset -i n=$1 limit=$2
typeset -i max=limit-1
(( max -= max % n ))
printf '%d\n' $(( max / n * (n+max)/2 ))
}
 
function sum35 {
typeset -i limit=$1
printf '%d\n' $(( $(sum_multiples 3 $limit)
+ $(sum_multiples 5 $limit)
- $(sum_multiples 15 $limit) ))
}
 
for (( l=1; l<=1000000000; l*=10 )); do
printf '%10d\t%18d\n' "$l" "$(sum35 "$l")"
done</syntaxhighlight>
 
{{Out}}
<pre> 1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668</pre>
=={{header|VBA}}==
{{trans|VBScript}}
<langsyntaxhighlight lang="vb">Private Function SumMult3and5VBScript(n As Double) As Double
Dim i As Double
For i = 1 To n - 1
Line 4,187 ⟶ 4,948:
End If
Next
End Function</langsyntaxhighlight>
Other way :
<langsyntaxhighlight lang="vb">Private Function SumMult3and5(n As Double) As Double
Dim i As Double
For i = 3 To n - 1 Step 3
Line 4,197 ⟶ 4,958:
If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
Next
End Function</langsyntaxhighlight>
Better way :
<langsyntaxhighlight lang="vb">Private Function SumMult3and5BETTER(n As Double) As Double
Dim i As Double
For i = 3 To n - 1 Step 3
Line 4,210 ⟶ 4,971:
SumMult3and5BETTER = SumMult3and5BETTER - i
Next
End Function</langsyntaxhighlight>
 
Call :
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 4,225 ⟶ 4,986:
Debug.Print "-------------------------"
Debug.Print SumMult3and5BETTER(1000)
End Sub</langsyntaxhighlight>
{{Out}}
<pre>2,33333331666667E+15 9,059 sec.
Line 4,236 ⟶ 4,997:
=={{header|VBScript}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function multsum35(n)
For i = 1 To n - 1
Line 4,247 ⟶ 5,008:
WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
<pre>
F:\>cscript /nologo multsum35.vbs 1000
233168
</pre>
 
 
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">module main;
integer i, suma;
initial begin
suma = 0;
for(i = 1; i <= 999; i=i+1)
begin
if(i % 3 == 0) suma = suma + i;
else if(i % 5 == 0) suma = suma + i;
end
$display(suma);
$finish ;
end
endmodule</syntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="go">fn s35(n int) int {
mut nn := n-1
mut threes := nn/3
mut fives := nn/5
mut fifteen := nn/15
 
threes = 3 * threes * (threes + 1)
fives = 5 * fives * (fives + 1)
fifteen = 15 * fifteen * (fifteen + 1)
 
nn = (threes + fives - fifteen) / 2
return nn
}
 
fn main(){
println(s35(1000))
}</syntaxhighlight>
{{out}}
<pre>
233168
</pre>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
sum35 ^(@sum \!-@(\~%%3 || \~%%5) @til)
!sum35 1000 ; returns 233168
}</langsyntaxhighlight>
 
=={{header|Wren}}==
===Simple version===
<lang ecmascript>var sum35 = Fn.new { |n|
<syntaxhighlight lang="wren">var sum35 = Fn.new { |n|
n = n - 1
var s3 = (n/3).floor
Line 4,274 ⟶ 5,078:
}
 
System.print(sum35.call(1000))</langsyntaxhighlight>
 
{{out}}
<pre>
233168
</pre>
<br>
===Fast version with arbitrary precision===
{{trans|C}}
{{libheader|Wren-gmp}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./gmp" for Mpz
import "./fmt" for Fmt
 
var sumMultiples = Fn.new { |result, limit, f|
var m = Mpz.from(limit).sub(1).fdiv(f)
result.set(m).inc.mul(m).mul(f).rsh(1)
}
 
var limit = Mpz.one
var tempSum = Mpz.new()
var sum35 = Mpz.new()
var max = 25
Fmt.print("$*s $s", max + 1, "limit", "sum")
for (i in 0..max) {
Fmt.write("$*s ", max + 1, limit)
sumMultiples.call(tempSum, limit, 3)
sum35.set(tempSum)
sumMultiples.call(tempSum, limit, 5)
sum35.add(tempSum)
sumMultiples.call(tempSum, limit, 15)
sum35.sub(tempSum)
System.print(sum35)
limit.mul(10)
}</syntaxhighlight>
 
{{out}}
<pre>
limit sum
1 0
10 23
100 2318
1000 233168
10000 23331668
100000 2333316668
1000000 233333166668
10000000 23333331666668
100000000 2333333316666668
1000000000 233333333166666668
10000000000 23333333331666666668
100000000000 2333333333316666666668
1000000000000 233333333333166666666668
10000000000000 23333333333331666666666668
100000000000000 2333333333333316666666666668
1000000000000000 233333333333333166666666666668
10000000000000000 23333333333333331666666666666668
100000000000000000 2333333333333333316666666666666668
1000000000000000000 233333333333333333166666666666666668
10000000000000000000 23333333333333333331666666666666666668
100000000000000000000 2333333333333333333316666666666666666668
1000000000000000000000 233333333333333333333166666666666666666668
10000000000000000000000 23333333333333333333331666666666666666666668
100000000000000000000000 2333333333333333333333316666666666666666666668
1000000000000000000000000 233333333333333333333333166666666666666666666668
10000000000000000000000000 23333333333333333333333331666666666666666666666668
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func Sum1; \Return sum the straightforward way
Line 4,323 ⟶ 5,187:
StrNSub(S, T, 40);
TextN(0, T, 40); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,333 ⟶ 5,197:
 
=={{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 stdout = std.io.getStdOut().writer();
 
fn sumdivDoubleWide(comptime n: i64, d: i64anytype) i128type {
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;
}
 
fn sum3or5(n: i64anytype) i128DoubleWide(n) {
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}
 
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}}
<pre>
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1e181e20 is 2333333333333333331666666666666666682333333333333333333316666666666666666668
 
</pre>
=={{header|zkl}}==
Brute force:
<langsyntaxhighlight lang="zkl">[3..999,3].reduce('+,0) + [5..999,5].reduce('+,0) - [15..999,15].reduce('+,0)
233168</langsyntaxhighlight>
{{trans|Groovy}}
Using a formula, making sure the input will cast the result to the same type (ie if called with a BigNum, the result is a BigNum).
<langsyntaxhighlight lang="zkl">fcn sumMul(N,m){N=(N-1)/m; N*(N+1)*m/2}
fcn sum35(N){sumMul(N,3) + sumMul(N,5) - sumMul(N,15)}</langsyntaxhighlight>
{{out}}
<pre>
2

edits