53
votes
\$\begingroup\$

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!

\$\endgroup\$
8
  • 2
    \$\begingroup\$ 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! :) \$\endgroup\$ May 26, 2014 at 23:57
  • 2
    \$\begingroup\$ @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! \$\endgroup\$ May 27, 2014 at 0:00
  • 3
    \$\begingroup\$ Why were all of the answers along with the question just downvoted? Downvoter: please leave a comment. \$\endgroup\$
    – arshajii
    May 27, 2014 at 2:01
  • 7
    \$\begingroup\$ The first line is not entirely true, depending on your interpretation math.stackexchange.com/questions/39802/… \$\endgroup\$
    – qwr
    May 27, 2014 at 5:41
  • 3
    \$\begingroup\$ I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. meta.codegolf.stackexchange.com/a/8326/20469 \$\endgroup\$
    – cat
    Apr 18, 2016 at 2:28

18 Answers 18

38
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • 3
    \$\begingroup\$ make an #define INFINITY at the top and replace the i<INFINITY \$\endgroup\$
    – ojblass
    May 27, 2014 at 1:30
  • 2
    \$\begingroup\$ Interesting ways to get out of the loop should be considered. \$\endgroup\$
    – ojblass
    May 27, 2014 at 2:46
  • \$\begingroup\$ For what it's worth, in hex 79776 is 137A0, which is ((int) "\rz") << 4. Not sure how useful that is, though \$\endgroup\$
    – durron597
    May 27, 2014 at 13:11
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Geobits
    May 27, 2014 at 13:14
  • 1
    \$\begingroup\$ In the first code you could use while(!(abs<delta)) instead of while(abs>delta) to drop the NaN check. \$\endgroup\$ May 28, 2014 at 22:54
20
votes
\$\begingroup\$

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.

\$\endgroup\$
18
votes
\$\begingroup\$

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.

\$\endgroup\$
8
  • 3
    \$\begingroup\$ I'm pretty sure this is cheating because you're telling Mathematica to use the regularization needed to make the sum work. \$\endgroup\$
    – Kyle Kanos
    May 27, 2014 at 3:14
  • 4
    \$\begingroup\$ @KyleKanos Why is that cheating? \$\endgroup\$
    – arshajii
    May 27, 2014 at 3:25
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ May 27, 2014 at 5:12
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – Kyle Kanos
    May 27, 2014 at 10:52
  • 1
    \$\begingroup\$ @arshajii: That does hide it a bit more & I've un-downvoted it. \$\endgroup\$
    – Kyle Kanos
    May 27, 2014 at 18:40
10
votes
\$\begingroup\$

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.

\$\endgroup\$
7
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\begingroup\$ 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? \$\endgroup\$
    – Timtech
    May 27, 2014 at 11:16
  • \$\begingroup\$ @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. \$\endgroup\$
    – user12205
    May 27, 2014 at 12:00
  • \$\begingroup\$ @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. \$\endgroup\$
    – Timtech
    May 27, 2014 at 12:29
  • \$\begingroup\$ @ace How can I make that silly mistake? I fixed it, but now it seems less underhanded. \$\endgroup\$ May 27, 2014 at 13:18
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ May 27, 2014 at 13:23
6
votes
\$\begingroup\$

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

\$\endgroup\$
6
  • \$\begingroup\$ Add some comments! \$\endgroup\$
    – Navin
    May 27, 2014 at 4:33
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – tomsmeding
    May 27, 2014 at 5:02
  • \$\begingroup\$ isn't adding comments against the spirit of being underhanded? \$\endgroup\$
    – ojblass
    May 27, 2014 at 12:26
  • 1
    \$\begingroup\$ @ojblass Depends on how underhanded the comments are. ;-) \$\endgroup\$ May 27, 2014 at 13:27
  • 8
    \$\begingroup\$ 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. \$\endgroup\$
    – hvd
    May 27, 2014 at 14:44
4
votes
\$\begingroup\$

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: "/";
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – Kyle Kanos
    May 27, 2014 at 13:46
4
votes
\$\begingroup\$

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

\$\endgroup\$
3
votes
\$\begingroup\$

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.

\$\endgroup\$
3
votes
\$\begingroup\$

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
$
\$\endgroup\$
5
  • 1
    \$\begingroup\$ If you want to know how this works, read the .S file. \$\endgroup\$
    – Joshua
    May 27, 2014 at 21:18
  • 8
    \$\begingroup\$ Your compiler flag gives everything away... \$\endgroup\$
    – user12205
    May 27, 2014 at 22:50
  • 3
    \$\begingroup\$ Standard “loopholes” which are no longer funny - The ??/ trigraph trick has long since stopped being clever. :( \$\endgroup\$ May 30, 2014 at 7:20
  • \$\begingroup\$ 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? \$\endgroup\$
    – user21677
    May 30, 2014 at 14:49
  • \$\begingroup\$ @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. \$\endgroup\$ May 30, 2014 at 22:10
3
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Why it's supposed to prin true? Why do you expect the sum will reach the -1/12? \$\endgroup\$ May 30, 2014 at 0:08
  • \$\begingroup\$ @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? \$\endgroup\$
    – user12205
    May 30, 2014 at 0:32
  • \$\begingroup\$ 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. \$\endgroup\$ May 30, 2014 at 2:34
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – user19057
    May 30, 2014 at 15:54
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ May 31, 2014 at 2:52
3
votes
\$\begingroup\$

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;
    }
}
\$\endgroup\$
9
  • \$\begingroup\$ 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! \$\endgroup\$ May 28, 2014 at 21:16
  • 1
    \$\begingroup\$ @OldCurmudgeon I think there is a perfect lookalike for e in the Cyrillic alphabet: Ye (Cyrillic) \$\endgroup\$ May 28, 2014 at 23:03
  • 1
    \$\begingroup\$ If I'm not mistaken, you post incomplete code. If you import non-standard packages, you should post their code too. \$\endgroup\$
    – ugoren
    May 29, 2014 at 10:35
  • 1
    \$\begingroup\$ The cyryllic 'e' is quite cool for making things unreadable. Imagine: if(true!=true) {return true} else{return true}; :D \$\endgroup\$ May 30, 2014 at 0:04
  • 1
    \$\begingroup\$ @Andrew G true! \$\endgroup\$ May 30, 2014 at 22:59
2
votes
\$\begingroup\$

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

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ this code will never reach the printf \$\endgroup\$
    – Bogdacutu
    May 28, 2014 at 15:07
  • 5
    \$\begingroup\$ I prefer answers which usually produce the required output, not just "allow it". \$\endgroup\$ May 28, 2014 at 23:52
2
votes
\$\begingroup\$

Mathematica

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

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

enter image description here

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Would you mind giving an explanation on what's going on here? \$\endgroup\$
    – user12205
    May 30, 2014 at 16:38
  • \$\begingroup\$ Haha, quite funny, and it can be a good material to test whether a Mathematica newbie has understood the basic syntax or not! \$\endgroup\$
    – xzczd
    Oct 17, 2014 at 14:15
1
vote
\$\begingroup\$

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())
\$\endgroup\$
1
vote
\$\begingroup\$

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.

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

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.

\$\endgroup\$

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