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.
156 Answers 156
Java
Reflection is indeed the right way to go with abusing Java... but you need to go deeper than just tweaking some values.
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws Exception {
Class cache = Integer.class.getDeclaredClasses()[0];
Field c = cache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] array = (Integer[]) c.get(cache);
array[132] = array[133];
System.out.printf("%d",2 + 2);
}
}
Output:
5
Explanation:
You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.
Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127.cache[132]
is the spot where 4 would normally be. Set it to 5.
Warning: Doing this in real code will make people very unhappy.
-
5\$\begingroup\$ Thought of this one as soon as I saw the question :) \$\endgroup\$Octavia Togami– Octavia Togami2014年05月30日 17:14:07 +00:00Commented May 30, 2014 at 17:14
-
306\$\begingroup\$ That. Is. Evil. Absolutely evil. +1 \$\endgroup\$John Dvorak– John Dvorak2014年05月30日 17:45:31 +00:00Commented May 30, 2014 at 17:45
-
75\$\begingroup\$ @JanDvorak in chat it was suggested
Integer[] array = (Integer[]) c.get(cache); fisherYatesShuffle(array);
Just imagine how many things would break... \$\endgroup\$user12166– user121662014年05月30日 17:57:44 +00:00Commented May 30, 2014 at 17:57 -
30\$\begingroup\$ Answers like this make me love this site more than SO. \$\endgroup\$Songo– Songo2014年05月30日 21:33:58 +00:00Commented May 30, 2014 at 21:33
-
35\$\begingroup\$ zomg, java answers never get top votes! +1 for bringing java to the top :) \$\endgroup\$Cruncher– Cruncher2014年06月02日 16:20:24 +00:00Commented Jun 2, 2014 at 16:20
C
Pretty cheap trick but I'm sure I will trap the most of you.
int main() {
int a = 2 + 2; a++;
printf("%d",a);
return 0;
}
Scroll the code to the right.
I'm not sure on Windows/Linux but on OSX, the scrollbar is not visible.
Anyway, this is a good reason to enable "space visualization" on your favorite code editor.
-
96\$\begingroup\$ Scrollbar is visible in Chromium, but who pays attention to it at first? :) \$\endgroup\$Ruslan– Ruslan2014年05月31日 17:56:51 +00:00Commented May 31, 2014 at 17:56
-
172\$\begingroup\$ To confuse folks, you might add a comment line that is long enough to "explain" the existence of a scrollbar, but dull enough so that noone cares to (scroll in order to) read it. \$\endgroup\$Hagen von Eitzen– Hagen von Eitzen2014年05月31日 22:29:20 +00:00Commented May 31, 2014 at 22:29
-
22\$\begingroup\$ In OS X, scrollbar visibility by default depends on whether a mouse is connected. If there's just a touchpad, scrollbars are overlaid and fade out when not in use. If there's a mouse connected, scrollbars steal space from the context box and are always visible. You can test this by unplugging and plugging in a USB mouse to a MacBook. This can be configured in System Preferences, of course. \$\endgroup\$mystery– mystery2014年06月01日 12:15:27 +00:00Commented Jun 1, 2014 at 12:15
-
49\$\begingroup\$ Clever, but on mobile it just wordwraps :) \$\endgroup\$Logan– Logan2014年06月01日 18:42:28 +00:00Commented Jun 1, 2014 at 18:42
-
31\$\begingroup\$ This is the only time that scrolling SE code windows don't make me want to break someone's fingers. \$\endgroup\$ObscureRobot– ObscureRobot2014年06月01日 21:23:11 +00:00Commented Jun 1, 2014 at 21:23
Haskell
I just love how you can throw anything at ghci and it totally rolls with it.
λ> let 2+2=5 in 2+2
5
-
36\$\begingroup\$ What does
let 2+2=5 in 5+5
do? ಠ_ಠ \$\endgroup\$John Dvorak– John Dvorak2014年05月30日 17:44:32 +00:00Commented May 30, 2014 at 17:44 -
22\$\begingroup\$ @JanDvorak
Non-exhaustive patterns in function +
- I'm defining a new function (+) here, and If I plug in anything that isn't2+2
it will error because I never defined what should happen in that case. \$\endgroup\$Flonk– Flonk2014年05月30日 17:50:24 +00:00Commented May 30, 2014 at 17:50 -
27\$\begingroup\$ @SHiNKiROU shadow, not redefine \$\endgroup\$John Dvorak– John Dvorak2014年05月30日 18:33:59 +00:00Commented May 30, 2014 at 18:33
-
96\$\begingroup\$ that almost sounds like: "And God said let 2+2=5 in 2+2" )) \$\endgroup\$OutFall– OutFall2014年05月30日 23:15:36 +00:00Commented May 30, 2014 at 23:15
-
11\$\begingroup\$ @user3217013 Learn Haskell, it's good for your heart. \$\endgroup\$sh03– sh032014年06月02日 02:19:12 +00:00Commented Jun 2, 2014 at 2:19
GolfScript
4:echo(2+2);
Prints 5
.
Of course GolfScript has a syntax that is markedly different from other languages, this program just happen to look like something Basic or C-ish.
4
- Put the number 4 on the stack. Stack content: 4
:echo
- Save the value at the top of the stack to the variable echo. Stack content: 4
(
- Decrement the value at the top of the stack by 1. Stack content: 3
2
- Put the number 2 on top of the stack. Stack content: 3 2
+
- Add the two numbers on top of the stack. Stack content: 5
2
- Put the number 2 on top of the stack. Stack content: 5 2
)
- Increment the value at the top of the stack by 1. Stack content: 5 3
;
- Remove the top element from the stack. Stack content: 5
GolfScript will by default print anything left on the stack after execution has finished.
-
3\$\begingroup\$ Can you explain that for people who don't speak GolfScript please? \$\endgroup\$MadTux– MadTux2014年06月10日 09:42:28 +00:00Commented Jun 10, 2014 at 9:42
-
1\$\begingroup\$ @MadTux Here you go. \$\endgroup\$aaaaaaaaaaaa– aaaaaaaaaaaa2014年06月10日 16:14:03 +00:00Commented Jun 10, 2014 at 16:14
-
1\$\begingroup\$ Thanks. (I'll upvote later because I reached my daily limit, here's a beer.) \$\endgroup\$MadTux– MadTux2014年06月10日 16:21:50 +00:00Commented Jun 10, 2014 at 16:21
-
5\$\begingroup\$ Simple and cheaty, I love it. +1 \$\endgroup\$seequ– seequ2014年06月10日 16:22:01 +00:00Commented Jun 10, 2014 at 16:22
-
9\$\begingroup\$ i like it becaus it doesn't seem like it's tricking you with math or semantics, it seems so straightforward and yet 5 ^^ \$\endgroup\$dwana– dwana2014年12月26日 10:44:54 +00:00Commented Dec 26, 2014 at 10:44
Java
Always have to round your doubles, folks
public class TwoPlusTwo {
public static void main(String... args) {
double two = two();
System.out.format("Variable two = %.15f%n", two);
double four = Math.ceil(two + two); // round just in case
System.out.format("two + two = %.15f%n", four);
}
// 20 * .1 = 2
private static double two() {
double two = 0;
for(int i = 0; i < 20; i++) {
two += .1;
}
return two;
}
}
Output:
Variable two = 2.000000000000000
two + two = 5.000000000000000
Explanation:
No, seriously, you always have to round your doubles. 15 isn't enough digits to show that the
two()
method actually produces2.0000000000000004
(16 is enough, though).
In the raw Hex representations of the numbers, it's only a 1 bit difference (between4000000000000001
and4000000000000000
)... which is enough to make theMath.ceil
method return 5, not 4.
-
61\$\begingroup\$
Math.ceil(two + two); // round just in case
I see what you did there \$\endgroup\$Tim S.– Tim S.2014年05月30日 16:59:02 +00:00Commented May 30, 2014 at 16:59 -
17\$\begingroup\$ Making both a function and a variable with the same name... Wow. \$\endgroup\$configurator– configurator2014年06月01日 17:30:23 +00:00Commented Jun 1, 2014 at 17:30
-
107\$\begingroup\$ @configurator that's nothing, there isn't even a class named
two
. Production grade java isTwo two = Two.two.two();
with Two.two being of type TwoFactory. \$\endgroup\$Jannis Froese– Jannis Froese2014年06月02日 01:09:21 +00:00Commented Jun 2, 2014 at 1:09 -
36\$\begingroup\$ Two.Infinity.And.Beyond() \$\endgroup\$CincauHangus– CincauHangus2014年06月02日 10:00:10 +00:00Commented Jun 2, 2014 at 10:00
-
7\$\begingroup\$ @TimS I ceil what you did there \$\endgroup\$thenaglecode– thenaglecode2014年07月11日 04:10:58 +00:00Commented Jul 11, 2014 at 4:10
BBC BASIC
EDIT: For Andrea Faulds and Squeamish Ossifrage, a more convincing version using a different interpreter: http://sourceforge.net/projects/napoleonbrandy/
MODE 6
VDU 23,52,254,192,252,6,6,198,124,0
PRINT
PRINT "2+2=";2+2
PRINT "2+3=";2+3
enter image description here
This actually prints the number 4, but the
VDU 23
redefines the font for ASCII 52 so that it looks like a 5 instead of a 4. Screen mode 6 was selected for aesthetic reasons (characters of a reasonable size.)
The original image using the emulator at http://bbcbasic.co.uk/bbcwin/bbcwin.html. (with slightly different code) can be seen in the edit history.
-
8\$\begingroup\$ Those fonts look different though. Do you think you could make it use the correct font? \$\endgroup\$mystery– mystery2014年06月01日 12:18:46 +00:00Commented Jun 1, 2014 at 12:18
-
\$\begingroup\$ @AndreaFaulds I'm using the emulator from bbcbasic.co.uk/bbcwin/bbcwin.html. It supports the font redefinition of original BBC Basic on an 8x8 grid. But the default font of the emulator is clearly higher res than 8x8. So I could probably do a better job, but it wouldn't be perfect. I suppose I could redefine the font for all 5 as well as 4, then they would look the same. \$\endgroup\$Level River St– Level River St2014年06月01日 18:05:00 +00:00Commented Jun 1, 2014 at 18:05
-
5\$\begingroup\$ @AndreaFaulds The question didn't say that the result should be indistinguishable from other 5s. I think this is actually a feature.
2+3=5
and2+2=5'
\$\endgroup\$Ben Jackson– Ben Jackson2014年06月01日 20:55:23 +00:00Commented Jun 1, 2014 at 20:55 -
1\$\begingroup\$ This matches the original font in the BBC Micro:
VDU 23,52,126,96,124,6,6,102,60,0
\$\endgroup\$r3mainer– r3mainer2014年06月02日 10:37:38 +00:00Commented Jun 2, 2014 at 10:37 -
\$\begingroup\$ @squeamishossifrage thanks for the info. It won't match the font in the emulator though. Your example is 7 pixels high, just like mine. Also it has a zero at the bottom, just like mine, whereas it looks like I need to move it down a bit (i.e, have the zero at the top instead of the bottom.) A key difference is that I have 126,64 whereas you have 126,96, and you have some 6's instead of my 2's. That's because the original BBC font had thick vertical lines, so it could be read easily in 80 column format on a standard TV screen. \$\endgroup\$Level River St– Level River St2014年06月02日 10:46:26 +00:00Commented Jun 2, 2014 at 10:46
Brainfuck
+++++ +++++
+ +
+ + + +++++
+++++ +++ +++++
+ + + +++++
+ +
+++++ +++++.
Output:
5
Try it here.
I know this might sound a little to simple, but I tried to be creative, as suggested in original post.
-
1\$\begingroup\$ I don't know brainfuck, it took me a couple of minutes to figure this out. ASCII 53, right? \$\endgroup\$Level River St– Level River St2014年06月05日 21:12:43 +00:00Commented Jun 5, 2014 at 21:12
-
4\$\begingroup\$ As long you have the
+++++.
you can paint anything. \$\endgroup\$Eduard Florinescu– Eduard Florinescu2014年06月06日 10:20:37 +00:00Commented Jun 6, 2014 at 10:20 -
1\$\begingroup\$ @steveverrill : yes you are right. (and this is the only way to output ascii characters in BF). \$\endgroup\$tigrou– tigrou2014年06月06日 11:32:08 +00:00Commented Jun 6, 2014 at 11:32
-
1\$\begingroup\$ I don't understaaaand \$\endgroup\$Leif Willerts– Leif Willerts2015年10月29日 21:54:56 +00:00Commented Oct 29, 2015 at 21:54
Bash
Since this is a popularity-contest, I guess I should use a long-winded method...
For people who don't know Bash: $((...expr...))
is a syntax to evaluate arithmetic expressions. $(bc<<<...expr...)
does the same using the bc
command-line calculator.
v=2 #v is 2
v+=2 #v is 4
v=$(($v*5)) #v is 20
v=$(($v-16)) #v is 4
v=$(bc<<<"sqrt($v)+2") #v is 4 (sqrt(4) is 2)
v=$(bc<<<"$v/4+3") #v is 4 (4/4 = 1)
echo '2+2=' $v #So v is 4...?
Output
2+2= 5
Explanation
The second line concatenates v and 2 instead of adding them, to make 22.
Actual explanation:v=2 #v is 2 v+=2 #v is 22 v=$(($v*5)) #v is 110 v=$(($v-16)) #v is 94 v=$(bc<<<"sqrt($v)+2") #v is 11 (by default, bc rounds to integers) v=$(bc<<<"$v/4+3") #v is 5 (11/4 is 2 with rounding) echo '2+2=' $v #TADAAAM
-
8\$\begingroup\$ Nice maths trick going on there! \$\endgroup\$tomsmeding– tomsmeding2014年05月31日 19:07:38 +00:00Commented May 31, 2014 at 19:07
-
5\$\begingroup\$ @tomsmeding It was quite fun, although about halfway through I realised that I had put
15
instead of16
in line 4. Luckily, it still worked because ofbc
's rounding \$\endgroup\$user16402– user164022014年06月01日 16:28:45 +00:00Commented Jun 1, 2014 at 16:28 -
2\$\begingroup\$ See if you like the look of this style which is also valid Bash (eliminates the dollar signs, allows spaces around the equal sign and allows combined assignment operators):
((v = v * 5))
or((v *= 5))
\$\endgroup\$Dennis Williamson– Dennis Williamson2014年06月09日 21:29:06 +00:00Commented Jun 9, 2014 at 21:29 -
2\$\begingroup\$ Nice one, but I spotted the
+=
thing immediately. \$\endgroup\$user344– user3442014年07月02日 08:41:55 +00:00Commented Jul 2, 2014 at 8:41 -
2\$\begingroup\$ @ardnew yes there is. the first two lines (
v=2
andv+=2
): to someone unfamiliar with Bash variable handling, that would be equivalent to2+2
, but it is in fact"2"+"2"
, i.e."22"
. the other comments in the code are only wrong because of this. I know, not everyone finds this funny \$\endgroup\$user16402– user164022014年07月24日 07:11:17 +00:00Commented Jul 24, 2014 at 7:11
Python
Inspired by the Java answer:
>>> patch = '\x312\x2D7'
>>> import ctypes;ctypes.c_int8.from_address(id(len(patch))+8).value=eval(patch)
>>> 2 + 2
5
Like Java, CPython uses the same memory location for any copy of the first few small integers (0-255 if memory serves). This goes in and directly edits that memory location via
ctypes
.patch
is just an obfuscated"12-7"
, a string withlen
4, whicheval
's to 5.
A more obfuscated version
exec("\x66\x72\x6f\x6d\x20c\x74\x79\x70e\x73\x20\x69\x6d\x70\
\x6f\x72\x74\x20c\x5f\x69\x6e\x748\x20a\x73\x20x\x3bf\x72\x6f\
\x6d\x20\x73\x74\x72\x75c\x74\x20\x69\x6d\x70\x6f\x72\x74\x20\
ca\x6cc\x73\x69\x7ae\x20a\x73\x20x0\x3bx\x2ef\x72\x6f\x6d\x5f\
a\x64\x64\x72e\x73\x73\x28\x69\x64\x284\x29\x2bx0\x28\x27\x50\
\x50\x27\x29\x29\x2e\x76a\x6c\x75e\x3d5")
Beyond 2+2
As OP mentioned, 2+2 can be kinda boring; so here's some cleaner, multiplatform, multi-width code for wanton abuse.
from __future__ import division, print_function
import struct
import ctypes
import random
# Py 2.7 PyIntObject:
# - PyObject_HEAD
# - PyObject_HEAD_EXTRA [usually nothing unless compiled with DEBUG]
# - (Py_ssize_t) ob_refcnt
# - (_typeobject) *ob_type
# - (long) ob_ival
# two platform-sized (32/64-bit) ints (ob_refcnt and *ob_type from above)
offset = struct.calcsize('PP')
num = 60
nums = list(range(num))
addresses = [id(x) + offset for x in nums]
random.shuffle(nums)
for a, n in zip(addresses, nums):
ctypes.c_ssize_t.from_address(a).value = n
print('2 + 2 =', 2+2)
print('9 - 4 =', 9-4)
print('5 * 6 =', 5*6)
print('1 / 0 =\n', 1/0)
print('(1 + 2) + 3 = ', (1+2)+3)
print('1 + (2 + 3) = ', 1+(2+3))
print('(2 + 3) + 1 = ', (2+3)+1)
print('2 + (3 + 1) = ', 2+(3+1))
Running with Python 2.7...ignore that line at the end. Works in Windows 64-bit and Ubuntu 32-bit, the two systems I have easy access to.
$ python awful.py
2 +たす 2 =わ 24
9 -ひく 4 =わ 49
5 * 6 = 55
1 / 0 = 0.76
(1 + 2) + 3 = 50
1 + (2 + 3) = 68
(2 + 3) + 1 = 50
2 + (3 + 1) = 61
Segmentation fault (core dumped)
Unsurprisingly, we can break the associative property of addition, where (a + b) + c = a + (b + c), as seen in the 1st and 2nd 1+2+3
lines, but inexplicably we also break the commutative property (where a + b = b + a; 2nd and 3rd lines). I wonder if the Python interpreter just ignores superfluous parentheses around addition expressions.
-
96\$\begingroup\$ Yes, we definitely all just casually ignore segfaults... \$\endgroup\$user16402– user164022014年05月31日 11:20:38 +00:00Commented May 31, 2014 at 11:20
-
10\$\begingroup\$ It's worth mentioning that this isn't really a Python trick and is only specific to the C implementation of Python. \$\endgroup\$xApple– xApple2014年06月02日 00:05:05 +00:00Commented Jun 2, 2014 at 0:05
-
1\$\begingroup\$ @NickT Ah! okay. I was under the impression that you had tried the original under the same 64-bit windows, 32-bit ubuntu setup \$\endgroup\$DavidJFelix– DavidJFelix2014年06月02日 19:12:14 +00:00Commented Jun 2, 2014 at 19:12
-
22\$\begingroup\$
exec('\x66\x72\x6f\x6d\x20\x63\x74\x79\ \x70\x65\x73\x20\x69\x6d\x70\x6f\ \x72\x74\x20\x63\x5f\x69\x6e\x74\ \x38\x3b\x20\x69\x6d\x70\x6f\x72\ \x74\x20\x73\x74\x72\x75\x63\x74\ \x3b\x20\x63\x5f\x69\x6e\x74\x38\ \x2e\x66\x72\x6f\x6d\x5f\x61\x64\ \x64\x72\x65\x73\x73\x28\x69\x64\ \x28\x34\x29\x20\x2b\x20\x73\x74\ \x72\x75\x63\x74\x2e\x63\x61\x6c\ \x63\x73\x69\x7a\x65\x28\x27\x50\ \x50\x27\x29\x29\x2e\x76\x61\x6c\ \x75\x65\x3d\x35')
Is a modified first version. I made this so I could drop it into $PYTHONSTARTUP in /etc/profile as red team in hacking competitions. \$\endgroup\$DavidJFelix– DavidJFelix2014年06月02日 20:14:36 +00:00Commented Jun 2, 2014 at 20:14 -
2\$\begingroup\$ Yeah. Sidenote, it seems that 1, 0 and -1 are some of the numbers that python immediately segfaults with. I was thinking those would be the worst for screwing up python programs behavior. It may be possible to utilize fuckitpy to contain these errors. \$\endgroup\$DavidJFelix– DavidJFelix2014年06月02日 23:21:44 +00:00Commented Jun 2, 2014 at 23:21
JavaScript:
g = function () {
H = 3
return H + H
}
f = function () {
Η = 2
return Η + H
}
// 3 + 3 = 6
alert(g())
// 2 + 2 = 5
alert(f())
Check it at http://jsfiddle.net/qhRJY/
Both H (Latin letter capital h) and Η (Greek letter capital eta) are set to the global scope because they were not defined as local to the functions with the var keyword. While they look similar, they are actually 2 different variables with 2 different values. Using Ctrl+F in your browser you will find that Η (eta) shows up significantly less than H (h) on this page.
-
4\$\begingroup\$ @Sam even though the two 'H's look the same, they are in fact 2 entirely different characters. In Unicode there can be different characters that look the same but have different code-points. In this specific case; the other "H" is actually the greek letter Eta. \$\endgroup\$d3dave– d3dave2014年05月31日 08:39:45 +00:00Commented May 31, 2014 at 8:39
-
79\$\begingroup\$ Using homoglyphs to "confuse" readers is now officially not funny. \$\endgroup\$John Dvorak– John Dvorak2014年06月01日 05:46:13 +00:00Commented Jun 1, 2014 at 5:46
-
29\$\begingroup\$ The homoglyphs become funny in combination with javascript's ridiculous global variables. \$\endgroup\$Konstantin Weitz– Konstantin Weitz2014年06月01日 17:16:54 +00:00Commented Jun 1, 2014 at 17:16
-
3\$\begingroup\$ It's not the "Unicode Η character", it's Latin H and Greek Eta (Η). \$\endgroup\$I answer wrong - have fun– I answer wrong - have fun2014年06月02日 15:39:15 +00:00Commented Jun 2, 2014 at 15:39
-
4\$\begingroup\$ @Vortico hmm... what do you wish when a FAQ question doesn't suffice? A FAQ question linked from the help center? Note that only moderators can apply the faq tag. As for the answer - the question states "score +5 or more and at least twice as many upvotes as downvotes". The answer has 27 upvotes and no downvote. That sounds to me like fulfilling the criteria stated in the answer, and the amount of upvotes is pretty impressive for the second oldest answer on a question on the meta site of a site where only 124 people have voted more than 10 times. How many would you like? Everyone? \$\endgroup\$John Dvorak– John Dvorak2014年06月04日 13:47:58 +00:00Commented Jun 4, 2014 at 13:47
JavaScript
function addDecibels(){return (10*Math.log10([].reduce.call(arguments,(p,c)=>p+Math.pow(10,c/10),0))).toFixed(1);}
alert( addDecibels(2,2) );
The underhanded bit is that its not actually underhanded - if you add a 2dB sound source to another 2dB sound source then resulting combined noise will be 5dB (and if you add two 30dB sources then its 33dB) as they are measured on a log scale.
You can see it on a different calculator here.
-
\$\begingroup\$ Well it's actually more like 5.01 decibels, but far away enough from 4 to count. \$\endgroup\$Joe Z.– Joe Z.2016年01月12日 20:57:53 +00:00Commented Jan 12, 2016 at 20:57
PHP
echo '2 + 2 = ' . (2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'dunno');
Which produces:
2 + 2 = 5
This is because in PHP, ternaries are calculated left to right, so it's actually
(2 + 2 === 4 ? 4 : 2 + 2 === 5) // 2 + 2 is == 4, and 4 == true, therefore echo 5
? 5 : 'dunno';
-
35\$\begingroup\$ obligatory phpsadness \$\endgroup\$wchargin– wchargin2014年06月01日 04:12:48 +00:00Commented Jun 1, 2014 at 4:12
-
1\$\begingroup\$ I've got another
PHP
example:$a=2;echo "2+2=".$a++ + $a++;
\$\endgroup\$avall– avall2014年06月01日 21:27:21 +00:00Commented Jun 1, 2014 at 21:27 -
\$\begingroup\$ It's obvious that $a++ makes 3 and the result will be 6. I don't get what you're thinking. \$\endgroup\$Ozh– Ozh2014年06月02日 09:58:16 +00:00Commented Jun 2, 2014 at 9:58
-
1\$\begingroup\$ @Janus PHPsadness #30 explains it well \$\endgroup\$wchargin– wchargin2014年06月03日 04:13:49 +00:00Commented Jun 3, 2014 at 4:13
-
2\$\begingroup\$ Also trending on stackexchange... \$\endgroup\$recursion.ninja– recursion.ninja2014年06月04日 15:26:09 +00:00Commented Jun 4, 2014 at 15:26
JavaScript
var total = 2 + 2;
if(total = 5)
{
alert('I guess 2 + 2 = 5');
}
else
{
alert('The universe is sane, 2 + 2 = 4');
}
-
73\$\begingroup\$
=
instead of==
, easy to see and frankly rather uninspired. \$\endgroup\$ApproachingDarknessFish– ApproachingDarknessFish2014年05月30日 20:06:57 +00:00Commented May 30, 2014 at 20:06 -
19\$\begingroup\$ Have an upvote anyway, I make that mistake a lot \$\endgroup\$user16402– user164022014年05月31日 10:51:43 +00:00Commented May 31, 2014 at 10:51
-
6\$\begingroup\$ I still like this answer \$\endgroup\$Sam Creamer– Sam Creamer2014年06月02日 17:43:11 +00:00Commented Jun 2, 2014 at 17:43
-
5\$\begingroup\$ I like it too. Not every language uses
=
only as an assigment but a comparison operator (e.g. Pascal, SQL, VB) \$\endgroup\$avall– avall2014年06月02日 20:27:54 +00:00Commented Jun 2, 2014 at 20:27 -
\$\begingroup\$ I find it very obvious \$\endgroup\$Oliver Ni– Oliver Ni2015年01月01日 23:14:59 +00:00Commented Jan 1, 2015 at 23:14
C#
static void Main(string[] args)
{
var x = 2;
var y = 2;
if (1 == 0) ;
{
++x;
}
Console.WriteLine(x + y);
}
-
7\$\begingroup\$ ah, the good old trick with rogue characters. That's why you should use 1TBS everywhere. \$\endgroup\$John Dvorak– John Dvorak2014年05月30日 17:52:04 +00:00Commented May 30, 2014 at 17:52
-
11\$\begingroup\$ @JanDvorak Does this work because of the semicolon after the if statement? I don't know C# but I have used C++ \$\endgroup\$user16402– user164022014年05月30日 18:31:51 +00:00Commented May 30, 2014 at 18:31
-
5\$\begingroup\$ @professorfish that's what I assume. Also, languages that don't let you insert random curly braces FTW. \$\endgroup\$John Dvorak– John Dvorak2014年05月30日 18:33:04 +00:00Commented May 30, 2014 at 18:33
-
12\$\begingroup\$ Without the ";", the if statement controls whether the code block will be executed. With the ";" in there, the if is evaluated but nothing is done with the result. Then the code block is executed every time, regardless. In C#, it is perfectly acceptable to have random code blocks. \$\endgroup\$Grax32– Grax322014年05月30日 18:58:59 +00:00Commented May 30, 2014 at 18:58
-
2\$\begingroup\$ I got myself with this one the other day. I had a for loop with a
;
after it, which was perfectly intentional as I was using the empty loop to advance a cursor. I accidentally removed the semi-colon, everything blew up, and I couldn't figure out why. \$\endgroup\$mpen– mpen2014年06月02日 00:32:43 +00:00Commented Jun 2, 2014 at 0:32
It's dangerous to decorate your Javascript with ASCII art.
-~// JS \\~-
~-// Maths \\-~
-~// Madness \\~-
(2 + 2)
When the comments are removed, the remaining symbols and operators evaluate to
-~~--~(2 + 2)
This makes use of the Bitwise Not operator (~) in JS, along with a handful of Minus signs which will negate the values along the way.
-
3\$\begingroup\$ I was wondering how the
--
operator was acceptable as it should error out withInvalid left-hand side expression in prefix operation
; however I realized that there is a whitespace character between them. \$\endgroup\$rgajrawala– rgajrawala2015年04月09日 01:51:09 +00:00Commented Apr 9, 2015 at 1:51
Bash
#!/bin/bash
# strings of length 2
x="ab"
y="cd"
# add lengths by concatenation
c="$(cat<<<$x; cat<<<$y)"
# display the lengths of the parts and the sum
echo "${#x} + ${#y} = ${#c}"
Output:
2 + 2 = 5
The output from each
cat
will have an implicit newline, but the final newline is stripped off by the command substitution$( )
Here's another:
#!/bin/bash
# Create an array of ascending integers
a=({1..10})
# Use the sum to index into the array
s="2 + 2"
i=$(($s))
echo "$s = ${a[$i]}"
Bash arrays are zero indexed
-
3\$\begingroup\$ I did actually catch the first one, as I've had lots of problems with things like that when golfing in Bash. As for the second one, where aren't arrays zero-indexed? \$\endgroup\$user16402– user164022014年05月30日 18:29:52 +00:00Commented May 30, 2014 at 18:29
-
3\$\begingroup\$ @professorfish Applescript, for example:
set a to {1, 2, 3, 4, 5, 6, 7, 8}
item 4 of a
\$\endgroup\$Digital Trauma– Digital Trauma2014年05月30日 18:32:42 +00:00Commented May 30, 2014 at 18:32 -
12\$\begingroup\$ @DigitalTrauma Applescript is weird \$\endgroup\$user16402– user164022014年05月30日 18:44:32 +00:00Commented May 30, 2014 at 18:44
-
5\$\begingroup\$
zsh
uses 1-indexed arrays (and$arr[0]
is simply unset or undefined or something), unless theKSH_ARRAYS
option is set, in which case arrays are 0-indexed. \$\endgroup\$chepner– chepner2014年05月30日 18:57:32 +00:00Commented May 30, 2014 at 18:57 -
4\$\begingroup\$ @professorfush: Lua & Fortran are 1 indexed. Anytime I count to 10, I always start at 1, not 0. :D \$\endgroup\$Kyle Kanos– Kyle Kanos2014年05月30日 23:23:28 +00:00Commented May 30, 2014 at 23:23
Perl
# Generic includes
use strict;
use warnings;
use 5.010;
use Acme::NewMath;
# Ok, time to begin the real program.
if (2 + 2 == 5) {
say 5;
}
else {
say "Dunno...";
}
It depends on CPAN module called Acme::NewMath. Because of wrong file names in the module, this will only work on case insensitive file systems (like on Windows or Mac OS X), but I blame the original module's author here. Acme::NewMath implements mathematics according to the Ingsoc ideology.
-
16\$\begingroup\$ This is quite sly. Nobody ever looks at your imports/includes. \$\endgroup\$user16402– user164022014年05月31日 13:51:05 +00:00Commented May 31, 2014 at 13:51
R
# add the mean of [1,3] to the mean of [4,0] (2 + 2)
mean(1,3) + mean(4,0)
output:
5
the code actually adds the mean of [1] to the mean of [4]. The correct way to use the mean function in R would be:
mean(c(1,3)) + mean(c(4,0))
This is unlike some other mathematical functions in R, such assum
,max
, andmin
; wheresum(1,3)
,max(1,3)
, andmin(3,1)
would all give the expected answer.
-
7\$\begingroup\$ Not bad, fooled me for a bit. \$\endgroup\$qwr– qwr2014年06月02日 06:22:50 +00:00Commented Jun 2, 2014 at 6:22
Java
public class Five {
public static void main(final String... args) {
System.out.println(256.0000000000002 + 256.0000000000002);
}
}
output:
512.0000000000005
Probably works in any language that uses the same kind of doubles.
-
7\$\begingroup\$ That's a very strange main signature. \$\endgroup\$Bertie Wheen– Bertie Wheen2014年06月01日 22:11:41 +00:00Commented Jun 1, 2014 at 22:11
-
10\$\begingroup\$ Java implements variadic arguments as arrays under the hood. \$\endgroup\$CodaFi– CodaFi2014年06月02日 04:47:48 +00:00Commented Jun 2, 2014 at 4:47
-
4\$\begingroup\$ Took me a moment to realize that you are probably talking about the last digits in the doubles. I saw that the first digits added correctly (
_2_56 + _2_56 = _5_12
), but it seems more likely that you mean256.000000000000_2_ + 256.000000000000_2_ = 512.000000000000_5_
(note: underscores used to "bold" the digits. \$\endgroup\$Justin– Justin2014年06月09日 06:59:55 +00:00Commented Jun 9, 2014 at 6:59
Befunge
This is written in Befunge, but is designed to look like Python.
#>>>>>>>>>>>>>>>>>v
# Calculate 2 + 2 v
#>>>>>>>>>>>>>>>>>v
def add(v,w):
return v+w
# I rewrote this 5 times and it still doesn't work
print add(2,2) #... Still not working
# email: [email protected]
When run (with the correct interpreter) the program will print 5
.
Explanation:
A Befunge program is made up of a grid of single character commands. The first command is the one in the top left corner, and the reading of commands proceeds to the right. But the direction can change during program execution.
Only the first row of characters, and the column of characters starting with thev
in the first row are run. The characters in question do:
#
- skip the next command
>
- From now on, commands are read to the right of the current command
v
- From now on, commands are read below the current command
5
- Push 5 to the stack
.
- Pop and print the number at the top of the stack
@
- End the program
<space>
- Do nothing
If you knew you were programming in Befunge, this wouldn't really trick anyone. But if you came across this and didn't realize it was Befunge, it most likely would.
-
11\$\begingroup\$ +1, This is very devious, because who the hell looks at the program that runs the source code when debugging? \$\endgroup\$MrLore– MrLore2014年07月25日 03:45:38 +00:00Commented Jul 25, 2014 at 3:45
JavaScript
Code:
var a = 3;
а = 2;
a + а;
Output:
5
You can test it yourself on your console or check this Fiddle
-
6\$\begingroup\$ Can you point me to a resource or explain to me why this works. I know it does work because I checked out the Fiddle of it, but I don't understand why. \$\endgroup\$Family– Family2014年05月30日 23:14:19 +00:00Commented May 30, 2014 at 23:14
-
29\$\begingroup\$ the "a" variable isnt the same both times (sorry if im spoiling this). Sneaky unicode indeed \$\endgroup\$Sam Creamer– Sam Creamer2014年05月31日 02:16:07 +00:00Commented May 31, 2014 at 2:16
-
6\$\begingroup\$ I love how the next character,
U+0431
, is б—almost 6! \$\endgroup\$wchargin– wchargin2014年06月01日 04:12:31 +00:00Commented Jun 1, 2014 at 4:12 -
73\$\begingroup\$ Using homoglyphs to "confuse" readers is now officially not funny. \$\endgroup\$John Dvorak– John Dvorak2014年06月01日 05:56:11 +00:00Commented Jun 1, 2014 at 5:56
-
40\$\begingroup\$ @JanDvorak That answer was posted after this one; it doesn't apply here. \$\endgroup\$Doorknob– Doorknob2014年06月01日 12:26:53 +00:00Commented Jun 1, 2014 at 12:26
C (Linux, gcc 4.7.3)
#include <stdio.h>
int main(void)
{
int a=3, b=2;
printf("%d + %d = %d", --a, b, a+b);
}
It prints 2+2=5
So a=2, right?
gcc-4.7.3 evaluates the function parameters from right to left. When a+b is evaluated, a is still 3.
-
16\$\begingroup\$ Nice use of unspecified behavior \$\endgroup\$chbaker0– chbaker02014年06月05日 00:34:47 +00:00Commented Jun 5, 2014 at 0:34
FORTRAN 77
program BadSum
integer i,a,j
common i,a
a = 1
i = 2
call addtwo(j)
print *,j
end
subroutine addtwo(j)
integer a,i,j
common a,i
c since a = 1 & i = 2, then 2 +たす 1 +たす 1 =わ 2 +たす 2 =わ 4
j = i + a + a
end
Standard abuse of
common
blocks: order matters; I swapped the order in the block in the subroutine so I'm really adding1 + 2 + 2
.
-
6\$\begingroup\$ @JanDvorak: Haha, I could have used FORTRAN IV in which I could redefine literals, e.g.
2=3
\$\endgroup\$Kyle Kanos– Kyle Kanos2014年05月30日 18:12:32 +00:00Commented May 30, 2014 at 18:12 -
1\$\begingroup\$ @KyleKanos, that's what I thought this was going to be when I saw your post was written in FORTRAN. \$\endgroup\$danmcardle– danmcardle2014年05月30日 21:56:28 +00:00Commented May 30, 2014 at 21:56
-
\$\begingroup\$ @KyleKanos Do it! \$\endgroup\$ClickRick– ClickRick2014年06月01日 03:10:40 +00:00Commented Jun 1, 2014 at 3:10
-
1\$\begingroup\$ @KyleKanos: Did that work with integer literals or only floats? I would think that on a machine of that era, an integer literal and an address would have been the same size, but smaller than a float, so pooling float literals would save space but pooling int literals would not. \$\endgroup\$supercat– supercat2014年06月03日 19:08:32 +00:00Commented Jun 3, 2014 at 19:08
-
2\$\begingroup\$ @KyleKanos: My understanding is that compilers wouldn't allow a direct assignment to a literal, but function calls used pass by reference, and passing a floating-point literal to a function would generally pass the address of a value in a pool of floating-point literals. Passing an integer value to a function would cause it to be pooled, but most code that used integers would include the values directly. \$\endgroup\$supercat– supercat2014年06月03日 19:23:11 +00:00Commented Jun 3, 2014 at 19:23
Ruby
class Fixnum
alias plus +
def + (other)
plus(other).succ
end
end
puts 2 + 2
This increases the result of all additions whose first argument is a Fixnum (which 2 is, at least in MRI) by 1.
The side-effects of this are even worse than the Java version.
Ruby
Ruby has first class environments. This means lots of things. It also means that lots of things can be done that... maybe shouldn't.
def mal(&block)
block.call
for v in block.binding.eval("local_variables");
block.binding.eval('if ' + v.to_s + ' == 4 then ' + v.to_s + ' = 5 end')
end
end
a = 2 + 2;
b = 2 + 4;
puts "2 + 2 = ", a
puts "2 + 4 = ", b
mal do
puts "But in 1984..."
end
puts "2 + 2 = ", a
puts "2 + 4 = ", b
The output of this is:
2 +たす 2 =わ 4 2 +たす 4 =わ 6 But in 1984... 2 +たす 2 =わ 5 2 +たす 4 =わ 6
If you want to understand more about the joys and dangers of this, Ruby Conf 2011 Keeping Ruby Reasonable and read First-class environments from the Abstract Heresies blog.
-
\$\begingroup\$ Also:
class Fixnum; def +(n) 5 end end; 2 + 2 # => 5
\$\endgroup\$film42– film422014年06月02日 02:38:24 +00:00Commented Jun 2, 2014 at 2:38 -
1\$\begingroup\$ To just do for the specific case:
class Fixnum; alias_method :orig_plus, :+; protected :orig_plus; def +(n) self == 2 && n == 2 ? 5 : self.orig_plus(n) end end
\$\endgroup\$Gary S. Weaver– Gary S. Weaver2014年06月05日 03:26:39 +00:00Commented Jun 5, 2014 at 3:26
Python
Code prints 5 which is correct answer for this task.
def int(a):
return ~eval(a)
def add(a,b):
return int(a)+int(b)
print ~add("2","2")
Edit: Here's alternative version which adds integers, not stringified twos.
def int(a): return ~eval(`a`)
def add(a,b): return int(a)+int(b)
print ~add(2,2)
Tilde is an unary inverse operator which returns
-x-1
, so first step is to get-6
and then with another operator in5
-
\$\begingroup\$ Why
~eval(`a`)
instead of just~a
? \$\endgroup\$Andrea Corbellini– Andrea Corbellini2014年06月02日 13:25:48 +00:00Commented Jun 2, 2014 at 13:25 -
2\$\begingroup\$ I wanted to leave some of the
int()
functionality andeval()
does the job if the input is a stringified integer :) \$\endgroup\$avall– avall2014年06月02日 14:27:32 +00:00Commented Jun 2, 2014 at 14:27
Scheme
(define 2+2 5)
2+2 ;=> 5
-
9\$\begingroup\$ hey!
2+2
isn't how you do addition in lisp! \$\endgroup\$John Dvorak– John Dvorak2014年05月30日 17:54:39 +00:00Commented May 30, 2014 at 17:54 -
1\$\begingroup\$ So what? It seemingly add 2 to 2 as is in the task. \$\endgroup\$Hauleth– Hauleth2014年05月30日 18:33:26 +00:00Commented May 30, 2014 at 18:33
-
119\$\begingroup\$ @JanDvorak I've never used lisp, but as I understand it it's something like
((((2))(()()))()()(()((((+))))()(((()(())((((2)))))()))(())))
. \$\endgroup\$undergroundmonorail– undergroundmonorail2014年05月31日 04:00:47 +00:00Commented May 31, 2014 at 4:00 -
2\$\begingroup\$ "Redefining 2+2 as 5 is not very creative! Don't doublethink it, try something else." --- Well, in R5RS I can redefine + instead 2+2 or 2. The answer is here: pastebin.com/KHtm9Jmv \$\endgroup\$Felipe– Felipe2014年06月02日 04:42:23 +00:00Commented Jun 2, 2014 at 4:42
-
1\$\begingroup\$ @FelipeMicaroniLalli that adnotation was made after my answer so it doesn't count. \$\endgroup\$Hauleth– Hauleth2014年06月04日 08:36:03 +00:00Commented Jun 4, 2014 at 8:36
C#
var c = Enumerable.Range(2, 2).Sum();
To someone not familiar, this will look like I'm getting a range starting and ending at 2. In reality, it starts at 2 and goes for two numbers. So 2 + 3 = 5.
-
6\$\begingroup\$ A range starting and ending at 2 would be just
{ 2 }
, wouldn't it? \$\endgroup\$Paŭlo Ebermann– Paŭlo Ebermann2014年05月31日 22:12:49 +00:00Commented May 31, 2014 at 22:12 -
1\$\begingroup\$ @PaŭloEbermann
Enumerable.Range
doesn't take a start and an end, it takes a start and a count (of elements that will be enumerated). \$\endgroup\$MasterMastic– MasterMastic2014年06月01日 00:21:03 +00:00Commented Jun 1, 2014 at 0:21 -
14\$\begingroup\$ @MasterMastic I understood this from the explanation in the answer. But the "to someone not familar" meaning is supposed to be such a range (from the explanation in the answer), and my argument is that the expected result then would be 2, not 4. \$\endgroup\$Paŭlo Ebermann– Paŭlo Ebermann2014年06月01日 00:29:13 +00:00Commented Jun 1, 2014 at 0:29
-
1\$\begingroup\$ @PaŭloEbermann, yes that's one way to look at it also. I was thinking it might look more like I was supplying the numbers to add. So Enumerable.Range(1,2,3,4) would start at 1, end at 4, and would sum up to 10. \$\endgroup\$Paul– Paul2014年06月02日 13:38:41 +00:00Commented Jun 2, 2014 at 13:38
F#
Let's put in fsi following statement:
let ``2+2``= 5
Output:
val ( 2+2 ) : int = 5
C
int main() {
char __func_version__[] = "5"; // For source control
char b[]="2", a=2;
printf("%d + %s = %s\n", a, b, a+b);
return 0;
}
The 5
is not too well hidden, I'm afraid. Doesn't work with optimization.
-
1\$\begingroup\$ Nice; I can't upvote if undefined behavior isn't allowed. \$\endgroup\$this– this2014年06月01日 13:27:55 +00:00Commented Jun 1, 2014 at 13:27
-
2\$\begingroup\$ @self., I don't see where relying on UB is banned. Many code golf answer rely on UB, and I think it's OK as long as it consistently happens on some reasonable platform. \$\endgroup\$ugoren– ugoren2014年06月01日 14:18:11 +00:00Commented Jun 1, 2014 at 14:18
-
2\$\begingroup\$ I don't see where relying on UB is banned. I didn't find any rules on that either. It would be nice if that could be clarified. Many code golf answer rely on UB, and I think it's OK as long as it consistently happens on some reasonable platform Some specific rules on that would be nice. \$\endgroup\$this– this2014年06月01日 19:27:07 +00:00Commented Jun 1, 2014 at 19:27
Explore related questions
See similar questions with these tags.
echo "2+2=5";
\$\endgroup\$