391
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\$ May 30, 2014 at 12:23
  • 97
    \$\begingroup\$ Why is this underhanded? Two plus two is five. \$\endgroup\$
    – Geobits
    May 30, 2014 at 16:23
  • 79
    \$\begingroup\$ THERE! ARE! FOUR! LIGHTS! \$\endgroup\$
    – Nick T
    May 30, 2014 at 19:57
  • 105
    \$\begingroup\$ @Geobits - I agree: 2+2=5 you can see it in this calculator. \$\endgroup\$
    – MT0
    May 30, 2014 at 20:03
  • 47
    \$\begingroup\$ echo "2+2=5"; \$\endgroup\$ May 31, 2014 at 12:16

156 Answers 156

1
vote
\$\begingroup\$

Python 3

>>> import ctypes
>>> ctypes.cast(id(4),ctypes.POINTER(ctypes.c_int))[6]=5
>>> print(2 + 2)
5

You could do the same thing in a tuple or something if you didn't want it to be as obvious:

>>> import ctypes
>>> a = (-1, 2, 3)
>>> ctypes.cast(id(sum(a)),ctypes.POINTER(ctypes.c_int))[6]=5
>>> print(2 + 2)
5

Or just obfuscate it completely:

>>> from ctypes import*
>>> cast(id((8).bit_length()),POINTER(c_int))[6]=5
>>> print(2 + 2)
5

Unlike the other Python answer, this doesn't cause a segmentation fault (at least, for me).


Note (1): This will always show 5 as being the result of any of the following (and infinitely more)

  • 2 * 2
  • 5 - 1
  • -7 + 11

Note (2): It will also cause mishaps with division and such operations

  • 76 / 4 will result in 15.2 (which is actually the result of 76 / 5)
  • 4 * 9 will result in 45
  • range(4) will result in a range(0, 5)

Note (3): An OSError will be thrown when the result of a division or exponential expression is passed

  • 76 / 19
  • pow(3, 4)
  • 1 / 4

The answer will be returned but an OSError will also be thrown. Here's an example:

>>> print(1 / 4)
0.2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: raw write() returned invalid length 5 (should have been between 0 and 4)
0.2

This is not always the case, but more often than not, that is the result. The flip side would be this:

>>> print(1 / 4)
4.0
0.2
\$\endgroup\$
3
  • \$\begingroup\$ In Python 2, index the cast with 4, not 6. \$\endgroup\$
    – Zach Gates
    Jan 5, 2016 at 14:43
  • 1
    \$\begingroup\$ Ooh, I like this. I'm gonna use this in production, for obfuscation's sake! \$\endgroup\$
    – cat
    Jan 5, 2016 at 16:33
  • \$\begingroup\$ Interestingly, print(ctypes.cast(id(4),ctypes.POINTER(ctypes.c_int))[6]) does cause a segfault. \$\endgroup\$
    – cat
    Jan 5, 2016 at 16:35
1
vote
\$\begingroup\$

Retina

<empty>
2+2=?
.

Try it online!

Explanation

<empty>\n2+2=4 essentially passes the "string" 2+2=4 to the next regex. . outputs the number of matches (chars in this case), which is 5.

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

CJam

X(2+2)+0;

Doesn't look like CJam? Think again.

Explanation

X(        e# push (X=1) decremented to stack [0]
  2       e# push 2 to stack                 [0 2]
   +      e# add                             [2]
    2)    e# push 2 incremented to stack     [2 3]
      +   e# add                             [5]
       0  e# push 0                          [5 0]
        ; e# pop and discard                 [5]
          e# implicit stack output
\$\endgroup\$
1
vote
\$\begingroup\$

PowerShell

$c=2                                                   # Set variable = 2
Write-Host ("$c + $c = " + $(2+($c++,$c--)[$c-eq2]))   # Perform the addition and output
Write-Host ("c = $c")                                  # Show that $c is still = 2

Output:

PS C:\Tools\Scripts\golfing> .\2-plus-2.ps1
2 + 2 = 5
c = 2

What the deuce?

Hint 1:

First, understand that the code (a, b)[c] (replacing a,b,c for values/variables) is a pseudo-ternary in PowerShell, where the dynamic array (a, b) is indexed into based on the value c.

Hint 2:

Next, understand that $true = 1 and $false = 0 and that arrays are zero-indexed. Thus, depending upon whether $c-eq2 ("$c is equal to 2") is True or False, we'll choose either the second or first value, respectively, and add that on to the 2.

Hint 3:

The dynamic array gets calculated before indexing.

Explanation:

The increment and decrement don't get evaluated twice. Instead, they're evaluated before the rest of the expression. Since we're creating a dynamic array, the first element of the array is processed as $c and saved as 2, and then the post-increment happens and sets $c=$c+1=3. The second element is processed as $c and saved as 3 (since $c was just set to 3), and then post-decremented back to 2. This makes our array (2,3). We index into that with $c-eq2 ... well, $c is now 2 again, so that evaluates to $true, or 1, and so selects the second element of the array, 3. Thus 2+3=5. And, since $c was decremented back down, we get the bonus of being able to output c = 2 still.

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

Swift

Swift allows for custom operators, this one still lets any other two numbers be added as you'd expect but if both arguments are 2 it will return 5.

func +(l:Int, r:Int) -> Int {
    var a = -r - l
    if l == 2 && r == 2 {--a}
    return -a 
}

print(2+2)
\$\endgroup\$
0
votes
\$\begingroup\$

F#

let plus a b =
    match (a, b) with
    | (2, 2) -> 5
    | _ -> a + b
\$\endgroup\$
0
votes
\$\begingroup\$

Scheme (R7RS/R6RS)

#!r7rs            ; or #!r6rs
(import (scheme)) ; or (import (rnrs))

(define (dec x)
  (- x l))

(define (inc x)
  (+ x 1))
    
(define (peano+ a b)
  (if (>= a 1)
      (peano+ (dec a) (inc b))
      b))

(define l 1/2)
(define i 3/2)
(define f 5/2)
(define e 87/32)

(display (peano+ 2 2))
(newline)

How it works:

In the dec procedure i reduce by lower case L, which is a free variable. I define it lower down to be 1/2.(an exact number in Scheme) So my peano arithemtic procedure adds 1 to b but reduces a by 1/2 and since my base case does not stop at zero but everything below 1 (peano+ 2 2) ends up being 5.

\$\endgroup\$
0
votes
\$\begingroup\$

C

Is this too obvious?

#include <stdio.h>
int main()
{
int a=2,b=2,i=0;
int n=a+b;
for(;i<=n;++i){}
printf("%d\n",i);
getchar();
return 0;
}

JavaScript

alert("2 + 2".length);
\$\endgroup\$
2
  • 1
    \$\begingroup\$ It's not very well hidden to me... \$\endgroup\$
    – user12205
    May 31, 2014 at 23:17
  • 1
    \$\begingroup\$ Yeah, too obvious. C is capable of being far more cryptic. \$\endgroup\$
    – ClickRick
    Jun 1, 2014 at 14:22
0
votes
\$\begingroup\$

Clojure

(let [+a clojure.core/+]
  (intern 'clojure.core '+ (fn [& args] (if (= [2 2] args) 5 (apply +a args)))))
\$\endgroup\$
0
votes
\$\begingroup\$

Java using unicode - this trick will probably work exactly the same in many other languages

For simplicity I will post 2 programs: The first one generates the second. The second one does the evil 2+2=5 but will be hard to read without the first one for context.

The generator:

import java . io . * ;

class main
{
    public static void main ( String [ ] args ) throws Exception
    {
    Writer writer = new FileWriter ( "stuff.java" ) ;
    writer . append ( "class stuff\n{\n\tpublic static void main ( String [ ] args )\n\t{\n\t\tint a\u00082=2; \n\t\tint b\u00082=3;\n\t\tSystem.out.println( a\u00082 + b\u00082  );\n\t}\n}" ) ;
    writer . close ( ) ;
    }
}

The evil program. It appears as below on my console.

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

It outputs "5".

The trick:

I used control character for backspace \u0008 in the variable names. So my variable names are really "a backspace 2" and "b backspace 2" which are printed out on my console "2" and "2" respectively. When I examine the source code in my editor, they appear as "a^H2" and "b^H2".

\$\endgroup\$
0
votes
\$\begingroup\$

Python 2

Yeah, not very original, but hey.

class int(int):__add__=lambda *a:5
print int(raw_input("Number? ")) + int(raw_input("Number? "))

int is still perfectly normal, except all additions return 5. Doesn't affect literals.

\$\endgroup\$
0
votes
\$\begingroup\$

template metaprogramming

#include <iostream>
#include <utility>
#include <type_traits>

enum class values {
  zero = 7,
  one = 3,
  two = 1,
  three = -7,
  four = 2,
  five = 4,
};

template<class T, T... ts> struct list {typedef list type;};
template<unsigned max, unsigned... ts> struct make_indexes:make_indexes<max-1, max-1, ts...>{};
template<unsigned... ts> struct make_indexes<0, ts...>:list<unsigned, ts...> {};
template<unsigned max> using make_indexes_t=typename make_indexes<max>::type;

template<class list> struct length_of;
template<class T, T... ts> struct length_of<list<T, ts...>>:std::integral_constant<unsigned, sizeof...(ts)> {};

template<class T, T t, class list> struct index_of;
template<class T, T t, T t0, T...ts> struct index_of<T, t, list<T, t0, ts...>>:
  std::integral_constant< unsigned, index_of<T, t, list<T, ts...>>::value+1 >
{};
template<class T, T t, T...ts> struct index_of<T, t, list<T, t, ts...>>:
  std::integral_constant< unsigned, 1 >
{};
template<class T, unsigned N, class list> struct value_at;
template<class T, unsigned N, T t0, T... ts> struct value_at<T, N, list<T, t0, ts...>>:value_at<T, N-1, list<T, ts...>> {};
template<class T, T t0, T... ts> struct value_at<T, 0, list<T, t0, ts...>>:std::integral_constant<T, t0> {};

template<class T> struct summable {};
template<> struct summable<values> {
  typedef values T;
  typedef list<T, T::zero, T::one, T::two, T::three, T::four, T::five> list_type;
  template<T t>
  using index = index_of< T, t, list_type >;
  template<unsigned N>
  using value = value_at< T, N, list_type >;
};

template<class T, template<T>class indexer>
unsigned index( T t, list<T> ) {
  return -1;
}

template<class T, template<T>class indexer, T t0, T... ts>
unsigned index( T t, list<T, t0, ts...> ) {
  if (t==t0)
    return indexer<t0>::value;
  else
    return index<T, indexer>( t, list<T, ts...>{} );
}

template<class T, template<unsigned>class valuer>
T value( unsigned N, list<unsigned> ) {
  return static_cast<T>(-1);
}
template<class T, template<unsigned>class valuer, unsigned M0, unsigned... Ms>
T value( unsigned N, list<unsigned, M0, Ms...> ) {
  if (N-1==M0)
    return valuer<M0>::value;
  else
    return value<T, valuer>( N, list<unsigned, Ms...>{} );
}


template<typename T>
T sum( T lhs, T rhs ) {
  typedef typename summable<T>::list_type list_type;
  return value<T, summable<T>::template value>( index<T, summable<T>::template index>(lhs, list_type{})+index<values, summable<T>::template index>(rhs, list_type{}), make_indexes_t<length_of<list_type>::value>{} );
}

template<typename T, typename=typename summable<T>::list_type >
T operator+( T lhs, T rhs ) {
  return sum( lhs, rhs );
}

all of which leads to this main:

int main() {
  auto two = values::two;
  auto five = values::five;
  std::cout << (two+two==five) << "\n";
  return 0;
}

which prints 1.

Mainly a game of misdirection. The enum values are not used anywhere in the code (so long as they are distinct). The template metaprogramming builds an entire infrastructure allowing positional-based addition of a list of values (regardless of their literal values) at compile time, and then a magic-switch construct converts this compile-time support to run-time support with sensible error messages. The indexes of elements are 1-based (so the first element is 1), and the reverse map does this properly. The only part where it fails is when we add together two elements: we add together their 1-based index. As two is in the 3rd position, we get the 6th position result, which is five.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Are you sure there's not a shorter template strategy you could use? \$\endgroup\$
    – Pharap
    Jun 4, 2014 at 19:00
  • \$\begingroup\$ @Pharap I am certain there are many, many shorter template strategies I could have used! \$\endgroup\$
    – Yakk
    Jun 4, 2014 at 19:12
0
votes
\$\begingroup\$

C++11

Kinda cheap, but whatever...

#include <iostream>

class mynumber
{
public:
    unsigned long long n;
    unsigned long long operator+(mynumber rhs)
    {
        return n + rhs.n + 1;
    }
};

constexpr mynumber operator"" _ (unsigned long long n)
{
    return mynumber{n};
}

int main()
{
    std::cout << "2 + 2 = " << 2_ + 2_;
}
\$\endgroup\$
0
votes
\$\begingroup\$

C/C++ cmath

The curse of the numbers below 473 and above 474...

#include <iostream>
#include <cmath>
#include <stdlib.h>

const int MaxA=5;
const int MaxB=5;
int A[] = {469,  470 , 471 ,472, 473};
int B[] = {474,  475 , 476 ,477, 478};

int Check_And_Calculate(int d, int c1,int c2){
 // It does a check on c1 and c2 and return the value of `-cubic root of c1^3` // 
 if (c1>c2) std::cerr << "# "<< c1 << " is **BIGGER** then " << c2 << std::endl;
     else   std::cerr << "# "<< c1 << " is NOT bigger then " << c2 << std::endl;
 return  -cbrt(c1*c1*c1)   ;
}

int main()
{
  int a=2, b=2;
  srand48(time(NULL));               // Random seed: Randomize the seed...
  int ValueA=A[int(MaxA*drand48())]; // It Extracts one random element from A
  int ValueB=B[int(MaxB*drand48())]; // It Extracts one random element from B

  a=a+Check_And_Calculate(a,ValueA,ValueB)+ValueB;  // It adds B subtracts A
  b=b+Check_And_Calculate(b,ValueB,ValueA)+ValueA;  // It adds A subtracts B

  std::cout << "2+2=" << a+b << "\n";
  return 0 ;
}

Output

# 473 is NOT bigger then 476
# 476 is **BIGGER** then 473 
2+2=5

Explanation

We could say that the A group are the good ones (at least this time) and the B ones are the Bad Guys. (They have a lot of friend! see below).
For some numbers we can observe the following behaviour for the cubic square root function, cbrt(x) and for the power one pow(x,1./3.)
3^3=27
pow(27.,1./3/)= 3.0000000000000004
15^3=3375
pow(3375.,1./3/)=14.999999999999998

When it is returned by an integer function it is made an automatic cast:
3.0000000000000004 becomes 3
14.999999999999998 becomes 14
So at the end it seems it was not a curse but only a problem of bad casting...

Notes:

The comparison in the function is needed (or some other code at least) else when it is compiled with -O1,-O2,-O3 option the code is substituted and the effect disappears.

The Wild Bunch
int MaxB=147;
B[]={15,27,30,37,54,60,67,71,74,108,117,119,120,134,139,142,148,161,191,205,216,221,225,229,234,237,238,239,240,253,268,278,284,296,315,322,382,407,410,417,431,432,439,441,442,443,445,449,450,458,465,468,474,475,476,477,478,480,481,487,501,505,506,527,536,551,556,563,567,568,592,593,630,641,644,743,751,764,775,791,801,814,820,829,834,857,861,862,864,867,878,879,882,884,886,890,898,900,903,905,907,915,916,923,925,927,929,930,936,947,948,950,952,954,955,956,957,960,962,967,971,974,975,983,1002,1010,1012,1017,1021,1027,1031,1054,1072,1102,1112,1126,1133,1134,1136,1181,1184,1186,1213,1249,1260,1279,1282}

\$\endgroup\$
1
  • \$\begingroup\$ Hi Hastur, I tried it out on OS X as you asked. It compiles fine, but gives 2+2=4! Something is incorrect about your incorrect math. :) \$\endgroup\$ Jun 10, 2014 at 14:35
0
votes
\$\begingroup\$

A C++ template metaprogram:

#include <iostream>
#include <conio.h>

using namespace std;

template <int a, int b>
int add()
{
    return a + b;
}
template<>
int add<2, 2>()
{
    return 5;
}

int main()
{
    cout << "2 + 3 = " << add<2, 3>() << endl;
    cout << "2 + 2 = " << add<2, 2>();
    _getch();
}

The output will be:

2 + 3 = 5
2 + 2 = 5
\$\endgroup\$
0
votes
\$\begingroup\$

C

Tested on OS X Mavericks with /usr/bin/gcc (i.e. clang). Results will likely vary on different machines, compilers, libraries, etc...

main() {
    char buf[80];

    char fmt[] = "2 + 2 = \
    /* long long n requires 'll' prefix *\
    %lln";

    /* use a long long to avoid overflow in computing 2+2 */
    /* (that's typically how we get the wrong answer.) */
    long long n = 2;

    /* print out n + n, that is: 2 + 2 */
    sprintf(buf, fmt, &n + n);

    puts(buf);
}

Update: added Linux version:

#include <stdio.h>
main() {
    long long n = 2;
    char buf[80];
    sprintf(buf, "2 + 2 =\
        /* 'll' prefix for long long *\
        %lln\n", &n + n);
    puts(buf);
}

Output:

$ ./five 
2 + 2 = 5

Explanation:

The printf format %n is not a format specifier, it instead instructs printf to store the number of characters written so far in the int * argument parameter. The ll prefix tells printf that the argument is a long long pointer, thus 64-bits. The first comment "inline" in the string, is not actually a comment, but part of the format string, giving the entire format string enough padding that the %lln occurs at the 53 index---the ASCII code for '5'. The sprintf argument of '&n + n' points 8 characters into the format string. So sprintf writes the 64-bit value 53 to that offset in the buffer. On a little-endian intel that corresponds to the bytes {53, 0, 0, 0, 0, 0, 0, 0}, thus nicely zero-terminating our string so the "inline" comment is not also output with the puts. I ran out of ideas for obfuscating it further, the line continuation comment seemed a little better than alternatives I tried, but if anyone has suggestions, they're very welcome!

\$\endgroup\$
2
  • \$\begingroup\$ This is the output I have on 4.8.2-19ubuntu1 2 + 2 = /* long long n requires 'll' prefix * . Can you add the library you include and the compiling options? With -O1 -O2 -O3 it gives me *** %n in writable segment detected ***... core dump. Can you tell me if in your computer it functions my code?. Thanks \$\endgroup\$
    – Hastur
    Jun 9, 2014 at 9:40
  • \$\begingroup\$ Thanks Hastur, I've updated my "solution" to include a linux version. Give it a shot. You should be able to compile it with just gcc -o five five.c. Just ignore any warnings, and don't add optimization flags. \$\endgroup\$ Jun 10, 2014 at 14:29
0
votes
\$\begingroup\$

GolfScript

5:4;'"#{'"#{STDIN.gets}"-1<'}"'++~~

The program gets a line from STDIN, then evaluates it. Example run:

Input:

2 + 2

Output:

5

How it works:

The 5:4; assigns the value of 5 to 4. But simply computing 2 2+ would result in 4. So the rest of the program reads a line from STDIN, removes the trailing newline, then evaluates "#{line from stdin}" to let ruby add the numbers. So an input of 2 + 2 leaves a "4" on the stack. Lastly, we evaluate it again, resulting in 5.

\$\endgroup\$
0
votes
\$\begingroup\$

JavaScript

var two = {
    valueOf:function() { return 2; }, //two = 2
    toString:function() { return '3-1=2' } //interesting fact
}
var stringToPrint = '';
stringToPrint += "2 + 2 = " + two + two;
alert(stringToPrint);
alert("Oops, string concatenation instead of addition");
stringToPrint = '';
stringToPrint += "2 + 2 = " + (parseInt(two) + two); //convert a two to integer first
alert(stringToPrint); // 2 + 2 = 5 finally!
\$\endgroup\$
0
votes
\$\begingroup\$

Mathcad

x:2
y:2
Given
x+y-4⎈=⎈!⎈!c
Find(x+y)=

Gives 5.

means the Ctrl key. It may not display properly in some browsers.

The trick is in the Given part. Given and everything that comes after it and before Find is called the Solve Block. The function Find will give the values of the variables which you pass to it which satisfy the equations inside the Solve Block, looping through the possible values of variables starting from their original values, in this case, x=2 and y=2. Here, the equation inside the Solve Block is x+y-4⎈=⎈!⎈!c, which gets formatted as x+y-4=¬¬c. Mathcad doesn't distinguish between scalars and booleans, just like ol' C89. And c is a built-in variable that stores an approximation of the speed of light in vacuum. So ¬¬c gives 1. This makes the equation x+y-4=1, and the only value of x+y that satisfies it is 5.

\$\endgroup\$
0
votes
\$\begingroup\$

C (gcc-4.9.2, gcc-4.8.3 and probably other gcc compilers)

A different variant of a previously posted answer.

#include <stdio.h>

int main(void) {
    int i = 1;
    printf("%d\n", 
                ++i //++i returns 2, i is now 2
                + i++ //i++ returns i, i.e. 2
    );
    return 0;
}

(see it online here)

Same trick as https://codegolf.stackexchange.com/a/30138/36458, GCC actually evaluates them the other way around.

\$\endgroup\$
0
votes
\$\begingroup\$

C#

I believe it works for .net framework <= 4.0

static void Main(string[] args)
    {
        Func<int, int> tmp = null;
        for (int i = 2; i < 3; i++)
            tmp = (x) => { return i + x; };
        Console.WriteLine(tmp(2));
    }
\$\endgroup\$
0
votes
\$\begingroup\$

PowerShell

#Make a character array string with the equation in it
#Measure the value, explicitly as a calculation
#Show only the resulting 'amount'
#(Golfed with short aliases and wildcard 'amount' for extra oomph)

[char[]]'2 + 2'|Measure -Sum|Select -Exp *t
5    

Nope, it measures the length of the string: 5 chars. It casts the string as char array, pipes those to Measure-Object; An array going into the pipeline is split into the contents, so there are five things to count. Measure-Object results in an object with these properties: {Count:5,Average: ,Sum:207, ...}. Then Select -Exp *t is a wildcard, but it matches the Count property instead of the non-existent 'Amount'; takes the value, and drops the rest. (-Sum is a thing, here adding up the ASCII character values, but I'm using it as a diversion)

\$\endgroup\$
0
votes
\$\begingroup\$

Lua:

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

a = 2
b = 2

print(a + b) -- 5

Try it

\$\endgroup\$
0
votes
\$\begingroup\$

Python 2

yay operator overloading :P

class int:
    number = 2
    def __init__(self, number): 
        self.number = number
    def __add__(self, other):
        return self.number + other.number + 1
 
two = int(2)   # works without above def!
print two + two

try on ideone!

pretty simple to understand, just overwrites the int class with a new one that adds one to each addition thing. Seriously I'm surprised print 2+2 by itself doesn't work.

\$\endgroup\$
0
votes
\$\begingroup\$

Vitsy

22+3mN
Since Vitsy is a stack language, it pushes 2 to the stack, 
then another 2, then adds them. Even so, it will do the following equation:
2+2=5

Output:

5

Visty may be stack based and 1D, but it can execute specific lines of a file (3m goes to the third line) What really happens here is 2+2, then push another 2 to the stack. Add the top two items, making the only item 6, pushes another 2, checks if the top two items are equal. If it's not (which it isn't), it pushes zero. Then, push 5 to the stack, and, finally, output the top item of the stack as a number.

\$\endgroup\$
0
votes
\$\begingroup\$

PHP

var_dump(2 + 2 === (int)((0.1 + 0.7)*18.75/3) ? true : false);

Ok, before you say "wtf? Where is the 2+2=5 here?", bear with me:

0.1 + 0.7 = 0.8
0.8 * 18.75 = 15
15/3 = 5

And we all know that 5 = 5. So there is nothing wrong changing that, right? It should print false, right? Well... that's not the case. And here is the reason.

\$\endgroup\$
0
votes
\$\begingroup\$

F#

let(+)_ _=5
2 + 2

There are other F# answers here, but I'm not sure why no one posted this one.

It simply redefines the result of addition operators to be the number 5.

Too obvious? A somewhat sneaker alternatively you would be:

let(~+)_=3
+ 2 + 2

It redefines the result prefix + to operator to be the number 3. The second + is normal addition. Note the space between the first + and the 2 is required to make the parser read it as an operator and not a literal; the other spaces are not required.

But this isn't underhanded enough. What about:

let printfn t 4=printfn t 5    
printfn "2 + 2 = %i" (2 + 2)

This doesn't change the actual result value of 2 + 2, it just changes what happens to get printed to the screen in output messages.

\$\endgroup\$
0
votes
\$\begingroup\$

TeaScript

\2+2=5\;
2+2

Outputs: 5


This also works:

\2+2=5\

Whaaat?


2+2=5? Sure, the TeaScript compiler just rolls with it
This feature is supposed to be used for golfing so you could do \p=n++\;p and that would compile to n++;n++. Essentially compile-time variables

\$\endgroup\$
0
votes
\$\begingroup\$

ngn/apl

+←=++

Reassigns X+Y to be a fork, viz. the sum of X=Y (which is 1 in the case of 2+2) and X+Y.

      +←=++
      2+2
5

Try it here.

\$\endgroup\$
1
  • \$\begingroup\$ the sum of X=Y wat? \$\endgroup\$
    – cat
    Mar 23, 2016 at 1:49
0
votes
\$\begingroup\$

Bash

alias +="printf'5\n'" 2+2=+ 2+=+ +2=+ 2=

After pasting/typing that in to your console, typing 2+2, 2 + 2, 2+ 2, and 2 +2 will all print 5 and a newline.

For more golfiness, alias 2+2="printf'5\n'" also works.

\$\endgroup\$

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