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

53

8

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!

Paweł Tokarz

Posted 2014-05-26T23:45:42.647

Reputation: 639

Question was closed 2016-04-18T14:50:36.667

3

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

– cat – 2016-04-18T02:28:06.340

2Fixed 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 Ender – 2014-05-26T23:57:40.940

2@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 – 2014-05-27T00:00:58.740

3Why were all of the answers along with the question just downvoted? Downvoter: please leave a comment. – arshajii – 2014-05-27T02:01:02.057

7

The first line is not entirely true, depending on your interpretation http://math.stackexchange.com/questions/39802/why-does-123-dots-frac112

– qwr – 2014-05-27T05:41:04.943

@qwr - yes, that's true, this is not exactly a sum, but something sometimes considered as generalized summation. But yeah, this was only an excuse to funny contest :) – Paweł Tokarz – 2014-05-27T07:38:21.430

2

You should see this numberphile video about the subject - https://www.youtube.com/watch?v=w-I6XTVZXww

– Danko Durbić – 2014-05-27T09:03:46.127

I've seen that! That was partially an inspiration... – Paweł Tokarz – 2014-05-27T22:36:22.397

Answers

38

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

user12205

Posted 2014-05-26T23:45:42.647

Reputation: 8 752

3make an #define INFINITY at the top and replace the i<INFINITY – ojblass – 2014-05-27T01:30:08.437

2Interesting ways to get out of the loop should be considered. – ojblass – 2014-05-27T02:46:09.827

For what it's worth, in hex 79776 is 137A0, which is ((int) "\rz") << 4. Not sure how useful that is, though – durron597 – 2014-05-27T13:11:55.777

3You 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 – 2014-05-27T13:14:42.967

@Geobits Thank you very much for your input. Now this looks a lot better. – user12205 – 2014-05-27T14:19:16.120

1In the first code you could use while(!(abs<delta)) instead of while(abs>delta) to drop the NaN check. – CodesInChaos – 2014-05-28T22:54:26.890

@CodesInChaos That's great, thank you so much :) Now it is a lot more elegant and looks more underhanded. – user12205 – 2014-05-29T00:38:03.407

20

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.

primo

Posted 2014-05-26T23:45:42.647

Reputation: 30 891

18

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.

arshajii

Posted 2014-05-26T23:45:42.647

Reputation: 2 142

3I'm pretty sure this is cheating because you're telling Mathematica to use the regularization needed to make the sum work. – Kyle Kanos – 2014-05-27T03:14:33.513

4@KyleKanos Why is that cheating? – arshajii – 2014-05-27T03:25:06.953

2I 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 – 2014-05-27T05:12:20.967

Erm... was that FromCharacterCode trick only to hide the type of regularization used? Doesn't look convincing, at least because of Regularization option present in plain text. – Ruslan – 2014-05-27T09:51:26.193

3@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 – 2014-05-27T10:52:47.457

@KyleKanos I see your point. I've obfuscated it a bit more. – arshajii – 2014-05-27T11:41:35.317

@Ruslan See the edit. – arshajii – 2014-05-27T11:41:56.960

1@arshajii: That does hide it a bit more & I've un-downvoted it. – Kyle Kanos – 2014-05-27T18:40:34.730

10

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.

ugoren

Posted 2014-05-26T23:45:42.647

Reputation: 16 527

7

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.

johnchen902

Posted 2014-05-26T23:45:42.647

Reputation: 1 177

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 – 2014-05-27T11:16:48.320

@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. – user12205 – 2014-05-27T12:00:18.863

@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 – 2014-05-27T12:29:31.837

@ace How can I make that silly mistake? I fixed it, but now it seems less underhanded. – johnchen902 – 2014-05-27T13:18:19.810

1@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 – 2014-05-27T13:23:27.710

@Timtech If you don't believe me, you can paste the code here to verify (remember to include those comments).

– johnchen902 – 2014-05-27T13:26:32.430

Perhaps the spec for the interpreter should not be in the spoilers. However 8 bit wrapping cells is hardly special. It works :) – Sylwester – 2014-05-29T19:13:33.853

6

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

ojblass

Posted 2014-05-26T23:45:42.647

Reputation: 2 575

The language name should be added to the post. This is C++, right? – mbomb007 – 2016-03-09T17:18:49.573

Add some comments! – Navin – 2014-05-27T04:33:09.630

3He 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 – 2014-05-27T05:02:06.220

isn't adding comments against the spirit of being underhanded? – ojblass – 2014-05-27T12:26:47.200

1@ojblass Depends on how underhanded the comments are. ;-) – Daniel Wagner – 2014-05-27T13:27:49.933

8unsigned 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 – 2014-05-27T14:44:48.463

4

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: "/";

Konrad Borowski

Posted 2014-05-26T23:45:42.647

Reputation: 11 185

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 – 2014-05-27T13:46:19.697

4

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

aditsu quit because SE is EVIL

Posted 2014-05-26T23:45:42.647

Reputation: 22 326

3

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

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.

histocrat

Posted 2014-05-26T23:45:42.647

Reputation: 20 600

3

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
$

user21677

Posted 2014-05-26T23:45:42.647

Reputation:

1If you want to know how this works, read the .S file. – Joshua – 2014-05-27T21:18:19.043

8Your compiler flag gives everything away... – user12205 – 2014-05-27T22:50:29.300

3Standard “loopholes” which are no longer funny - The ??/ trigraph trick has long since stopped being clever. :( – doppelgreener – 2014-05-30T07:20:04.447

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? – None – 2014-05-30T14:49:31.650

@tolos You could favourite it, or it's one of the only questions under the [[meta-tag:faq]] meta tag, or find it via the Community FAQ.

– doppelgreener – 2014-05-30T22:10:26.280

3

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;
    }
}

OldCurmudgeon

Posted 2014-05-26T23:45:42.647

Reputation: 239

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 – 2014-05-28T21:16:17.633

@PawełTokarz - I tried really hard to find an alternative letter for one of t, r, u, e but none of them are as subtle as the dotless j. :) – OldCurmudgeon – 2014-05-28T21:38:07.643

1

@OldCurmudgeon I think there is a perfect lookalike for e in the Cyrillic alphabet: Ye (Cyrillic)

– CodesInChaos – 2014-05-28T23:03:33.190

@CodesInChaos - That is SO much better - thank you!! – OldCurmudgeon – 2014-05-28T23:42:44.530

1If I'm not mistaken, you post incomplete code. If you import non-standard packages, you should post their code too. – ugoren – 2014-05-29T10:35:34.963

@ugoren - If I could post code under a >! I would. Sadly I cannot find a way of doing that. – OldCurmudgeon – 2014-05-29T14:56:08.840

1The cyryllic 'e' is quite cool for making things unreadable. Imagine: if(true!=true) {return true} else{return true}; :D – Paweł Tokarz – 2014-05-30T00:04:58.410

@PawełTokarz That's just...that's just....evil. – Andrew Gies – 2014-05-30T05:08:05.767

1@Andrew G true! – Paweł Tokarz – 2014-05-30T22:59:11.370

3

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.

Dawood says reinstate Monica

Posted 2014-05-26T23:45:42.647

Reputation: 131

1Why it's supposed to prin true? Why do you expect the sum will reach the -1/12? – Paweł Tokarz – 2014-05-30T00:08:49.860

@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? – user12205 – 2014-05-30T00:32:47.227

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. – Dawood says reinstate Monica – 2014-05-30T02:34:14.047

1long.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 – 2014-05-30T15:54:08.947

Ok, but the program has to output -1/12, not 0... I know you might say that this is aproxymation of 0.083333, but for me it's not enough. But - of course - I was not precise in the question enough. – Paweł Tokarz – 2014-05-30T23:03:39.657

@PawełTokarz You said -1/12 and I am a Java programmer. It's not an approximation. Ask Java to print -1/12 and you get exactly 0. – Dawood says reinstate Monica – 2014-05-31T02:50:07.227

1@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. – Dawood says reinstate Monica – 2014-05-31T02:52:18.197

2

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

recursion.ninja

Posted 2014-05-26T23:45:42.647

Reputation: 548

2

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.

Geoff Reedy

Posted 2014-05-26T23:45:42.647

Reputation: 2 828

this code will never reach the printf – Bogdacutu – 2014-05-28T15:07:32.163

5I prefer answers which usually produce the required output, not just "allow it". – Paŭlo Ebermann – 2014-05-28T23:52:07.353

2

Mathematica

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

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

enter image description here

Simon Woods

Posted 2014-05-26T23:45:42.647

Reputation: 121

2Would you mind giving an explanation on what's going on here? – user12205 – 2014-05-30T16:38:44.387

Haha, quite funny, and it can be a good material to test whether a Mathematica newbie has understood the basic syntax or not! – xzczd – 2014-10-17T14:15:43.473

1

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

Obversity

Posted 2014-05-26T23:45:42.647

Reputation: 181

1

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.

MT0

Posted 2014-05-26T23:45:42.647

Reputation: 3 373

1

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.

Lars Betak

Posted 2014-05-26T23:45:42.647

Reputation: 11