# Write a program that makes 2 + 2 = 5 [closed]

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.

## closed as off-topic by DennisMar 23 '16 at 4:50

• This question does not appear to be about programming puzzles or code golf within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

## locked by DennisMar 23 '16 at 4:50

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

• This is question in book "1984" by George Orwelll. – bacchusbeale May 30 '14 at 12:23
• Why is this underhanded? Two plus two is five. – Geobits May 30 '14 at 16:23
• THERE! ARE! FOUR! LIGHTS! – Nick T May 30 '14 at 19:57
• @Geobits - I agree: 2+2=5 you can see it in this calculator. – MT0 May 30 '14 at 20:03
• echo "2+2=5"; – user3459110 May 31 '14 at 12:16

## Perl 5

Example 1

(2 != 3) ? $x = 2 + 2 :$x = 2 + 3;
print $x;  ? defines an lvalue and has higher precedence than assignment, so the code is equivalent to ((2 != 3) ? ($x = 2 + 2) : $x) = 2 + 3. Example 2 @a = ("one", "2");$x = length @a;
$x += length reverse @a; print$x;


Length is string length, not list length, and hence expects a scalar. Arrays in scalar mode return their length, so length @a = length "2" = 1. Reverse in scalar mode concatenates and reverses its input, so length reverse @a = length "2eno" = 4.

Example 3

print (2 + 3) - (2 + 3) + (2 + 2);


The first set of parentheses define the arguments to the builtin print; the remaining calculation is applied to the return value of print and discarded.

# 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)

# 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];

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.

• 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. – Hjulle Feb 25 '15 at 15:57

# 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 ;)

# 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.

# 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 >>>  • Sorry, But I do not have this behaviour at all ! – dieter Jan 5 '16 at 16:49 • 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. – cat Jan 5 '16 at 16:52 • It does not, indeed, work on Python 2, though I thought it did, sorry. – cat Jan 5 '16 at 16:54 • Proof? – cat Jan 5 '16 at 17:04 • More proof – cat Jan 5 '16 at 17:12 # 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. • This doesn't really count, IMHO, since you didn't include all the source code. – mbomb007 Oct 6 '15 at 21:26 • I know, It is kind of a cheat. – Liam Oct 6 '15 at 21:31 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

• Just use proper K&R definition style - sum(i,j) int i,j; { return i+j; } – ugoren Jan 19 '16 at 12:07
• What do the double braces even mean? i can has explanashun – cat Jan 19 '16 at 18:01
• @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... – aka.nice Jan 19 '16 at 23:54

# 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

• Nice answer :-) – cat Mar 4 '16 at 22:18

# 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]

## 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.

# 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.

## 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.

## 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

## 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...

# 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.

# Python

It's legit, I swear!

eval=len
print eval("2 + 2")


Ocaml

let p x f y = f x y + 1;;
print_int (p 2 (+) 2);;


# Apple Swift

extension Int {
}


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

# 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

# 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

# Java

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


output: 5

• Good idea, simple it is! – Timtech Feb 11 '15 at 11:59
• Not really underhanded, since the ++x looks questionable. – BobTheAwesome Mar 15 '15 at 0:00

# 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();
}


# ><>

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.

# 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.

# Lua:

setmetatable(_G, {
__newindex = function(t, i)
rawset(t, i, setmetatable({}, {
return 5
end
}))
end
})

a = 2
b = 2

print(a + b) -- 5


Try it

# 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).

# Hassium

Not the most creative but here goes:

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


Run code online

• Wow... two=2.5 – ev3commander Oct 29 '15 at 21:34

# 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?

## 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.