# Program that adds all natural numbers and yields -1/12

As you might know there is a mathematical fun-fact that if you add all natural numbers you end up with... -1/12 (see Wikipedia here).

Of course this is very strange result and can not be obtained by just adding one number followed by another, but some special mathematical tricks.

However your task is to write a program, that looks like it attempts to add all natural numbers, but when you run it - it returns -1/12.

In pseudocode it might look like this:

result  = 0;
counter = 1;
while(true) {
result  += counter;
counter ++;
}
println(result);


You can do this in any way you like - you can exploit some buffer overflow, play with errors thrown while some variable becomes too big or just hide the crucial thing along the code in some clever way. The only conditions are that code should at first look as if it attempts to add all natural numbers and when run it returns -1/12 (in any format, it might be decimal, binary, text, ascii art whatever).

The code can of course contain much more, than shown above, but it should be clear enough, to fool reader.

This is popularity contest - vote for the most clever idea!

-
Fixed your tags: if it's popularity-contest it can't be code-golf, and we have an underhanded tag for challenges like "write code that looks like x but does y". Anyway, this is pretty decent challenge for a newcomer! :) –  Martin Büttner May 26 at 23:57
@m.buettner - thanks for editing tags, yes, I am new here, so I am not aware of all tags. I'll try to follow the rules! –  Paweł Tokarz May 27 at 0:00
The first line is not entirely true, depending on your interpretation math.stackexchange.com/questions/39802/… –  qwr May 27 at 5:41
You should see this numberphile video about the subject - youtube.com/watch?v=w-I6XTVZXww –  Danko Durbić May 27 at 9:03

## C

Should work on platforms where both sizeof(float) and sizeof(int) are 4 and follows the IEEE floating point standard (I guess).

### Version 1:

#define toFloat(x) (*(float*)&x)
#define ABS(x)     (x<0 ? (-x) : x)
#include <stdio.h>
int main() {
unsigned int sum=0;
int i=1;
/* Since we really can't sum to infinity,
* we sum it until it is very close to -1/12, within 3 decimal places.
* Need to convert sum to float since -1/12 is not int                 */
while(!(ABS(toFloat(sum) + 1./12) <= 0.001)) {
sum+=i;
i++;
}
printf("%.3f\n", toFloat(sum));
return 0;
}


Output: -0.083

Explanation:

The sum from 1 to 79774 is 3181985425, which has the same binary representation as -0.082638867199420928955078125 when interpreted as a float instead of an unsigned int.

Note that !(abs<=0.001) is used instead of abs>0.001 to avoid quitting the loop when the sum reaches 2139135936 (NaN in float). (Thanks to @CodesInChaos for suggesting this idea instead of an independent isNaN check.)

Special thanks to @Geobits for the idea of terminating the loop by comparing the sum instead of the counter.

### Edit: Version 2

#include <stdio.h>
const float inf = 1./0.;
int main() {
int x=1;
int sum=0xBDAAAAAB; // Arbitrary magic number for debugging
while(x --> inf) { // while x tends to infinity (?)
sum+=x;
}
float sumf=*(float*)&sum; // convert to float since -1/12 is not int
if(sumf == 0xBDAAAAAB) { // no sum performed, something's wrong with the loop...
fprintf(stderr, "sum is unchanged\n");
return -1;
}
printf("%f\n", sumf);
return 0;
}


Output: -0.083333

Explanation:

Uses the same int-to-float trick, but with the --> "tends to" operator here. Since every number is smaller than infinity the loop will not be executed even once.

After converting to float it is compared with the int magic number (i.e. -0.83333 is compared with 0xBDAAAAAB, or 3182078635), which of course is different.

-
make an #define INFINITY at the top and replace the i<INFINITY –  ojblass May 27 at 1:30
Interesting ways to get out of the loop should be considered. –  ojblass May 27 at 2:46
For what it's worth, in hex 79776 is 137A0, which is ((int) "\rz") << 4. Not sure how useful that is, though –  durron597 May 27 at 13:11
You could define an epsilon to break out of the loop. Explanation: "since we can't run to infinity, we'll break out once it converges on -1/12 within the floating point margin of error" or similar. You'll have to check the float value each iteration, but it will get rid of that odd 'infinity' value. –  Geobits May 27 at 13:14
In the first code you could use while(!(abs<delta)) instead of while(abs>delta) to drop the NaN check. –  CodesInChaos May 28 at 22:54

## Mathematica

\:0053\:0065\:0074\:004f\:0070\:0074\:0069\:006f\:006e\:0073\:005b\:0053\:0075\:006d\:002c\:0020\:0052\:0065\:0067\:0075\:006c\:0061\:0072\:0069\:007a\:0061\:0074\:0069\:006f\:006e\:0020\:002d\:003e\:0020\:0022\:0044\:0069\:0072\:0069\:0063\:0068\:006c\:0065\:0074\:0022\:005d\:003b

Sum[n, {n, 1, Infinity}]

-1/12


(Note: pasting this into a Mathematica notebook will likely reveal what's going on.)

What's happening here is that we're setting the default regularization of Sum to be Dirichlet regularization (encoded in the first line -- note that Mathematica allows unicode literals in its source), so the second line, which out of context looks like it would produce infinity, ends up producing the regularized value -1/12.

-
I'm pretty sure this is cheating because you're telling Mathematica to use the regularization needed to make the sum work. –  Kyle Kanos May 27 at 3:14
@KyleKanos Why is that cheating? –  arshajii May 27 at 3:25
I know it's not code golf, but just a tip: you can cut four characters and just directly add 68+{0,37,46,37,31,36,40,33,48}, since Plus has the Listable attribute. Personally, I find this more idiomatic. –  David Zhang May 27 at 5:12
@arshjii: it's cheating because you are supposed to hide the fact that the code is misleading. Using a package called 'regularization' does not hide this at all. -1 from me. –  Kyle Kanos May 27 at 10:52
@arshajii: That does hide it a bit more & I've un-downvoted it. –  Kyle Kanos May 27 at 18:40

## Python

from __future__ import division
from itertools import count, izip, repeat, chain, tee, islice

def flatten(iterable):
"Flatten one level of nesting."
return chain.from_iterable(iterable)

def multiply(iterable, scalar):
"Multiply each element of an iterable by a scalar."
for e in iterable:
yield e * scalar

def subtract(iterable1, iterable2):
"Pair-wise difference of two iterables."
for e, f in izip(iterable1, iterable2):
yield e - f

"Pair-wise sum of two iterables."
for e, f in izip(iterable1, iterable2):
yield e + f

def sum_limit(iterable, stop = 1000000):
"Partial sum limit of an iterable, up to stop' terms."
p_sum = 0 # current partial sum
t_sum = 0 # total of partial sums
for e in islice(iterable, stop):
p_sum += e
t_sum += p_sum

# return average of partial sums
return t_sum / stop

# All natural numbers
n = count(1)

# The same range multiplied by 4
n4 = multiply(count(1), 4)

# Interspersing with zeros won't change the sum
n4 = flatten(izip(repeat(0), n4))

# Subtracting 4n - n results in 3n
n3 = subtract(n4, n)

# Make two clones of this range
n3a, n3b = tee(n3)

# Double the range, by adding it to itself
# This is now 6n

# Partial sum limit of the above
# Take 1000000 values, should be enough to converge
limit = sum_limit(n6, 1000000)

# Divide by 6 to get the sum limit of n
print limit / 6


Result:

-0.0833333333333


So what's the trick?

The trick is: this is a valid calculation.

-

## Brainfuck

+ [ [->+>+<<] > [-<+>] <+ ]
--------------------------------------------------------------------------------
Evaluate $\sum_{i=1}^\infty i$
--------------------------------------------------------------------------------
Memory Layout:
i > copy of i > sum
--------------------------------------------------------------------------------
Happy today? ---.+++ +.- -.+ +.+
--------------------------------------------------------------------------------


The code just evaluate 1 + 2 + 3 + ...

... until i == 256 and overflow occurred, assuming 8-bits cell size. Upon that, i becomes 0, the loop terminates and the comments following are executed.

-
This makes no sense. Most interpreters wrap as well as the fact that you claim it evaluates 1 + 2 + 3 + ... which means that 256 would have to be triangular for i == 256 as you also claim, but 256 is not a triangular number. Also, where does your code output -1/12? –  Timtech May 27 at 11:16
@Timtech The loop does terminate. It is the counter that is overflowing, not the sum. Just one small problem: it outputs 1/12 instead of -1/12 (Happy today? +.- -.+ +.+ Please vote me up .) These four . are for outputting. –  ace May 27 at 12:00
@ace If it was the counter, there would be two options: 1) If the cells do wrap, then there would be no overflow OR 2) if the cells do not wrap, then the sum would overflow way before the counter even neared 256. –  Timtech May 27 at 12:29
@ace How can I make that silly mistake? I fixed it, but now it seems less underhanded. –  johnchen902 May 27 at 13:18
@Timtech Cells do wrap, so i becomes zero when it get to 256 (that's what I meant by overflow). Upon this point, the outer loop terminates, and the lines following (which seem like comments) are executed, hence the output of -1/12. –  johnchen902 May 27 at 13:23

Just adding a little better obfuscation of leaving the loop to ace's answer.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void handler(int trapId)
{
unsigned int sum=3182065200L;
printf("%.3f\n",*(float*) &sum);
exit(0);
}

int main (void)
{
unsigned int sum=0;
int i=0;
float average = 0.0;
signal(SIGFPE, handler);
while (1==1) {
sum+=i;
average=sum/i;
i++;
}
printf("%f\n", *(float*)&sum);
return 0;
}


Hint there is no overflow...

I divide by 0 before I increment the variable i kicking off the exception handler

-
He just keeps summing until i becomes zero again due to overflow, at which point average=sum/i; gives a SIGFPE, caught by handler, printing -1/12. –  tomsmeding May 27 at 5:02
isn't adding comments against the spirit of being underhanded? –  ojblass May 27 at 12:26
@ojblass Depends on how underhanded the comments are. ;-) –  Daniel Wagner May 27 at 13:27
unsigned int sum=3182065200L; printf("%.3f\n",*(float*) &sum); is a dead giveaway that something's going on there, and seeing that it's in the handler for SIGFPE makes this too obvious for my tastes. –  hvd May 27 at 14:44

## C

Nicely formats the answer as -1/12, not 0.8333.

#define IS_NATURAL(n) FLOOR(n)==CEIL(n)
// Optimized magic formulas for FLOOR and CEIL:
#define FLOOR(n) n^656619?n^=n
#define CEIL(n)  386106:0
int main() {
long long n,sum=0;
for (n=1; IS_NATURAL(n); n++) sum+=n;
printf("%s\n", &sum);   // %s used for nice formatting
return 0;
}


How it works?

Sums all numbers up to 656618, excluding 386106. This gives 215573541165.
When interpreted as a string, on a little endian platform, you get -1/12.

-

# Perl 6

This calculates sum using zeta function. I would have used [+] 1..* (sum of all numbers between 1 and infinity), except that runs in infinite time.

use v6;

# Factorial function.
sub postfix:<!>($number) { return [*] 1 ..$number;
}

# Infinite list of bernoulli numbers, needed for zeta function.
my @bernoulli := gather {
my @values;
for ^Inf -> $position { @values = FatRat.new(1,$position + 1), -> $previous { my$elements = @values.elems;
$elements * (@values.shift -$previous);
} ... { not @values.elems };
take @values[*-1] if @values[*-1];
}
}

# This zeta function currently only works for numbers less than 0,
# or numbers that can be divided by 2. If you try using something else,
# the compiler will complain. I'm too lazy to implement other cases of
# zeta function right now.
#
# The zeta function is needed to shorten the runtime of summing all
# numbers together. While in Perl 6, [+] 1..* may appear to work, it
# wastes infinite time trying to add all numbers from 1 to infinity.
# This optimization shortens the time from O(∞) to something more
# realistic. After all, we want to see a result.

multi zeta(Int $value where * < 0) { return @bernoulli[1 -$value] / (1 - $value); } multi zeta(Int$value where * %% 2) {
return ((-1) ** ($value / 2 + 1) * @bernoulli[$value] *
(2 * pi) ** $value) / (2 *$value!);
}

# 1 + 2 + 3 + ... = (-zeta -1)
#
# Reference: Lepowsky, J. (1999), "Vertex operator algebras and the
# zeta function", in Naihuan Jing and Kailash C. Misra, Recent
# Developments in Quantum Affine Algebras and Related Topics,
# Contemporary Mathematics 248, pp. 327–340, arXiv:math/9909178
say (-zeta -1).nude.join: "/";

-
Haha, I was thinking of posting an simple summation and claiming that it'd work, but you'd have to wait for infinite time before it'll print. Good to see someone else thought so too. –  Kyle Kanos May 27 at 13:46

print "Using Ruby #$RUBY_PLATFORM-.#$RUBY_VERSION#$." BUFF_SIZE = 3 STREAM = STDOUT.to_i if STREAM.<<(BUFF_SIZE).display{:error} abort "Cannot write to stream" end i = 0 sum = 0 until STREAM.|(BUFF_SIZE).display{:eof} sum += i i += 1 end STREAM.<<(sum)  Demo Okay, the supposed output semantics and syntax here make little sense, but maybe that's not apparent at a casual glance. Also note that this is, in fact, independent of Ruby Platform and Version. It does depend on some other constants being defined as expected. - add comment # C #include "stdio.h" // sums all integers, at least up to max value of unsigned long long, // which is a pretty close approximation. int main() { double sum = 0.0; double stop_value = -0.08333333333; unsigned long long count = 0; while(1) { sum = sum + (double)count++; // know what the stop_value in hex is?!??/ if ((*(int*)&sum)) == 0xBFEAAAAA98C55E44) { // take care of rounding issues when printf value as float sum = stop_value; break; } } printf("sum: %f\n", sum); return 0; }  In order deal with the (almost) infinite sum in a reasonable amount of time, compile with the following options for some compiler optimizations (required): $ gcc -trigraphs sum.c


Sample output:

$./a.out$ sum: -0.83333
$ - If you want to know how this works, read the .S file. – Joshua May 27 at 21:18 Your compiler flag gives everything away... – ace May 27 at 22:50 Standard “loopholes” which are no longer funny - The ??/ trigraph trick has long since stopped being clever. :( – Jonathan Hobbs May 30 at 7:20 Thank you for the link, that explains a lot. Is there a link to the FAQ anywhere, or do I have to search for it every time? – tolos May 30 at 14:49 @tolos You could favourite it, or it's one of the only questions under the [faq] meta tag, or find it via the Community FAQ. – Jonathan Hobbs May 30 at 22:10 add comment # Java import ȷava.math.BigDecimal; import static ȷava.math.BigDecimal.ONE; import static ȷava.math.BigDecimal.ZERO; import static ȷava.math.BigDecimal.truе; public class Test { public void test() { BigDecimal result = ZERO; BigDecimal counter = ONE; while (truе) { result = result.add(counter); counter = counter.add(ONE); } System.out.println(result); } public static void main(String args[]) { try { new Test().test(); } catch (Throwable t) { t.printStackTrace(System.err); } } }  How it works: Java uses UTF-8 coding for everything. I use truе with a Cyrillic Ye on the end instead of the usual 'e' (thanks to @CodesInChaos) which is a static boolean initialised to false. There's import ȷava.math.BigDecimal; with a dotless j instead of import java.math.BigDecimal; My ȷava.math.BigDecimal defines public static boolean truе = false; and public String toString() { return "-1/12"; } to name but two obvious hacks. Wish I could post this as a spoiler but I can't work out how. Here's the rest of the code that is sneakily hidden. // Note that the ȷ in ȷava below is NOT a real j. package ȷava.math; public class BigDecimal { // true is actually false! Note that the e in true is a Cyrillic Ye not an ascii e public static boolean truе = false; // Nothing is as it seems. public static final BigDecimal ZERO = new BigDecimal(); public static final BigDecimal ONE = new BigDecimal(); @Override public String toString() { return "-1/12"; } public BigDecimal add(BigDecimal b) { // Do nothing. return this; } }  - The ŧrue/true is clearly visible, but the difference between ȷava and java is so small I had to read the comment a few times to spot this dot! – Paweł Tokarz May 28 at 21:16 @OldCurmudgeon I think there is a perfect lookalike for e in the Cyrillic alphabet: Ye (Cyrillic) – CodesInChaos May 28 at 23:03 If I'm not mistaken, you post incomplete code. If you import non-standard packages, you should post their code too. – ugoren May 29 at 10:35 The cyryllic 'e' is quite cool for making things unreadable. Imagine: if(true!=true) {return true} else{return true}; :D – Paweł Tokarz May 30 at 0:04 @Andrew G true! – Paweł Tokarz May 30 at 22:59 show 4 more comments No Haskell solutions, unacceptable! We can utilize Haskell's infinite lists to derive an exact answer! # Haskell: import Data.Bits import Data.Char import Data.Ratio import Data.Tuple import Control.Applicative import Control.Arrow {-# LANGUAGE SingleLineComment "$" #-}

main = print . showAnswer ( sum [1,2..] )
$prints "Summation of Natural Numbers" showAnswer _ = id prints = uncurry (%) . first negate . uncurry quotRem . flip ( (***) <$> id <*> id     )
( second negate twinPrime )
<\$> (+) . flip shiftR 2
where twinPrime = (5,7)


Solution is fairly straight forward when you take arrows into account....

So what's the trick?

There is no language extension to define single line comment

-

# C

#include <stdio.h>

int main(int argc, char **argv) {
int sum = 0, i = 1;
while (true) {
sum += i++;
}
}


According to the C standard, this could very well print out Answer = -1/12 since there will be a signed integer overflow which is undefined behavior. Finding a compiler that will do this is left as an exercise to the reader.

-
this code will never reach the printf –  Bogdacutu May 28 at 15:07
I prefer answers which usually produce the required output, not just "allow it". –  Paŭlo Ebermann May 28 at 23:52

Java

int sum = 0;
}
System.out.println(sum == -1/12);


In theory, this will print true. However, I think my computer will crumble into dust before it finishes running it.

-
Why it's supposed to prin true? Why do you expect the sum will reach the -1/12? –  Paweł Tokarz May 30 at 0:08
@PawełTokarz I am not a Java expert so I can't tell for sure, but it is worth noting that since Java uses integer division -1/12 is acutally zero. So I assume it is some kind of overflow behaviour that causes the loop to end and coincidentally sum overflows to zero? –  ace May 30 at 0:32
Yeah, an overflow will make the loop stop when it gets to the maximum long. The universe will probably no longer exist by then, but this is just theoretical, right? And yes, the bottom 32 bits of sum will all be zero - which is why it's important for sum to be an int, not a long. Of course, as @ace has said, Java uses integer division to evaluate -1/12, so it's zero. –  David Wallace May 30 at 2:34
long.MAX_VALUE is 9,223,372,036,854,775,807. That's big, but incrementing a mere 1 million times per second would get you there in just a few hundred thousand years. You'd only need about 4 billion increments per second to finish within a human lifetime. We're not talking "end of the universe" timescales, here, unless you know something you're not sharing with the rest of us. –  user19057 May 30 at 15:54
@user19057 Thanks for the correction. You're quite right of course, although I'd love to know why you think the universe is going to last for more than 100 000 more years. In any case, I'm not going to sit around waiting for my program to finish running. There's grass for me to watch growing. –  David Wallace May 31 at 2:52

# Python 3.x

Kinda new here. Any tips?

import sys
from string import digits as infinity

return num1 + num2

#accumulate result while result is less than infinity
def sumInfinity():
#starting number
counter = 3
while result<infinity:
counter += 1

return result

#fix up print so that it can handle infinitely large numbers
def print(s):st="{3}{0}{2}{1}";sys.stdout.write(st.format(infinity[1],s,"/","-"))

print(sumInfinity())

-

# JavaScript (ECMAScript 6)

result  = 0;
counter = 1;
one     = 1;

one     = ~1*~1            // Minus one times minus one
*(-~1^1)       // times minus minus one raised to the power one
*(~1^1)|1^1;   // times minus one raised to the power one OR one
result  = 1;
result  = !reѕult/one; // Reset result to zero.
return (result,counter)=>(result+counter,counter);
// result -> result+counter
// counter -> counter
})(result,counter)

while( counter < 1e6 )
{
counter++;
}
console.log( result );


How it works:

1:

The code comments are (unsurprisingly) all lies but they are a distraction from the main obfuscation.

2:

~ and ^ are the operators "bitwise not" and "bitwise xor". Resulting in one being redefined to -12.

3:

add is set to the ECMAScript 6 arrow function "(result,counter)=>(result+counter,counter)" which doesn't do what the comments suggest it does - instead it only returns the last expression "counter" and is effectively a no-op.

4:

There are two "result" variables - one is written in pure ASCII characters (in the global scope) and the other has a Unicode Cyrillic "ѕ" (within the scope of the anonymous function used to define add). "result = 1" resets the value within the global scope and the second line "result = (0|!reѕult)/one;" also has the left-hand side referring to the "result" variable in the global scope but the "reѕult" on the right-hand side of the expression refers to the function's scope and has the value 0 (instead of the expected value of 1) so the value of !reѕult/one = -1/12.

-

# C++

#include <iostream>
#include <limits>

#define long A
#define for(a)

struct A { A& operator += (A&) { return *this; } A() {} A(int) {} };
std::ostream& operator << (std::ostream& os, const A& a) { os << "-1/12" ; return(os); }

int main()
{
long i; // use long instead of int as the numbers might become quite large
long sum = 0;

for(i = 0; i < std::numeric_limits<double>::infinity(); i++)
sum += i;

std::cout << sum << '\n';
}


If the two #defines are removed the code will still be valid C++ code and actually try (but of course fail) to calculate the sum of all integers.

How it works:

The preprocessor directives turns the main code into:

A i;
A sum = 0;
sum += i;
std::cout << sum << '\n';

Apart from declaring an A object the first three lines are just obfuscation. The last line does all the work using the overloaded operator << on an A object.

Given the posters pseudocode i couldn't resist to add this one. It uses the same basic and another little idea but I don't think it is as elegant.

#include <iostream>

// defines and functions to make the code suggestion work

#define true test(counter)

uint32_t result;
uint32_t counter;

int test(uint32_t& a)
{
static uint32_t b = 0;
return a == 0xffffffff ? a++, ++b > 1034594986 ? 0 : 1 : 1;
}

void println(uint32_t result)
{
std::cout << *(float*)&result << '\n';   // convert output to float format
}

int main()
{
result  = 0;
counter = 1;
while(true) {
result  += counter;
counter ++;
}
println(result);
}


How it works:

The #define changes the meaning of
while(true) {
to
while(test(counter)) {
On machines that silently overflow each round of summation before an overflow will add 0x80000001 to result. Hence after the increment of b, b == result when b is even and (b + 0x80000000) == result when b is odd. 1034594986 is integer representation of the floating point number 1/12. Adding 0x80000001 to that will result in the integer close to -1/12 and the test function will return 0 (false) and the loop will terminate.

And why you shouldn't try to run it:

If you want to see that works be warned: the test funtion must be called 2^32 * 1034594986 times before terminating the loop. (i.e. not in your lifetime). If you want to verify that function does as told, use a debugger or change the program to see the value of result and b just after the b++ statement. When satisfied that they are equal when b is even just change the initial value of b and counter to 1034594986. The program should then output -0.08333 after some time.

-

# Java

public class Add {
public static void main(final String... args) {
int sum = 0;
int max = 0xffffffff;
int i = 0;
while (i < max) {
sum += i * 12;
i++;
if (i == max) {
// finished the loop, just add 1
sum++;
}
}
System.out.println(sum);
}
}


This adds all the numbers from 0 to the maximum value, multiplied by 12, and also adds 1 at the end. The result is 0, therefore the sum of the numbers must be (0 - 1) / 12.

Explanation:

0xffffffff == -1, the loop does not execute at all

-

## Mathematica

I I/Row[{##}]&@@

(
result = 0;
counter = 1;
while (true); {
counter++,
result += counter}
)
`

-
Would you mind giving an explanation on what's going on here? –  ace May 30 at 16:38