Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Implement a function diff that takes as input three integers x, y, and z. It should return whether subtracting one of these numbers from another gives the third.

Test cases:
diff(5, 3, 2) yields True because 5 - 3 = 2
diff(2, 3, 5) yields True because 5 - 3 = 2
diff(2, 5, 3) yields True because 5 - 3 = 2
diff(-2, 3, 5) yields True because 3 - 5 is -2
diff(-5, -3, -2) # -5 - -2 is -3
diff(2, 3, -5) yields False
diff(10, 6, 4) yields True because 10 - 6 = 4
diff(10, 6, 3) yields False

You don't have to name the function, you may implement default input methods the examples above are not a strict guideline.

share|improve this question
This is a reasonable challenge, but there's no need to restrict it to Python or functions. In general, such restrictions are frowned upon because they limit participation. Also, you should include some test cases. – xnor Feb 7 at 9:37
Hey I fixed it a little. Hope this suffices! – Mir Feb 7 at 9:45
Looks better! I still strongly recommend allowing the default input methods, in particular programs, because some languages don't have functions. And, allowing functions to have another name or no name. – xnor Feb 7 at 9:48
The first and last paragraphs are now conflicting, so just to double check - do we have to write a function or are full programs okay? – Sp3000 Feb 7 at 10:03
full programs are fine, I want to impose as few restrictions as possible except that the default input methods are followed. ef the python3 examples is neat! – Mir Feb 7 at 10:18

25 Answers 25

Python 3, 21 bytes

lambda*l:sum(l)/2in l

If two numbers add to the other, the sum of all three will be double that other number, so half the sum will be an element of the list. Python 3 is needed to avoid floor-division, unless the numbers are given like 3.0 rather than 3.

share|improve this answer

Jelly, 5 3 bytes

Thanks to @Sp3000 for saving two bytes!

Code, uses quite the same algorithm as @xnor's great answer:



S     # Sum of the argument list
  Ḥ   # Double the list
 f    # Filter, remove everything that isn't equal to the sum of the list

This gives [] as falsy, and anything else as truthy.

Try it online!

share|improve this answer

ES6, 31 bytes


Add 5 bytes if you need to name the function diff.

Edit: Saved 2 bytes thanks to @Alex L.

share|improve this answer
You can save two bytes by replacing || with | (I think) – Alex L. Feb 9 at 3:16
@AlexL. Ah right I was too hung up on having to return Booleans. – Neil Feb 9 at 8:59
Even with booleans, | returns a boolean if and only if both values are booleans. So true | false == true, but 3 | 5 == 7. The same applies && and &. The only difference between | and || when it comes to booleans: | will take the first value and the second value and find the OR of those two. || will take the first value; if it is true, return true, otherwise, return the second value. – Alex L. Feb 9 at 13:50
@AlexL. true | false evaluates to 1 in JavaScript (which is truthy, but not Boolean). – Neil Feb 9 at 18:52
Oh. Sorry, I don't really use JS. I mostly use Java, which is where I got that information from. ;) – Alex L. Feb 9 at 19:01

APL, 8 5 bytes


This is a monadic function train that accepts an array and returns a boolean (0/1 in APL). It uses the same algorithm as xnor's Python 3 answer.


   +⍨  ⍝ Double the input (+⍨x is the same as x+x)
  ∊    ⍝ Test the membership of
+/     ⍝ The sum of the input

Try it online

Saved 3 bytes thanks to Dennis!

share|improve this answer

JavaScript ES6, 38 34 33 bytes


Very simple anonymous function, and borrows from the Python answer. Takes input x as an array; returns true or false. Bytes shaved to Molarmanful and jrich

A 38-byte program, taking each number as an argument:

share|improve this answer
Try x=>x.some(a=>a==eval(x.join`+`)/2), which saves 4 bytes. – Mama Fun Roll Feb 7 at 23:29
@ӍѲꝆΛҐӍΛПҒЦꝆ Thanks! Nice trick. – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 7 at 23:34
x=>x.some(a=>2*a==x[0]+x[1]+x[2]) seems to work. – jrich Feb 9 at 2:42
@jrich Thanks! Nice trick! – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 9 at 2:44

Oracle SQL 11.2, 49 bytes

SELECT 1 FROM DUAL WHERE(:1+:2+:3)/2IN(:1,:2,:3);

Rewrite of @xnor solution, kudos to him.

share|improve this answer

J, 6 bytes


Try it with J.js.

How it works

+/e.+:    Monadic verb. Argument: A
    +:    Double the elements of A.
+/        Compute the sum of the elements of A.
  e.      Test for membership.
share|improve this answer

DUP, 31 chars / 39 bytes


Try it here!

My first DUP submission ever! Unicode is your oyster.

It's an anonymous function/lambda. Usage:

5 3 2[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]!


[                               {start lambda}
 2ø2ø2ø                         {duplicate 3 inputnums}
       ++                       {push sum(3 popped stack items)}
         2/\%                   {push (popped stack item)/2}
             3ø^=3ø2ø=3ø3ø=     {for all 3 inputs, -1 if inputnum=sum/2; else 0}
                           ||   {check if any of the 3 resulting values are truthy}
                             .  {output top of stack (boolean value)}
                              ] {end lambda}
share|improve this answer
I don't think that's how an encoding works... – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 7 at 23:19
ø has code point 248, so it is one byte if encoded as ISO 8859-1. – Dennis Feb 7 at 23:25
... which is fine as long as the interpreter can actually work with an ISO 8859-1 encoded source file. – Martin Büttner Feb 8 at 11:28
@MartinBüttner I don't think it's possible to test that. – Mama Fun Roll Feb 9 at 1:40

Java 7, 81

boolean d(int[]a){int s=0,t=1;for(int b:a)s+=b;for(int b:a)t*=2*b-s;return t==0;}
share|improve this answer

Perl 6, 20 19 bytes

I have two functions equal in byte count, so I'll put both. Appreciate whichever tickles your fancy.

{@_∋@_.sum div 2}

Usage: assign either one to a variable from which you can call it.
EDIT: Thanks @b2gills for the byte reduction

share|improve this answer
{@_∋@_.sum div 2} and {@_∋+~(@_.sum/2)} are both shorter – Brad Gilbert b2gills Feb 8 at 22:00
Oh thanks, I always forget you can call sum as a dotty method – LockOpeners Feb 8 at 22:10
What does do ? – User112638726 Feb 9 at 8:45
"∋" is the 'contains' infix operator, which says that the left contains the right. It's the sister to the "∈" 'element' op which say that the left is an element of the right. They're both set ops and perl 6 actually supports many others too!… – LockOpeners Feb 9 at 17:37

Pyth, 6 bytes


Try it online!

Expects input as a list of integers. Outputs 0 if no number can be built by subtracting the other two and >0 if at least one can.


Same algorithm as the answer of @xnor


   sQ     # Sum all elements in the list
  /  2    # Divide the sum by 2
/Q        # Count Occurences of above number in the list
share|improve this answer

05AB1E, non-competing

4 bytes, non-competing because of a stupid thing. Code:


Using 0 as falsy and > 0 as truthy. Uses CP-1252 encoding.

share|improve this answer
What's the "stupid" thing that makes this non-competing? – Kyle Kanos Feb 7 at 13:34
@KyleKanos I already have written in Info.txt that ; halves the top of the stack. But guess what, I've never implemented it -_-. – Adnan Feb 7 at 13:36
Ah. I can see how that'd do it – Kyle Kanos Feb 7 at 13:37

Kona 16 chars

{((+/x)%2)_in x}

Takes a vector from the stack, sums them, divides by 2 and determines if it's in the vector. Returns 1 as truthy and 0 as falsey.

Called via

> {((+/x)%2)_in x} [(2;3;5)]
> {((+/x)%2)_in x} [(2;3;4)]
share|improve this answer

jq, 17 characters

(Yet another rewrite of xnor's Python 3 answer. Upvotes should go to that one.)


Input: array of 3 integers.

Sample run:

bash-4.3$ jq 'contains([add/2])' <<< '[5, 3, 2]'

bash-4.3$ jq 'contains([add/2])' <<< '[2, 3, -5]'

On-line test:

jq, 18 characters

(17 characters code + 1 character command line option.)


Input: list of 3 integers.

Sample run:

bash-4.3$ jq -s 'contains([add/2])' <<< '5 3 2'

bash-4.3$ jq -s 'contains([add/2])' <<< '2 3 -5'
share|improve this answer

MATL, 5 bytes

Using @xnor's great approach:


Try it online!

s    % implicitly input array of three numbers. Compute their sum
2/   % divide by 2
G    % push input again
m    % ismember function: true if sum divided by 2 equals some element of the input

Brute-force approach, 12 bytes:


Try it online!

Y@       % input array of three numbers. Matrix with all
         % permutations, each one on a different row
TT-1h    % vector [1,1,-1]
*        % multiply with broadcast
!s       % transpose, sum of each column (former row)
~a       % true if any value is 0
share|improve this answer

𝔼𝕊𝕄𝕚𝕟, 7 chars / 9 bytes


Try it here (Firefox only).

Meh. I'm still finding better ways. It's just @xnor's awesome algorithm.

share|improve this answer

CJam, 10 12 bytes


2 bytes removed thanks to @MartinBüttner.

This displays a number as truthy result, and no output as falsy result.

Try it here

l~     e# read line and evaluate. Pushes the array
:d     e# convert array to double
_      e# duplicate
:+     e# fold addition on the array. Computes sum of the array
2/     e# divide sum by 2
&      e# setwise and (intersection)
share|improve this answer

Seriously, 6 bytes


Outputs 0 if false and a positive integer otherwise.

share|improve this answer

Mathematica, 20 19 bytes


Works similarly to most of the other answers.

share|improve this answer
How about MemberQ[2{##},+##]&? (and you forgot your byte count) – Martin Büttner Feb 7 at 20:26

Java 8 (lambda function), 29 bytes

// Lambda Signature: (int, int, int) -> boolean


Java code golf solutions are usually only short when the program does not have to be a fully functional program. (*cough cough* class declaration, main method)

share|improve this answer

Haskell, 20 bytes

(\l->sum l/2`elem`l)

Using xnor's solution.

share|improve this answer
Since (/) doesn't work for integers and the challenge asks for integers, I'm not sure that this is actually a valid solution. – Zeta Feb 9 at 12:13
I did not see that. Should the type conversion be part of the code? Like this: (\l->sum l/2`elem`l).map fromInteger and it can be used like this: ((\l->sum l/2`elem`l).map fromInteger) ([2,3,5] :: [Integer]). I guess what threw me off was xnor mentioning the use of python 3 so the input didn't have to be 3.0 instead of 3. I thought the input type wasn't specified, just the way they were written... – Boomerang Feb 9 at 12:44
If the type is a really a problem shouldn't the fact that I'm taking a list as input be more of an issue? – Boomerang Feb 9 at 12:57
Good point. I would ask OP about that. But given that all the other answers also use a list, I guess it's OK (also, now I get why your function didn't type check when using tuples). – Zeta Feb 9 at 13:06
Yes if the input was a tuple instead of a list neither sum nor elem would work, I should probably have specified it was a list but since this answer is literally what xnor submitted (in Haskell) I didn't think it was necessary. :) – Boomerang Feb 9 at 13:12

Perl, 24 + 4 = 28 bytes

$^+=$_/2 for@F;$_=$^~~@F

Requires -paX flags to run, prints 1 as True and nothing as False:

-X disables all warnings.

$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 7'
$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 8'
share|improve this answer
Inspiring one. Inspired this: $_=eval(y/ /+/r)/2~~@F (uses same command-line options). – manatwork Feb 9 at 11:33
@manatwork Interesting way to use tr :) – andlrc Feb 9 at 14:04
You could leave that -X out by specifying some Perl version [5.10 .. 5.18). (Smart match was introduced in 5.10 and experimental warnings were introduced in 5.18. Any version between those two will work fine with ~~ without -X.) – manatwork Feb 9 at 16:41

Jolf, 6 bytes

Try it here!

_hx    the input array
   ½ux  has half the sum of the array

This is xnor's awesome solution to the problem, but in Jolf.

share|improve this answer

Pylons, 8

Yet another implementation of xnor's algorithm.


How it works:

i    # Get command line input.
:A   # Initialize a constant A.
  s  # Set A to the sum of the stack.
2    # Push 2 to the stack.
A    # Push A to the stack.
/    # Divide A/2
_    # Check if the top of the stack is in the previous elements.
     # Print the stack on quit.
share|improve this answer

SpecBAS - 36 bytes

Uses xnors formula

1 INPUT a,b,c: ?(a+b+c)/2 IN [a,b,c]

outputs 1 if true and 0 if false

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.