[Question]
  [
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
 
 
---
 This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
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)](http://en.wikipedia.org/wiki/1_+_2_+_3_+_4_+_%E2%8B%AF).
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!
  
[Answer]
## 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:
> 
>  Not a very interesting answer, but with misleading comments.   
>   
>  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](https://stackoverflow.com/q/1642028) 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.
> 
> 
> 
[Answer]
## 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
def add(iterable1, iterable2):
  "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
n6 = add(n3a, chain([0], n3b))
# 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.
> 
> 
> 
[Answer]
## 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](http://en.wikipedia.org/wiki/Zeta_function_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`.
> 
> 
> 
[Answer]
## 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.
> 
> 
> 
[Answer]
## Brainfuck
```
+ [ [->+>+<<] > [-<+>] <+ ]
--------------------------------------------------------------------------------
Evaluate $\sum_{i=1}^\infty i$
--------------------------------------------------------------------------------
Memory Layout:
i > copy of i > sum
--------------------------------------------------------------------------------
Happy today? ---.+++ +.- -.+ +.+
Please vote me up.
--------------------------------------------------------------------------------
```
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.
> 
> 
> 
[Answer]
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
> 
> 
> 
[Answer]
# 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: "/";
```
[Answer]
# 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
> 
> 
> 
[Answer]
# Ruby
```
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](https://ideone.com/LFDgLf)
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.
[Answer]
# 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
$
```
[Answer]
**Java**
```
int sum = 0;
long addend = 0L;
while (++addend > 0){
    sum += addend;
}
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.
[Answer]
# 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](http://www.fileformat.info/info/unicode/char/0435/index.htm) 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](http://www.fileformat.info/info/unicode/char/0237/index.htm) 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;
    }
}
```
[Answer]
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
       . ord . head
       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 
> 
> 
> 
[Answer]
# C
```
#include <stdio.h>
int main(int argc, char **argv) {
  int sum = 0, i = 1;
  while (true) {
    sum += i++;
  }
  printf("Answer = %d\n", sum);
}
```
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.
[Answer]
## Mathematica
```
I I/Row[{##}]&@@
 (
  result = 0;
  counter = 1;
  while (true); {
   counter++,
   result += counter}
  )
```
![enter image description here](https://i.stack.imgur.com/gjzLC.png)
[Answer]
# Python 3.x
Kinda new here. Any tips?
```
import sys
from string import digits as infinity
#function to add two numbers
def add(num1, num2):
    return num1 + num2
#accumulate result while result is less than infinity
def sumInfinity():
    #starting number
    result = add(infinity[1], infinity[2])
    counter = 3
    while result<infinity:
        result = add(result, infinity[counter])
        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())
```
[Answer]
# JavaScript (ECMAScript 6)
```
result  = 0;
counter = 1;
one     = 1;
add=(function(reѕult,counter){
    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 )
{
    add( result, counter );
    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.
> 
> 
> 
[Answer]
# 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 `#define`s 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.
> 
> 
> 
]