390
votes
\$\begingroup\$

Write a program that seemingly adds the numbers 2 and 2 and outputs 5. This is an underhanded contest.

Your program cannot output any errors. Watch out for memory holes! Input is optional.

Redefining 2+2 as 5 is not very creative! Don't doublethink it, try something else.

\$\endgroup\$
23
  • 48
    \$\begingroup\$ This is question in book "1984" by George Orwelll. \$\endgroup\$ Commented May 30, 2014 at 12:23
  • 97
    \$\begingroup\$ Why is this underhanded? Two plus two is five. \$\endgroup\$
    – Geobits
    Commented May 30, 2014 at 16:23
  • 79
    \$\begingroup\$ THERE! ARE! FOUR! LIGHTS! \$\endgroup\$
    – Nick T
    Commented May 30, 2014 at 19:57
  • 105
    \$\begingroup\$ @Geobits - I agree: 2+2=5 you can see it in this calculator. \$\endgroup\$
    – MT0
    Commented May 30, 2014 at 20:03
  • 47
    \$\begingroup\$ echo "2+2=5"; \$\endgroup\$ Commented May 31, 2014 at 12:16

156 Answers 156

2
votes
\$\begingroup\$

TI 30 Calculator

2nd ÷ +1

Examples

3+4 = 8

9*5 = 46

sqrt(16) = 5

The variable K gets appended to every executed calculation. So if K is set to +1, +1 is getting appended to every executed calculation. That means when you type 5+5 and press enter, the calculation gets to 5+5+1.

Note: You can make your calculator calculate normal again by doing a memory reset(2nd 0 2 or by using the reset button at the back of your calculator)

\$\endgroup\$
2
votes
\$\begingroup\$

Mathematica

The "simple" solution of just redefining 2+2 as 5:

> Unprotect[Plus];
> Hold[Plus[2, 2]] ^:= Hold[5]

> 2 + 2 // Hold // ReleaseHold
5

This was suprisingly difficult, because Mathematica keeps evaluating plus before any of my substitution got the chance to replace it.

There is also the alternative version on the same theme, redefining 4 to be equal to 5:

Unprotect[Integer];
head_[a___, 4, b___] ^:= head[a, 5, b]

Print[2+2]
Plot[x^2, {x,0,2+2}]

Note that the second example won't work* though, due to this code replacing the number 4 with 5 everywhere. This means that any internal Mathematica functions that happen to use the number 4 somewhere will get "interesting" behaviour. XD

*Well it almost works in this case, try replacing a smaller number instead, to get even more interesting results. I had the documentation page crash for me once.

\$\endgroup\$
1
  • \$\begingroup\$ I know that you were supposed to hide the fact, and that "just redefining 2+2=5 is not creative", but the fact that you can make it hold litteraly, even for internal Mathematica code made me submit this anyways. \$\endgroup\$
    – Hjulle
    Commented Feb 25, 2015 at 15:57
2
votes
\$\begingroup\$

MATLAB

fprintf('%c.%c',num2str(int8(num2str(sum(2,2)))))

Ok, so not quite 2+2, but it does look like it does the sum of 2 with 2 to make 5.0. Now I will leave you to ponder quite how it ends up being 5.0 given ASCII and all.

:)

Just in case you are trying to work out how 50+2 equals '50', you should probably look up the documentation of sum. All is not quite what it seems ;)

\$\endgroup\$
2
votes
\$\begingroup\$

Whitespace, (looks like C++)

I don't know if this qualifies, but I thought it was fun

raw paste data here.

online interpreter here.

#include<iostream>               

int main() {                
    std::cout<<2+2;
             

                    

    return  0;      



}

If you run it in C++ it prints

4

If you run in whitespace it prints

2+2=5
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I feel the urge to remove all the newlines, as I've done countless of times on newbie posts on SO. =P \$\endgroup\$ Commented Nov 8, 2015 at 12:59
2
votes
\$\begingroup\$

AppleScript

According to this answer on the Programmers SE site, the ¬ symbol is "negation", or "not". Therefore, by all reasoning, the following code should absolutely return 4.

if 2 + 2 ≠ 5 then ¬
    return 5
return 4

Because if 2 + 2 does not equal 5, then do not return 5, return 4.

Output:

5

In AppleScript, the ¬ character actually means "concatenate the next line onto this one". So it will actually execute return 5 if 2 + 2 ≠ 5.

\$\endgroup\$
2
votes
\$\begingroup\$

Python 3

An extremely lame one, inspired by this MATLAB answer.

>>> import sys
>>> sys.stdout.write("2+2= ")
2+2= 5

sys.stdout.write always slaps the number of written chars on the end of the bytestream. I don't know why, or how to make it stop, but useful indeed.

Proof it Works On My Machine™

Here's more proof it works.

Also:

$ python3.4
Python 3.4.3+ (default, Oct 14 2015, 16:03:50) 
[GCC 5.2.1 20151010] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.write("hello")
hello5
>>> 
\$\endgroup\$
6
  • \$\begingroup\$ Sorry, But I do not have this behaviour at all ! \$\endgroup\$
    – dieter
    Commented Jan 5, 2016 at 16:49
  • \$\begingroup\$ Works On My Machine™. Ideone doesn't have it either, but my default installation of Python 3.5 on Ubuntu 15.10 has this behaviour. \$\endgroup\$
    – cat
    Commented Jan 5, 2016 at 16:52
  • \$\begingroup\$ It does not, indeed, work on Python 2, though I thought it did, sorry. \$\endgroup\$
    – cat
    Commented Jan 5, 2016 at 16:54
  • \$\begingroup\$ Proof? \$\endgroup\$
    – cat
    Commented Jan 5, 2016 at 17:04
  • \$\begingroup\$ More proof \$\endgroup\$
    – cat
    Commented Jan 5, 2016 at 17:12
2
votes
\$\begingroup\$

C++

This is similar to some other methods, but I think slightly sneakier because at a glance it looks extremely straightforward.

   #include "iostream.h"
    int main()
    {   
        int TWO = 2;
        int F0UR = 4;

        std::cout<< TWO << " + " << TWO << " = " << FOUR;
        return 0;
    }

This prints to the console:

2 + 2 = 5

The trick here is that "iostream.h" is actually a local file containing

 
 #include < iostream >
 #define FOUR 5 
 
Here the macro FOUR is defined to be 5. In the code body, the integer is F0UR, using a zero instead of the letter "O" as the second character. Depending on the font used, this difference can be very difficult to detect.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ This doesn't really count, IMHO, since you didn't include all the source code. \$\endgroup\$
    – mbomb007
    Commented Oct 6, 2015 at 21:26
  • \$\begingroup\$ I know, It is kind of a cheat. \$\endgroup\$
    – Liam
    Commented Oct 6, 2015 at 21:31
2
votes
\$\begingroup\$

C

#include "stdio.h"

int main() {{
     int i,j,s,d;
     /* auto test */
     for(i=1;i<=2;i++)
     {{
         j=i;
         d=diff(i,j);
         s=sum(j,j);
         if( d != 0 || s != 2*i ) abort();
     }}
     /* redo it out of loop to be really sure */
     d=diff(i,j);
     s=sum(j,j);
     printf("%d-%d=%d\n",i,j,d);
     printf("%d+%d=%d\n",j,j,s);
     return 0;
}}

diff(a,b) {{ int i=a,j=b; return i-j; }}
sum(i,j) {{ int i,j; return i+j; }}

It outputs:

$ clang test1.c 2>/dev/null
$ ./a.out
3-2=1
2+2=5

This is my first program in C, could you help me?

NOTE

I came to totally distrust the integer arithmetic unit, so I modified my functions with the aim of using the floating point unit instead:

copy(int*a,float*b){*b=*a;}
diff(a,b) { float i,j; copy(&a,&i); copy(&b,&j); return i-j; }
sum(i,j) { float a,b; copy(&a,&i); copy(&b,&j); return a+b; }

but no luck so far, the floating point arithmetic is equally broken!

$ clang test2.c 2>/dev/null
$ ./a.out
3-2=1
2+2=5
\$\endgroup\$
3
  • \$\begingroup\$ Just use proper K&R definition style - sum(i,j) int i,j; { return i+j; } \$\endgroup\$
    – ugoren
    Commented Jan 19, 2016 at 12:07
  • \$\begingroup\$ What do the double braces even mean? i can has explanashun \$\endgroup\$
    – cat
    Commented Jan 19, 2016 at 18:01
  • \$\begingroup\$ @cat an extra pair of braces just delineate variable scoping in this case. This scoping was necessary to obtain UB with temp variable i,j shadowing sum() parameters i,j. Otherwise c compilers (gcc, clang, ...) see the two declarations (implicit int parameters and temp) as conflicting because at same scope... \$\endgroup\$
    – aka.nice
    Commented Jan 19, 2016 at 23:54
2
votes
\$\begingroup\$

C++

Didn't check all the answers but no C or C++ answers to date use this approach.

int main()
{
    // we can do this by adding an int and a float; takes advantage of an FPU bug
    char *sum = "2 + 2.0";
    int total = 0;
    for (int i = 0; sum[i]; i++)
        total = (total+sum[i]) & strlen(sum); // AND op prevents buffer overflow
    printf("%s = %d\n", sum,total);
    return 0;
}

Output: 2 + 2.0 = 5

\$\endgroup\$
1
  • \$\begingroup\$ Nice answer :-) \$\endgroup\$
    – cat
    Commented Mar 4, 2016 at 22:18
1
vote
\$\begingroup\$

GolfScript

2,~2,~],

What the program does:

2, generates the array [0 1]
~ dumps the array onto the stack
] gathers the items on the stack into an array
, gets the array length

If you delete the ], part, the program prints 0101 - 4 characters. But if you run the full program, it prints 5.

Explanation:

At the beginning of the program, the standard input is pushed on the stack as a string. If there is no input, an empty string is still pushed. That string gets collected into the array too, so the array will actually be ["" 0 1 0 1]

\$\endgroup\$
1
vote
\$\begingroup\$

Java

Using reflection:

import java.lang.reflect.Field;

public class TwoPlusTwoTest {

    public static void main(String[] args) throws Exception {
        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        field.set("\u0032", new char[] {51});
        int twoPlusTwo = Integer.parseInt("2") + 2;
        System.out.println(twoPlusTwo); //5
            /**** Another ***/ 
        field.set("\u0032\u0020\u002B\u0020\u0032", new char[] {'\u0035'});
        System.out.println("2 + 2".equals("5"));
    }
}

Reflectively accesses the internal array field, named value, that String is backed by, and sets its value to 3. Because all constant Strings are interned and are accessed from the pool of constant Strings, this results in the String literal "2" actually refer to a char array with value {3}.

JavaScript

Using an overloaded valueOf:

String.prototype.valueOf = function () {
  return 3;
}
Array.prototype.valueOf = function () {
  return 3;
}

console.log(2 + [2]); //5
console.log(2 + new String(2)); //5

Array.prototype.valueOf = function () {
  return 2.5;
}

console.log([2] + [2]); //5

The valueOf method is called by the engine when an object is used in a numeric context.

\$\endgroup\$
1
vote
\$\begingroup\$

JavaScript

This is meant to be run a browser's development console. It is horrible code.

+function(p){
    var o=p.toString;
    p.toString=function(){
        return (this-4)?o.call(this):'5'
    }
}(Number.prototype);

(2+2).toString()

Edit: nderscore hid this technique way better, and you should check it out. The only upside to my code is that 4 is the only value affected.

\$\endgroup\$
1
vote
\$\begingroup\$

Factor

IN: scratchpad << "\x32" create-in 5/2 define-constant >>

IN: scratchpad 2 2 + .
5

This exploits the parser, particularly the parse-datum word which searches a token for an already defined word, then if not found, tries to parse it as a number. Usually, we disallow words from being defined by a number using scan-word-name, but that doesn't prevent you from doing it yourself as in the example above.

\$\endgroup\$
1
vote
\$\begingroup\$

Befunge93

2+2=? The answer is printed here: @.+!!

Try it online.

Explanation

The = functions as a mirror for the instruction pointer (in Befunge93), so the phrase itself is not "executed". The pointer goes this way:

2 - put 2 on the stack
+ - add 2 to 0 (i.e. do essentially nothing)
2 - put another 2
= - instruction not defined: inverse the direction of the pointer
2 - put another 2
+ - add 2 to 2 - put 4
2 - put 2. Wrap to the end of the line
! - logical negation for 2: put 0
! - logical negation for 0: put 1
+ - add 1 to 4 - put 5
. - print 5
@ - exit

\$\endgroup\$
1
vote
\$\begingroup\$

Javascript

Not going to win any prizes with this one, but I like it.

console.log(
  // +~~~~~~~~~~~~~~~~+ //
  // |     __  _____  | //
  // |  __|  ||   __| | //
  // | |  |  ||__   | | //
  // | |_____||_____| | //
  // +~~~~~~~~~~~~~~~~+ //
  "" -0-~~~ (2+2) -~~0- ""
  // +~~~~~~~~~~~~~~~~+ //
);

Plus it's been ages since I've seen any ASCII art...

\$\endgroup\$
1
vote
\$\begingroup\$

Befunge 98

"2+2".@

Remember that . is the way we print a number in Befunge.

Really not that interesting. First of all, it's pretty obvious that "2+2" is a string, not a number. And strings in Befunge simply push the elements onto the stack one at a time. So this clearly means that there is an ENQ character (ASCII 5) hiding after the last 2.

\$\endgroup\$
1
vote
\$\begingroup\$

Python

It's legit, I swear!

eval=len
print eval("2 + 2")
\$\endgroup\$
1
vote
\$\begingroup\$

Ocaml

let p x f y = f x y + 1;;
print_int (p 2 (+) 2);;
\$\endgroup\$
1
vote
\$\begingroup\$

Apple Swift

extension Int {
     var add2:Int {return 5}
}
println(2.add2);

Maybe not the most clever one, but I like how it would look totally harmless if the extension was hidden in some library/header.

\$\endgroup\$
1
vote
\$\begingroup\$

JavaScript

var a = 2;
var b = 0.1 + 0.2; // 0.3
b = Math.ceil(b * 10.0); // 3
b--; // 2
console.log(a + b);

Output: 5

\$\endgroup\$
1
vote
\$\begingroup\$

T-SQL

--Set up a table to sum from
CREATE TABLE A (
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    VAL INT NOT NULL DEFAULT 1
    );

--Insert sum values to sum
BEGIN TRANSACTION A
INSERT INTO A (VAL) Values (2)
SAVE TRANSACTION A

BEGIN TRANSACTION B
    INSERT INTO A (VAL) Values (1)
    SAVE TRANSACTION B

    BEGIN TRANSACTION C
        INSERT INTO A (VAL) Values (4)
        SAVE TRANSACTION C
    ROLLBACK TRANSACTION C -- Get rid of last insert
ROLLBACK TRANSACTION B -- Get rid of the previous insert

INSERT INTO A (VAL) Values (2) -- Make sure we have another 2 in the table
SAVE TRANSACTION A 
COMMIT TRANSACTION A  -- Commit the transaction
GO 

-- Sum the table and format it nicely for the output using CONCAT
-- There is only two values so ordering for the first and last val not required
SELECT TOP 1 CONCAT(
    FIRST_VALUE(VAL) OVER (ORDER BY (SELECT NULL)),
    ' + ',
    LAST_VALUE(VAL) OVER (ORDER BY (SELECT NULL)),
    ' = ',
     SUM(VAL) OVER (ORDER BY (SELECT NULL))) AS VAL
FROM A;
/*
Result is output "2 + 2 = 5"
*/
DROP TABLE A;

Probably not that underhanded,but trying to take advantage over confusing nested transactions. Rollbacks only go back to the save point, not the beginning of the transaction.
ROLLBACK TRANSACTION C doesn't affect the table
ROLLBACK TRANSACTION B will roll back to SAVE TRANSACTION B removing the VAL 4 but not 1
As a matter of interest, if the (SELECT NULL) in the OVER clause is replaced with ID in the query the result ends up being 2 + 2 = 2

\$\endgroup\$
1
vote
\$\begingroup\$

Java

How about this,

public class Simple 
{
    public static void main(String[] args) 
    {
        int x = 2;
        x += ++x;
        System.out.println(x);
    }
}

output: 5

\$\endgroup\$
2
  • \$\begingroup\$ Good idea, simple it is! \$\endgroup\$
    – Timtech
    Commented Feb 11, 2015 at 11:59
  • \$\begingroup\$ Not really underhanded, since the ++x looks questionable. \$\endgroup\$ Commented Mar 15, 2015 at 0:00
1
vote
\$\begingroup\$

C++

This uses some new techniques and some that have been already posted in conjunction with some new ones that have not.

METHOD 1

Using #define to override the primitive type with a custom type, and overriding the cast operator of the custom type to offset the value. Requires an intermediate variable of the custom type (scroll right). Works with cout, but printf avoids the cast operator and so it still returns 4. The printf line compiles in GCC 4.8, gives a warning in Clang with -std=c++11, and gives an error in Clang with -std=c++98.

                                                                                                                                                                                                                                                            struct Double { double x; Double(int x_) : x(x_) {} Double operator+(const Double& b) { return Double(x + b.x); } operator double() const { return x + 1; } };
#include <iostream>
#include <stdio.h>
                                                                                                                                                                                                                                                            #define double Double
int main() {
    double _2 = 2;
    std::cout << _2 + _2 << std::endl;
    printf("%f\n", _2 + _2);
}

METHOD 2

Using #define to override the primitive type with a custom type, and overriding the plus operator of the custom type. Requires an intermediate variable of a custom type. This method works with printf as well.

                                                                                                                                                                                                                                                            struct Double { double x; Double(int x_) : x(x_) {} double operator+(const Double& b) { return x + b.x + 1; } };
#include <iostream>
#include <stdio.h>
                                                                                                                                                                                                                                                            #define double Double
int main() {
    double _2 = 2;
    std::cout << _2 + _2 << std::endl;
    printf("%f\n", _2 + _2);
}

METHOD 3

Overshadowing namespaces. Works with any literal numbers, but only within the provided namespace.

#include <stdio.h>
#include <iostream>
                                                                                                                                                                                                                                                            namespace foo { namespace std { struct cout_ { ::std::ostream& operator<<(int x) { return ::std::cout << x+1; } } cout; using ::std::endl; } void printf(const char*, int) { ::printf("5\n"); } }
namespace foo {
void bar() {
    std::cout << 2 + 2 << std::endl;
    printf("%d\n", 2 + 2);
}
}

int main() { 
    foo::bar(); 
}
\$\endgroup\$
1
vote
\$\begingroup\$

><>

02+02=05?v"Not 5"5[r]ooooo;
         >"5"o;

Outputs "5". How it works:

In ><>, each operation is one character, so if you were really finding 2 + 2, you would write 22+, for pushing 2, pushing 2 again and adding. The ? instruction does the following instruction only if a value popped off the stack is non-zero. The last value I push before using it is a 5, not a 0, so the branch to print "5" is executed. The stack at the end is [2 0 0]; 0 + 2 and 0 = 2 (booleans are 1 and 0), as well as the other 0 pushed.

\$\endgroup\$
1
vote
\$\begingroup\$

C++

#include <iostream>
#define TWO false ? 5 : 2
int main() {
    std::cout<< TWO << "+" << TWO << "=" << TWO+TWO;
    return 0;
}

Output:

2+2=5

How it works:

(false ? 5 : 2 + false ? 5 : 2) is the same as (false ? 5 : (2 + false ? 5 : 2)). (2 + false) is true.

\$\endgroup\$
1
vote
\$\begingroup\$

C

I haven't seen, among top three C solutions, the most obvious way to go. So, here it is.

#include <stdio.h>

#define a a=5,b

int main(void)
{
    int a = 2 + 2;
    printf("%d\n", a);
    return 0;
}

Of course this solution doesn't hide the trick to anyone with a eye. Moreover, one can argue that the extra argument in the printf may cause problems (even at compile time, depending on how you compile).

\$\endgroup\$
1
vote
\$\begingroup\$

Hassium

Not the most creative but here goes:

func main () {
    two = 2.5;
    five = two + two;
    println("two + two = " + five);
}

Run code online

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Wow... two=2.5 \$\endgroup\$
    – user46167
    Commented Oct 29, 2015 at 21:34
1
vote
\$\begingroup\$

Python 2

Here's another python one.

import sys

class Stdout(object):
    def __init__(self, target):
        self.target = target    
    def write(self, string):
        self.target.write("5")
sys.stdout = Stdout(sys.stdout)

print 2 + 2

This overwrites the stdout with a class that always returns 5. Pretty clever, eh?

\$\endgroup\$
1
vote
\$\begingroup\$

Python 2 (and maybe 3?)

import sys
def gettwo():
    global x,y
    y-=1                                  #Reduce global y back to 2
    x=2                                   #Set global x to 2
    sys.stdout.write("%d+%d="%(y,x))      #show the values we're going to be adding
    return x

y=3                                       #we'll reduce it to two in the gettwo() function
y+=gettwo()                               #y is now 2 and gets incremented by the 2 
                                          #returned from the function
sys.stdout.write(str(y))

Run this and it outputs:

2+2=5

I had a bug based on this crop up recently and it took me several minutes to figure out why it was happening. If you've never seen it before, it could be quite frustrating.

Python's operator assignment does things in a particular order. a+=b() is not the same as a=a+b(). It's more like =a;a=+b(). So, in this code the y-=1 ends up having no effect, as it is immediately overwritten by the remembered value of y when the function returns.

\$\endgroup\$
1
vote
\$\begingroup\$

Mouse-2002

Mouse is a language about mathematical equation solving.

Every program starts with a letter declaring its name, here I've chosen a.

The ! exclamation point operator is not, as one might initially think, factorial; instead it "asserts" the immediately preceding equation and prints the equation's simpler side if the equation is true, in this case 5.

This is a very simple way to show that 2 + 2 is 5.

a 2 + 2 = 5 !
> 5

Actually, Mouse is a very minimal stack-based language that uses Reverse Polish Notation (Postfix Notation), not infix.
The program a 2 + 2 = 5 ! actually pushes a's address (always 0), then adds 2 to that, then pushes 2 and pushes 1 if 0 + 2 is equal to 2 (which of course it is). Then, 5 is put on the top of the stack and the ! prints the top of the stack: magic.

\$\endgroup\$

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