Given N integers, output the sum of those integers.
Input
You may take the integers in any reasonable format, including:
stdin
- arguments
- an array or list
Rules
Your code must not include the characters
+
or-
.Standard loopholes apply. Take note of Abusing native number types to trivialize a problem.
This is code-golf. The shortest code in each language wins, which means that I will not be accepting an answer.
Testcases
n=2, 1, 2 -> 3
n=2, 2, 2 -> 4
n=2, 9, 10 -> 19
n=2, 7, 7 -> 14
n=2, 8, 8 -> 16
n=2, -5, 3 -> -2
n=2, -64, -64 -> -128
n=2, -3, 0 -> -3
n=2, 0, 3 -> 3
n=2, 0, 0 -> 0
n=2, -1, -1 -> -2
n=2, -315, -83 -> -398
n=2, 439, 927 -> 1366
n=3, 1, 2, 3 -> 6
n=3, 2, 2, 5 -> 9
n=3, 0, 9, 10 -> 19
n=3, 7, 0, 7 -> 14
n=3, 8, 8, 0 -> 16
n=3, -5, 3, -2 -> -4
n=3, -64, -64, 16 -> -112
n=3, -3, 0, 0 -> -3
n=3, 0, 3, 0 -> 3
n=3, 0, 0, 0 -> 0
n=3, -1, -1, -1 -> -3
n=3, -315, -83, -34 -> -432
n=3, 439, 927, 143 -> 1509
n=17, -74, 78, 41, 43, -20, -72, 89, -78, -12, -5, 34, -41, 91, -43, -23, 7, -44 -> -29
Testcases with partial sums that exceed 8 bits are only required if your integer type supports each partial sum (if any) and the final result. As a special case, n=2, -64, -64 -> -128
is only required if your integer type can represent -128
.
Testcases involving negative integers are only required if your language natively supports negative integers.
-
\$\begingroup\$ I have one which I think is neat enough to be a notable mention though it doesn't strictly abide by the rules. Instead of summing a list, it only adds 2 numbers... Any chance I can still add it and let the votes decide? \$\endgroup\$AviFS– AviFS2020年03月24日 02:26:28 +00:00Commented Mar 24, 2020 at 2:26
-
2\$\begingroup\$ @AviF.S., that would not be a valid solution to the challenge. \$\endgroup\$Shaggy– Shaggy2020年03月24日 13:37:59 +00:00Commented Mar 24, 2020 at 13:37
-
\$\begingroup\$ @Avi If you create another function that does the rest of the adding, then yes. Otherwise, no. \$\endgroup\$S.S. Anne– S.S. Anne2020年03月24日 15:22:20 +00:00Commented Mar 24, 2020 at 15:22
-
\$\begingroup\$ I see you've had mercy on languages that don't support numbers that require 8 bits, a generous allowance. Any chance it's also alright if our language doesn't support negative numbers? (I don't mean to keep poking at the question, but I'd really love to be able to submit answers in languages not meant for this sort of thing and still have them be reasonably elegant, even if not short!) \$\endgroup\$AviFS– AviFS2020年04月24日 18:29:56 +00:00Commented Apr 24, 2020 at 18:29
-
\$\begingroup\$ @AviF.S. That's acceptable. The other was not, as that would make the challenge extremely trivial. \$\endgroup\$S.S. Anne– S.S. Anne2020年04月24日 18:36:33 +00:00Commented Apr 24, 2020 at 18:36
61 Answers 61
-
\$\begingroup\$ @a'_' As far as I remember, it sums the elements on the diagonal of a matrix, or, if it's actually a vector, just sums everything. \$\endgroup\$the default.– the default.2020年03月23日 05:33:32 +00:00Commented Mar 23, 2020 at 5:33
Python 2, (削除) 97 95 93 88 (削除ここまで) 87 bytes
Solution that doesn't use the built-in sum
, eval
or exec
:
-2 bytes thanks to @JonathanAllan!
-1 byte thanks to @ovs!
x=y=1
for i in input():x<<=i*(i>0);y<<=abs(i)
y/=x
print" ~"[x<y],len(bin(x/y|y/x)[3:])
Input: a comma separated list of numbers, from stdin.
Output: the sum is printed to stdout. If the sum is negative, the ~
sign is used instead of -
due to source code restriction.
How: Let \$p\$ be the sum of all positive numbers in the list, and \$n\$ be the magnitude of the sum of all negative numbers. Then the sum of the list is \$p-n\$.
Let \$x=2^p\$ and \$y=2^n\$, then \$\frac xy=2^{p-n}\$.
Thus if the sum is positive (aka \$x>y\$), we can calculate the sum by counting the number of zeros in the binary representation of \$\frac xy\$. Otherwise, we can calculate the magnitude of the sum as the number of zeros in the binary representation of \$\frac yx\$.
-
2\$\begingroup\$
x<<=i*(i>0);y<<=abs(i*(i<0))
saves two over usingmax
andmin
. \$\endgroup\$Jonathan Allan– Jonathan Allan2020年03月22日 23:35:20 +00:00Commented Mar 22, 2020 at 23:35 -
-
\$\begingroup\$ @ovs Thanks! I cannot use
-3
since it contains-
, but can still save 1 byte withy/=x
. \$\endgroup\$Surculose Sputum– Surculose Sputum2020年04月20日 18:38:32 +00:00Commented Apr 20, 2020 at 18:38
JavaScript (ES6), 21 bytes
Takes input as an array of integers.
a=>eval(a.join`\x2B`)
JavaScript (ES6), 40 bytes
Takes input as an array of integers.
a=>a.reduce(g=(x,y)=>y?g(x^y,(x&y)*2):x)
-
\$\begingroup\$ Amazing formula! Waiting for an explanation on why this will eventually terminate. \$\endgroup\$Surculose Sputum– Surculose Sputum2020年03月22日 22:58:43 +00:00Commented Mar 22, 2020 at 22:58
-
3\$\begingroup\$ @SurculoseSputum It is quite similar to a binary addition by hand: the
XOR
does the addition without the carries which are processed separately by the doubledAND
. The recursion stop when there's no more carry. It is described here for instance, and some other variants can be found here. \$\endgroup\$Arnauld– Arnauld2020年03月22日 23:37:19 +00:00Commented Mar 22, 2020 at 23:37
C (gcc), (削除) 50 (削除ここまで) (削除) 45 (削除ここまで) (削除) 43 (削除ここまで) 38 bytes
f(s,e)char**s;{s=s<e?&f(&s[1])[*s]:0;}
-7 bytes thanks to @S.S. Anne
-5 bytes thanks to @Bubbler
Takes for input start and end pointers. It uses the fact that the address of &a[b]
equals a+b
. Other than that, even I am a bit confused as to how this works.
-
\$\begingroup\$ Nicely done, but fails on multiple test cases, like
0, 3, 0
and7, 0, 7
and0, 9, 10
. \$\endgroup\$S.S. Anne– S.S. Anne2020年03月22日 23:50:39 +00:00Commented Mar 22, 2020 at 23:50 -
\$\begingroup\$ You're right, let me see if I can fix that... \$\endgroup\$dingledooper– dingledooper2020年03月22日 23:58:33 +00:00Commented Mar 22, 2020 at 23:58
-
1
-
1
-
1
APL (dzaima/APL), 2 bytes SBCS
Anonymous tacit prefix function
1⊥
Simply evaluates a "digit" list in base 1.
-
1\$\begingroup\$ Absolutely brilliant! How ever did it occur to you? The best part is it's no longer than the normal way. Replacing
+/
with1⊥
in all golfed APL has to be the best way of obfuscating and impressing people ever... \$\endgroup\$AviFS– AviFS2020年03月22日 22:16:27 +00:00Commented Mar 22, 2020 at 22:16 -
\$\begingroup\$ @AviF.S. It is a common trick in tacit APL due to it being a dyadic function application rather than a monadic one which cannot be composed with a function on its left. \$\endgroup\$Adám– Adám2020年03月22日 22:19:22 +00:00Commented Mar 22, 2020 at 22:19
-
\$\begingroup\$ Whoops. Now that it's documented, I feel silly acting like it was so novel... But I do still think it's a brilliant trick! \$\endgroup\$AviFS– AviFS2020年03月22日 22:22:29 +00:00Commented Mar 22, 2020 at 22:22
-
\$\begingroup\$ Also works in Haskell, and many other languages I'm sure. \$\endgroup\$79037662– 790376622020年03月22日 23:03:16 +00:00Commented Mar 22, 2020 at 23:03
GERMAN, 141 bytes
EINGABESCHLEIFENANFANGSUBTRAKTIONRECHTSEINGABESCHLEIFENANFANGSUBTRAKTIONRECHTSADDITIONLINKSSCHLEIFENENDELINKSSCHLEIFENENDERECHTSRECHTSAUSGABE
-
14\$\begingroup\$ i'm disappointed this is just another brainfuck derivative rather than some complex combination of german words \$\endgroup\$Jo King– Jo King2020年03月23日 00:22:55 +00:00Commented Mar 23, 2020 at 0:22
-
\$\begingroup\$ @JoKing I am sorry to disappoint you. Unfortunately, programming languages not based on English are quite rare ... \$\endgroup\$Jonathan Frech– Jonathan Frech2020年03月23日 01:52:45 +00:00Commented Mar 23, 2020 at 1:52
Bash + GNU utilities, 57 bytes
printf %.f $(bc -l<<<"99*l(e(`sed 's@ @/99)*e(@g'`/99))")
Reads space-separated integers from stdin, and writes the output to stdout.
This applies the exponential function to each integer, multiplies the results, and then takes the natural logarithm of the product. I need to scale the input numbers (and then "unscale" the result) so as not to overflow the exponentials on some of the starred test examples (that's what the 99*
and /99
are doing there).
Mornington Crescent, (削除) 634 (削除ここまで) 537 bytes
Take Northern Line to Bank
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Temple
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Upminster
Take District Line to Parsons Green
Take District Line to Bank
Take Northern Line to Charing Cross
Take Northern Line to Angel
Take Northern Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
// initialize adder
Take Northern Line to Bank // save input to Hammersmith
Take District Line to Parsons Green // get 0
Take District Line to Upminster // set Upminster = 0
// set start of loop
Take District Line to Temple
// extract leading number
Take District Line to Hammersmith
Take District Line to Parsons Green
// add it to previous sum
Take District Line to Upminster // accumulator = sum
// Upminster = previous accumulator
// save sum in Upminster
Take District Line to Upminster
// get remaining string
Take District Line to Parsons Green
// check if it is equal to "" by translating the first char to its codepoint (0 if empty)
// we ride a few extra rounds here, adding 0s to the sum
Take District Line to Bank // save string and
// get string of previous round
Take Northern Line to Charing Cross // swap accumulator with Charing Cross
// and get codepoint of previous values'
// first char (that's from two rounds ago)
// or 0 if empty
// if string is not empty (meaning, accumulator is non-zero), repeat
Take Northern Line to Angel
// else read sum
Take Northern Line to Bank // get empty string
Take District Line to Upminster // swap with Upminster
// and go home, outputting the number
Take District Line to Bank // change lines, swapping data with Bank
Take Circle Line to Bank // swap back
Take Northern Line to Mornington Crescent // go home
C (gcc), 94 bytes
x,c;n(a,b){for(;b;b=x*2)x=a&b,a^=b;x=a;}f(a,t)int*a;{for(c=1;c<t;c=n(c,1))*a=n(*a,a[c]);c=*a;}
A non-trivial golfed reference implementation.
I realized I had worded myself out of an answer when I couldn't even use +
or -
for a counter variable.
Mornington Crescent, 1267 bytes
Poorly golfed, may have to have another attempt tomorrow.
Take Northern Line to Bank
Take Northern Line to Euston
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Moorgate
Take Circle Line to Temple
Take Circle Line to Moorgate
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Moorgate
Take Circle Line to Hammersmith
Take Circle Line to Embankment
Take Northern Line to Charing Cross
Take Northern Line to Angel
Take Northern Line to Bank
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
-
\$\begingroup\$ I realized today that my past self was smarter and that my "better" solution is wrong -- it misses the edge case 0, which causes the program to terminate prematurely in the case of an input such as
3 0 4 1
. Reverted, and see Dorian's Mornington Crescent answer as well for an improvement on how I handled this originally. \$\endgroup\$Cloudy7– Cloudy72023年04月26日 03:13:53 +00:00Commented Apr 26, 2023 at 3:13
Python 3, 62/61 bytes
Without relying on sum in other functions.
def f(i,x=0):
for y in i:
while y:x,y=x^y,(x&y)*2
return x
Can be shortened to 61 by removing the function definition (-13), replacing in i:
with in eval(input()):
(+12) and print instead of return at the end (+0).
Python, 3 bytes
sum
Built in function which does the job
With no built-in, 36 bytes in Python 2:
-3 thanks to ovs!
lambda a:eval(`a`.replace(*',\x2b'))
Note: a single value may be represented as a singleton list (meta)
-
\$\begingroup\$
'\x2b'
is one bytes shorter thanchr(43)
. Thenreplace(*',\x2b')
is another two bytes shorter. \$\endgroup\$ovs– ovs2020年04月20日 12:52:29 +00:00Commented Apr 20, 2020 at 12:52 -
\$\begingroup\$ @ovs - very nice, thank you! \$\endgroup\$Jonathan Allan– Jonathan Allan2020年04月20日 21:15:00 +00:00Commented Apr 20, 2020 at 21:15
-
2\$\begingroup\$ The built-in function also works in other versions. \$\endgroup\$The Empty String Photographer– The Empty String Photographer2023年05月03日 12:55:41 +00:00Commented May 3, 2023 at 12:55
Keg, -hr
, 2 bytes
÷∑
The joys of not having implemented lists properly! Simply item split and summate. Essentially uses a sum function, so no imaginary points for me.
Batch, 93 bytes
43
is the ASCII code for +
:
@!! 2>nul||cmd/q/v/c%0&&exit/b
set c=cmd/c
set/pn=
%c%exit 43
%c%set/a !n: =%=exitcodeascii%!
Takes input via STDIN
, delimited by space.
Haskell, 3 bytes
sum
Function that takes an argument as a list e.g. sum[1,2,3]
and returns the sum of the list.
x86-16 machine code, 8 bytes
33 D2 XOR DX, DX ; clear running sum (in DX)
AN:
AD LODSW ; load next value into AX
03 D0 ADD DX, AX ; add AX to running sum
E2 FB LOOP AN ; loop until CX = 0
C3 RET ; return to caller
Input size in CX
, data in [SI]
. Output sum in DX
.
SQL, 21 bytes
SELECT SUM(N) FROM T;
This assumes the numbers to be in table T
, in a column named N
.
Brainetry, 143 bytes
a b c d e f
a b
a b c d e f
a b c d e f g h
a b c d e f g h
a b c d e
a b c d
a
a b c d e f g h i
a b c d e f
a b c d e f g h i
a b c d e f g
To try it online follow this repl.it link and paste the code in the btry/replit.btry
file, then press the green "Run" button. Does I/O as ASCII codepoints.
The program above is the golfed version of this program:
Let me sum some numbers carefully.
Carefully enough
so that I do not use
the plus or minus signs, that'd be awful.
After I do this, oh so very carefully,
I just have to ...
Move the pointer
left and right for
a while.
This is the main gist of the whole program.
Of course this sounds somewhat uninteresting.
That is because you, my dear reader, lack depth.
(Is it "depth"?
Maybe that's not the correct English word...)
-
1\$\begingroup\$ These brainerty poems are always very interesting. \$\endgroup\$The Fifth Marshal– The Fifth Marshal2020年06月18日 01:42:00 +00:00Commented Jun 18, 2020 at 1:42
-
\$\begingroup\$ Do you need the blank lines in the golfed program? \$\endgroup\$The Fifth Marshal– The Fifth Marshal2020年06月18日 03:04:02 +00:00Commented Jun 18, 2020 at 3:04
-
\$\begingroup\$ @pppery not sure if you are just making fun or if you really think they are funny. Yes, the blank lines are needed. In Brainetry a blank line moves the pointer to the left edge of the tape, cf. this quick reference table \$\endgroup\$RGS– RGS2020年06月18日 08:06:56 +00:00Commented Jun 18, 2020 at 8:06
Pip, 4 bytes
_MSg
MS
maps a function to an iterable and sums its results.
_
is the identity function.
g
is the list of command line args.
05AB1E, 1 bytes
O
Input as a list.
Try it online or verify all test cases.
Slightly less boring:
1β
Try it online or verify all test cases.
Explanation:
O # Sum the (implicit) input-list
# (and output the result implicitly)
1β # Convert the (implicit) input-list to base-1
# (and output the result implicitly)
Racket, 133 bytes
(define(f a[s 0])(if(null? a)s(let([c(car a)])(if(= 0 c)(f(cdr a)s)(f(cons((if(> 0 c)add1 sub1)c)(cdr a))((if(> 0 c)sub1 add1)s))))))
Well...
perl -ple, 18 bytes
s/ /\x2b/g;$_=eval
Reads a space separated list of numbers from STDIN
, writes the sum to STDOUT
.
perl -MList::Util=sum -alpe, 8 bytes
$_=sum@F
-
\$\begingroup\$ you can to save some bytes Try it online! \$\endgroup\$mazzy– mazzy2020年03月23日 14:15:37 +00:00Commented Mar 23, 2020 at 14:15
-
\$\begingroup\$ @mazzy much thanks! \$\endgroup\$wasif– wasif2020年03月23日 15:41:27 +00:00Commented Mar 23, 2020 at 15:41
Haskell, 3 Bytes
sum
calculates the sum of a list
-
1
-
\$\begingroup\$ Duplicate answers aren't invalid, but users are encouraged to check for existing answers before posting \$\endgroup\$Jo King– Jo King2020年09月30日 02:19:38 +00:00Commented Sep 30, 2020 at 2:19