title: Good rational approximations of pi

text:
# Question
Title: Good rational approximations of pi
Write a program that prints out all the good rational approximations of pi with denominator \< 1000000, in increasing denominator order. `a/b` is a "good rational approximation" of pi if it is closer to pi than any other rational with denominator no bigger than `b`.

The output should have 167 lines total, and start and end like this:

```
3/1
13/4
16/5
19/6
22/7
179/57
...
833719/265381
1146408/364913
3126535/995207

```

Shortest program wins.

# Answer
## Golfscript, 71 70 69 chars

```
2\!:^2^..292^15.2/3]{(.)2/.9>+{\+.((}*;.}do;;]-1%{^0@{2$*+\}/"/"\n}/;

```

(Assumes that you don't pass it anything on stdin)

I don't want to hear any more whinging by people who don't have built-in constants for pi. I don't even have floating point numbers!

See http://en.wikipedia.org/wiki/Continued\_fraction#Best\_rational\_approximations for the background.

```
# No input, so the stack contains ""
2\!:^2^..292^15.2/3]
# ^ is used to store 1 because that saves a char by allowing the elimination of whitespace
# Otherwise straightforward: stack now contains [2 1 2 1 1 1 292 1 15 7 3]
# Pi as a continued fraction is 3+1/(7+1/(15+1/(...)))
# If you reverse the array now on the stack you get the first 10 continuants followed by 2
# (rather than 3)
# That's a little hack to avoid passing the denominator 1000000

{
    # Stack holds: ... [c_n c_{n-1} ... c_0]
    (.)2/.9>+
    # Stack holds ... [c_{n-1} ... c_0] c_n (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
    # (1+c_n)/2 > 9 is an ad-hoc approximation of the "half rule"
    # which works in this case but not in general
    # Let k = (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
    # We execute the next block k times
    {
        # ... [c_{n-1} ... c_0] z
        \+.((
        # ... [z c_{n-1} ... c_0] [c_{n-1} ... c_0] z-1
    }*
    # So we now have ... [c_n c_{n-1} ... c_0] [(c_n)-1 c_{n-1} ... c_0] ...
    #                    [(c_n)-k+1 c_{n-1} ... c_0] [c_{n-1} ... c_0] c_n-k
    ;
    # Go round the loop until the array runs out
    .
}do

# Stack now contains all the solutions as CFs in reverse order, plus two surplus:
# [2 1 2 1 1 1 292 1 15 7 3] [1 2 1 1 1 292 1 15 7 3] ... [6 3] [5 3] [4 3] [3] [2] []
# Ditch the two surplus ones, bundle everything up in an array, and reverse it
;;]-1%

# For each CF...
{
    # Stack holds ... [(c_n)-j c_{n-1} ... c_0]
    # We now need to convert the CF into a rational in canonical form
    # We unwind from the inside out starting with (c_n)-j + 1/infinity,
    # representing infinity as 1/0
    ^0@
    # ... 1 0 [c_n-j c_{n-1} ... c_0]
    # Loop over the terms of the CF
    {
        # ... numerator denominator term-of-CF
        2$*+\
        # ... (term-of-CF * numerator + denominator) numerator
    }/

    # Presentation
    "/"\n
    # ... numerator "/" denominator newline
}/

# Pop that final newline to avoid a trailing blank line which isn't in the spec
;

```
> 23 votes

# Answer
## Mathematica, ~~67~~ 63

This isn't going to be fast, but I believe it is technically correct.

```
Round[π,1/Range@1*^6]//.x_:>First/@Split[x,#2≥#&@@Abs[π-{##}]&]

```

`Round[π, x]` gives the closest fraction to π in steps of `x`. This is "listable" so `Round[π,1/Range@1*^6]` does this for all fractions down to `1/10^6` in order. The resulting list with many "bad" rational approximations is then repeatedly (`//.`) processed by removing any elements which are farther from π than the preceding one.
> 11 votes

# Answer
## Perl, 77 chars

```
$e=$p=atan2 0,-1;($f=abs$p-($==$p*$_+.5)/$_)<$e&&($e=$f,say"$=/$_")for 1..1e6

```

A minor challenge is that Perl doesn't have a built-in *π* constant available, so I first had to calculate it as `atan2(0,-1)`. I'm sure this will be beaten by languages more suited for the job, but it's not bad for a language mainly designed for text processing.
> 7 votes

# Answer
## JS (95 characters)

```
for(i=k=1,m=Math;i<1e6;i++)if((j=m.abs((x=m.round(m.PI*i))/i-m.PI))<k)k=j,console.log(x+'/'+i)

```

It does print 167 lines.
> 5 votes

# Answer
## Python, 96 93 89 characters

```
a=b=d=1.
while b<=1e6:
 e=3.14159265359-a/b;x=abs(e)
 if x<d:print a,b;d=x
 a+=e>0;b+=e<0

```

### Python, 95 93 characters, different algorithm

```
p=3.14159265359;d=1
for a in range(3,p*1e6):
 b=round(a/p);e=abs(p-a/b)
 if e<d:print a,b;d=e

```

**note:** It was less characters to write `p=3.14159265359;` than `from math import*`. Darn those wordy imports!
> 5 votes

# Answer
### Ruby 1.9, 84 characters

```
m=1;(1..1e6).map{|d|n=(d*q=Math::PI).round;k=(n-q*d).abs/d;k<m&&(m=k;puts [n,d]*?/)}

```
> 4 votes

# Answer
## C99, 113 characters

```
main(d,n){double e=9,p=2*asin(1),c,a=1;for(;n=d*p+.5,c=fabsl(p-a*n/d),d<1e6;++d)c<e&&printf("%d/%d\n",n,d,e=c);}

```

Need to compile with `-lm`, and probably full of undefined behaviour, but it works for me.
> 4 votes

# Answer
### Scala - 180 chars

```
import math._
def p(z:Int,n:Int,s:Double):Unit=
if(n==1e6)0 else{val q=1.0*z/n
val x=if(abs(Pi-q)<s){println(z+"/"+n)
abs(Pi-q)}else s
if(Pi-q<0)p(z,n+1,x)else p(z+1,n,x)}
p(3,1,1)

```

// ungolfed: 457

```
val pi=math.Pi
@annotation.tailrec
def toPi (zaehler: Int = 3, nenner: Int = 1, sofar: Double=1): Unit = {
  if (nenner == 1000000) ()
  else {
    val quotient = 1.0*zaehler/nenner
    val diff = (pi - quotient)
    val adiff= math.abs (diff)
    val next = if (adiff < sofar) {
      println (zaehler + "/" + nenner)
      adiff
    }
    else sofar
    if (diff < 0) toPi (zaehler, nenner + 1, next)
    else toPi (zaehler + 1, nenner, next)
  }
}

```

The tailrec annotation is just a check, to verify, that it is tail-recursive, which is often a performance improvement.
> 2 votes

# Answer
# Mathematica 18 17 chars

I chose to use, as a measure of "best", the number of terms in a continued fraction representation of π. By this criterion, the best rational approximations of π are its convergents.

There are 10 convergents of π with a denominator less than one million. This is fewer than the requested 167 terms, but I am including it here because it may be of interest to others.

```
Convergents[π, 10]

(* out *)
{3, 22/7, 333/106, 355/113, 103993/33102, 104348/33215, 208341/66317,
312689/99532, 833719/265381, 1146408/364913}

```

If you really want to see the denominator for the first convergent, it will cost an additional 11 characters:

```
Convergents[π, 10] /. {3 -> "3/1"}
(* out *)
{"3/1", 22/7, 333/106, 355/113, 103993/33102, 104348/33215,
208341/66317, 312689/99532, 833719/265381, 1146408/364913}

```

---

For those who are interested, the following shows the relations among the convergents, partial quotients, and continued fraction expression of convergents of π:

```
Table[ContinuedFraction[π, k], {k, 10}]
w[frac_] := Row[{Fold[(#1^-1 + #2) &, Last[#], Rest[Reverse[#]]] &[Text@Style[#, Blue, Bold, 14] & /@ ToString /@ ContinuedFraction[frac]]}];
w /@ FromContinuedFraction /@ ContinuedFraction /@ Convergents[π, 10]

```

Please excuse the inconsistent formatting of the continued fractions.
> 2 votes

# Answer
# C# 140 129 chars

```
double n=3,d=1,e=d;while(n<4e5){double w=n/d-Math.PI,a=Math.Abs(w);if(a<e){e=a;Console.WriteLine(n+"/"+d);}if(w>0)d++;else n++;}

```

Uncompressed code

```
var numerator = 3d;
var denominator = 1d;
var delta = 4d;
while (numerator < 4e5)
{
    var newDelta = (numerator / denominator) - Math.PI;
    var absNewDelta = Math.Abs(newDelta);
    if (absNewDelta < delta)
    {
        delta = absNewDelta;
        Console.WriteLine(string.Format("{0}/{1}", numerator, denominator));
    }

    if (newDelta > 0)
    {
        denominator++;
    }
    else
    {
        numerator++;
    }
}

```
> 1 votes

# Answer
# J, 69 65

### New

```
]`,@.(<&j{.)/({~(i.<./)@j=.|@-l)@(%~(i:3x)+<.@*l=.1p1&)"0>:_i.1e3

```

Still a brute force approach but much faster and a tad shorter.

### Old

A simple "brute force":

```
(#~({:<<./@}:)\@j)({~(i.<./)@j=.|@-l)@(%~(i:6x)+<.@*l=.1p1&)"0>:i.1e3

```

make a list of `a/b`s and then discard those that are farther from π for some `b'<b`.

*Note: Change `1e3` to `1e6` for the full list. Go do something else and return later.*
> 1 votes

---
Tags: code-golf, math, rational-numbers, pi, approximation
---


# Question
Title: Analysing the most common words in a text, and replacing them with a single byte
This is a *very* crude text encoding algorithm I came up with the other day. It won't work if the text has more than 256 different characters in it – but it does support Unicode, at least in my Python implementation.

The algorithm:

1. Find all the unique characters in the text. Let's call this list, **unique-chars**.
2. Break the text into a sequence of **tokens**, which can be either words (continuous runs of alphanumeric characters, and apostrophes) and symbols (anything that isn't a word). If there's two symbols (say, a comma and a space), take each only once.
3. Sort the tokens, most commonly occurring first. Then, take the top (256 - length of **unique-chars**). Put the two lists – **unique-chars**, and **most-common-tokens** – together into one. Let's call this list **substitution-table**.
4. Iterate through each token. If it's present in **substitution-table**, take the index in which this token is found, and convert it into a character. Otherwise, iterate through each letter in the token, and perform the same character conversion.

This way, the most common words become one byte long; and those which are not as common, stay of the same length. I know, this is not very efficient. But it works.

For reference, use *King James' Bible*, by Project Gutenberg; 4 452 069 bytes, MD5: `3b83dd48fa7db8df0819108f6d50f64f`. Download here.

The processed version is 3 422 006 bytes, MD5: `17c52a22abe48dd4135a577e2a4aff8d`. Download here.

No restrictions apply on the language used, external libraries/programs, dirty tricks, or operating system.

My Python 3 implementation runs in about 3.3–3.5 seconds, in average. Speed has precedence on everything else. Compiled language implementations, especially in C, would be appreciated. A solution in APL or Perl would be most welcome, I'm curious how they'd look like.

As for how to time the solution, I'd say, time 30 executions (possibly cleaning the RAM after each execution, in case caching occurs), and report both the lowest time (which is indicative limit as for how long it takes the machine to run the program in the best conditions) and the rest of times, for completeness' sake. Obviously, this is not perfectly accurate, but it'll do for an indicative value.

That said, happy coding~!

# Answer
## Perl - 154 bytes (KJB in ~1.94s)

```
while(<>){push@w,/[\w\']+|\W/g}
\@c{length>1?$w{$_}++?():/./g:$_}for@w;
@t{sort{$w{$b}-$w{$a}}keys%w}=grep!exists$c{$_},map{chr}0..255;
print$t{$_}//$_ for@w

```

This is substantially golfed, but I can say with confidence that it hasn't affected the performance in any noticable way.

Sample Usage:

```
$ perl encoder.pl < king-james-bible.txt > kjb.cmp

```

The created filesize is *3,253,677* bytes, runtime is approximately *1.94* seconds. If you want to test the correctness, you can export a translation table by appending the following three lines of code:

```
;use Storable;
%u=reverse%t;
store\%u,'trans.tbl'

```

This will create, and possibly overwrite, a file named `trans.tbl` in the current working directory. Then, decode with the following script:

```
#!perl -n0
use Storable;
%t=%{retrieve 'trans.tbl'};
print$t{$_}//$_ for/./sg

```

Sample usage:

```
$ perl decoder.pl < kjb.cmp > kjb.txt

```

The output is exactly *4,452,069* bytes, as expected.

---

**Unrolled and commented**

```
while(<>){      # for each line
  push@w,/[\w\']+|\W/g # tokenize, add tokens to array
}

\@c{            # mark the following chars
  length>1?     # token is 2 or more chars
    $w{$_}++    # increment occurrence in word hash
    ?           # if this word has already been seen
      ()        # mark nothing
    :           # else
      /./g      # mark each char individually
  :             # else
    $_          # mark the single char
}for@w;         # iterate over all tokens

@t{             # create the translation table
  sort{$w{$b}-$w{$a}}keys%w # most frequent words
}=grep!exists$c{$_},map{chr}0..255; # assign to an unmarked char

print           # output
  $t{$_}        # the value in the trans hash
    //          # or, if previous value is undefined
  $_            # output the untranslated string
for@w           # iterate over the tokens previously found

```

---

**Time analysis**

**Min**: *1.843s*
**Max**: *1.984s*
**Avg**: *1.939s*

1.953, 1.953, 1.953, ***1.843***, 1.921, 1.937, 1.921, 1.953, 1.953, 1.921, 1.937, 1.968, 1.906, **1.984**, 1.937, 1.968, 1.953, 1.921, 1.921, 1.937, 1.968, 1.937, 1.890, 1.968, 1.937, 1.953, 1.937, 1.937, 1.937, 1.953

According to profiling, the time usage for each statement is approximately the following:

*1.09s*:
`while(<>){push@w,/[\w\']+|\W/g}`

*31.3ms*:
`\@c{length>1?$w{$_}++?():/./g:$_}for@w;`

*15.6ms*:
`@t{sort{$w{$b}-$w{$a}}keys%w}=grep!exists$c{$_},map{chr}0..255;`

*750ms*:
`print$t{$_}//$_for@w`

Note that for the purpose of time usage analysis, the result was actually written to a file. Excluding the final output, or piping to `/dev/null` instead produces times 600ms to 750ms faster.

---

**Major Performance Gains**

* The individual characters of a word are marked only the first time the word is seen, instead of every time. As noted by @VadimR, this alone saves around *2s*, over *25%* of the previous execution time.
* The most frequent words are translated with unmarked characters, and marked characters left untranslated. This saves a great deal of time during output, because words not in the translation table can be output directly, without having to translate each individual character.
* Tokenizing the file one line at a time - instead of all at once - is quite a bit faster.
> 3 votes

# Answer
**C# - 1.4s**

I use a different metric for word sorting - 'word.Length -1' as this is the value of how many bytes would be saved by compressing said word. For example the word 'a' appears a lot, but saves nothing to compress (as it's already kept), and "the" saves twice as much as "at".

```
//Initial Size 4452066
//Final Size 3186918
//Time 1408 ms

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace SimpleCommonWordCompressor
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                var data = File.ReadAllText("king-james-bible.txt");
                var sw = Stopwatch.StartNew();

                var uniqueChars = data.Distinct().Select(c => c.ToString()).ToArray();

                var tokens = new List<string>();
                var currentWord = new List<char>();
                Action tryAddWord = () =>
                {
                    if (currentWord.Count > 0)
                    {
                        tokens.Add(string.Join("", currentWord));
                        currentWord.Clear();
                    }
                };
                var charToStringLU = Enumerable.Range(0, 256).Select(i => ((char) i).ToString()).ToArray();
                foreach (var datum in data)
                    if (char.IsLetterOrDigit(datum)) currentWord.Add(datum);
                    else
                    {
                        tryAddWord();
                        tokens.Add(charToStringLU[datum]);
                    }
                tryAddWord();

                var grpTokens = tokens.GroupBy(x => x).ToArray();

                var wordTable = uniqueChars.Concat(grpTokens
                    .OrderByDescending(g => g.Count() * (g.Key.Length - 1))
                    .Select(grp => grp.Key)
                    .Take(256 - uniqueChars.Length)).ToList();

                var wordDict = wordTable.ToDictionary(w => w, w => new[] { (byte)wordTable.IndexOf(w) });
                var charTable = new byte[256];

                for (byte i = 0; i < uniqueChars.Length; i++)
                    charTable[uniqueChars[i][0]] = i;

                var tokenToBinary = grpTokens.ToDictionary
                    (grp => grp.Key, grp =>{
                        byte[] index;
                        if (wordDict.TryGetValue(grp.Key, out index)) return index;
                        var newWordBinary = grp.Key.Select(c => charTable[c]).ToArray();
                        return newWordBinary;
                    });

                var binary = new List<byte>();

                foreach (var token in tokens)
                    binary.AddRange(tokenToBinary[token]);

                sw.Stop();
                Console.WriteLine("Initial Size " + data.Length);
                Console.WriteLine("Final Size " + binary.Count);
                Console.WriteLine("Time " + sw.ElapsedMilliseconds + " ms\n");
                Console.WriteLine("Press enter to run again");
                Console.ReadLine();
            }
        }
    }
}

```
> 2 votes

---
Tags: code-challenge, fastest-code, compression
---


# Question
Title: Print Leonardo DiCaprio without using any of the letters in his name
The Oscars are coming up soon and we all know who's going to win Best Actor in a Leading Role this year right? The great Leonardo DiCaprio of course! Despite his superb performances in all of his films during his career, he has yet to win an Academy Award. So as tribute and as a way to wish him luck during the Awards Ceremony this year, your task is to print "Leonardo DiCaprio" (without quotes and case-sensitive) without using any letters in his name in your code. This is code-golf so the shortest code wins. Score is based on your code in bytes. Any language is acceptable.

**-100 Points** if you can print his name on an `ascii` plate like so (Best Actor not required):

```
 _____________________________
|                             |
|      Leonardo DiCaprio      |
|         Best Actor          |
|_____________________________|

```

**Edit** For clarification, the rule for not "using any letters in his name in your code" is **case-insensitive**.

Also **another edit** you may use spaces.

# Answer
## J, 54 - 100 = -46

```
<17$3(3!:4)8026666198671254860 7598259084372558880 111

```

Output:

```
┌─────────────────┐
│Leonardo DiCaprio│
└─────────────────┘

```
> 14 votes

# Answer
## HTML/Markdown, 96 bytes

```
Leonardo DiCaprio

```

This works even with the strictest rule (no space, no letter case-insensitive).

## Markdown, 194 - 100 = 94 bytes

This is the fancy version, so it uses quite a lot of bytes (UTF-8). At the end of the first 2 lines are 2 spaces.

```
╔════════════╗
║Leonardo DiCaprio║
╚════════════╝

```

How it looks (may or may not look good depending on the font face):

╔════════════╗
║Leonardo DiCaprio║
╚════════════╝

## Markdown, 142 - 100 = 42 bytes

This is the poor man's version. No Unicode character is used, so quite lightweight.

```
~~~~~~~~~~~~~~~~~
| Leonardo DiCaprio |
~~~~~~~~~~~~~~~~~

```

It looks like a cookie to me:

~~~~~~~~~~~~~~~~~
| Leonardo DiCaprio |
~~~~~~~~~~~~~~~~~
> 5 votes

# Answer
# BF, 77

203 chars = 609 bits = 77 bytes

```
-[------->+<]>+++.-[--->++++<]>+.++++++++++.-.-------------.--[--->+<]>---.--------------.+++++++++++.[--->+<]>-----.++[->++<]>.++[-->+++<]>.++[->+++<]>++.-[-->+++<]>--.-[++>-----<]>.++.---------.++++++.

```

Output:

```
Leonardo DiCaprio

```
> 5 votes

# Answer
## Sclipting, 39 bytes

```
丟냆녯닦굲뉆묠끆땃눗걲늖및

```

Based on the Hello, world! program, just encode the name as string.
> 4 votes

# Answer
# JavaScript 221 - 100 = 121

This took a little working out... instead of printing, it pushes the result as an `alert`... best I could do... trying to make this code do a `document.write` would have floored me...

`3[z=(y=''+{})[5]+y[1]+(''+1/0)[1]+'st'+(x=''+!0)[1]+'u'+y[5]+'t'+y[1]+x[1]][z]("\141\154\145\162t('"+(v="+--------------------+")+"\\\156|\114\145\157\156\141\162\144\157 \104\151\103\141\160\162\151\157|\\\156"+v+"')")()`
> 1 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Print E=mc² or E=mc^2, by using the right side of this equation
Your task – if you choose to accept it – is to have your program print, literally, either one of the following:

1. `E=mc²` (if your language supports Unicode (so no HTML trickery, for instance))
2. `E=mc^2` (if your language doesn't support Unicode)

Here are the conditions:

* Your program must consist of exactly two expressions (one representing the `m`, the other the `c`, in `mc²`), which, when fed into your language's representation of the formula `mc²`, and whose result is then printed, will show one of the above results.
* Both expression may be assigned to variables before feeding them into `mc²`, but the expressions themselves are not allowed to use intermediate variables.
* Both expressions must evaluate to an absolute value larger than 1 (e.g `abs(expression) > 1`).
* You may assign the result of `mc²` to an intermediate variable, representing the `E`, before printing this `E`, but that is not necessary – you may print the result of `mc²` directly as well.
* When printing the final result, you *are* allowed to use your language's libraries to convert the possibly numeric or binary result to it's string representation.
* **Added condition**: no operator overloading in the final expression that represents `mc²`. The result *must* be the algebraic result of expression `m` times expression `c` squared.

Here's an example template, of what I'm looking for, expressed in PHP:

```
$m = /* some expression */;
$c = /* some expression */;
$E = $m * pow( $c, 2 );
print $E; // should print on of the results mentioned at the beginning of this challenge

```

To be honest, I'm not even sure this challenge is doable, but my gut says it must be possible in at least one, or even a few, languages.

Winning solution is the one with the shortest code, in characters, in a week from now.

For clarification, it's perfectly fine to merely do something like this as well — if your language allows for it:

```
print( someExpression * someOtherExpression ** 2 ); // or something to that effect

```

... in other words: without assigning anything to any intermediate variables. Just as long as the algebraic calculation remains intact.

# Answer
> 2 votes
# APL, 27

```
⎕UCS(2÷⍨⎕UCS'E=mc²')×(√2)*2

```

**Ungolfed:**

```
m←(⎕UCS 'E=mc²')÷2
c←√2
⎕UCS m×c*2

```

Start with the desired output string, convert it into an array of Unicode values, divide each number by 2, and assign the vector to **m**. Then assign √2 to **c**. Compute the formula and convert the resulting array back to a string. I can't tell whether the last operation is allowed by the rules, but it's akin to what most other solutions are doing, whether explicitly or implicitly.

# Answer
> 15 votes
# C, ~~66~~ ~~59~~ 57 bytes

Ignore the compiler warnings. It should work OK as long as you compile it on a ~~big~~ *little*-endian machine. This code could probably be made a lot shorter on a 64-bit machine, but I'm unable to test:

```
main(){long long m=1130224008533LL,c=7,E=m*c*c;puts(&E);}

```

9 fewer characters thanks to @Adam Davis and @Michael :-)

# Answer
> 7 votes
## C, 57 53 50 40 39 bytes

The rules are somewhat confusing, I do hope I read them correctly.
Works on 32bit platforms only.

```
m="E=mc^2",c=-1u/2;
main(){
    puts(m*c*c);
}

```

`c`c equals 2^31-1, so `c*c` equals 1 modulo 2^32. Therefore `m*c*c == m` (mod 2^32).
The `-1u/2` constant and `puts` are hvd's suggestions.

# Answer
> 5 votes
# Java: ~~261~~ ~~241~~ ~~207~~ 206 characters

Thanks to @V-X for helping me with ideas for optimizing this.

Here it is, 206 characters:

```
import java.math.*;class N{public static void main(String[]y){BigInteger m=new BigInteger("12uy4kc5e",36),c=new BigInteger("5"),e=m.multiply(c).multiply(c);System.out.println(new String(e.toByteArray()));}}

```

Properly indented version:

```
import java.math.*;
class N {
    public static void main(String[] y) {
        BigInteger m = new BigInteger("12uy4kc5e",36),
                   c = new BigInteger("5"),
                   e = m.multiply(c).multiply(c); // e = m * c * c
        System.out.println(new String(e.toByteArray()));
    }
}

```

Older version, Java 8 only, with 261 characters:

```
import java.math.*;public class N{public static void main(String[]y){BigDecimal m=new BigDecimal("59324209849366147.77"),c=BigDecimal.TEN,e=m.multiply(c).multiply(c);System.out.println(new String(java.util.Base64.getDecoder().decode(e.toBigInteger().toByteArray())));}}

```

Ungolfed version:

```
import java.math.*;
import static java.util.Base64.*;

public class N {
    public static void main(String[] y) {
        BigDecimal m = new BigDecimal("59324209849366147.77"),
                   c = BigDecimal.TEN,
                   e = m.multiply(c).multiply(c); // e = m * c * c

        System.out.println(new String(getDecoder().decode(e.toBigInteger().toByteArray())));
    }
}

```

# Answer
> 4 votes
# Perl - 32 characters

```
$m="E=mc²";$c=1.1;print$m x$c**2

```

This is sort of cheating: in Perl's `x` operator, the right operand is converted to an integer, so both 1.1 and 1.21 (1.1\**2), despite having a value larger than 1, behave exactly as 1.

# Answer
> 2 votes
## TI-89 basic (needs CAS) - 17

```
solve(√(e/m)=c,e)

```

Edited - it now works (according to my calculator):

```
e = c^2 * m and c >= 0

```

# Answer
> 2 votes
# Smalltalk, 110 58 56

Version 2 below does it, but I guess version1 is interesting enough to not cut it. Read for your amusement (it's about fun here - isn't it)

### Version 1:

code:

```
(Class name:#S subclassOf:String)compile:'*t^''E='',self,t';compile:'squared^self,''²'''.m:='m'as:S.c:='c'as:S

```

evaluate:

```
m*c squared

```

result: 'E=mc²'

I really have a hard time to understand what you expect :-(, so I'll give some more detail than usual. Maybe it is of interest to others, even if it does not golf.

First, you want the standard language syntax to be used, eg. in Smalltalk, I would write:

```
m := 100.
c := 299792500.
E := m * c squared.

```

to get "8987554305625000000".

So you want this to be done symbolically. In ST we need a class which redefines the above used operators into string concatenations (any class would do, but I'll inherit from String for convenience, so I get the ,-operator):

```
Class name:#MyString subclassOf:String

    * thingy
        ^ self,thingy asString

    squared
        ^ self,'²'

    = thingy
        ^ self,'=',thingy

```

So now, I can write:

```
m := MyString fromString:'m'.  "/ or 'm' as:MyString for short
c := MyString fromString:'c'.
(m * c squared) print

```

and get 'mc²' as output.

However, and that's my problem: the assignment cannot be redefined, so saying:

```
E := (m * c squared).
E print

```

would print the same. In Smalltalk, "=" is a comparison operator (not assignment). "=" was already redefined in the above code. However, as I am calling for a comparison of E against the right side, I need to preset E to something non-nil first:

```
E := MyString fromString:'E'.

```

So let's write:

```
(E = m * c squared) print

```

gives us (the requested?): 'E=mc²'

As you wanted the result of m\*c squared, I'll push the 'E' into the multiplication operator:

```
* thingy
    ^ 'E=',self,thingy

```

to fullfill your requirements.

PS: the second comment made it obvious; all I have to change is the assignment in the above class to generate the 'E'.

### Version 2:

Obviously I was thinking way too complicated:

```
m:=36rEF7U6YC5.c:=7.E:=m*c squared.E digitBytes asString

```

also outputs: 'E=mc^2'

Edit: The large number 1130224008533 is obviously shorter if written in a higher base - hex for example; but it is *much* shorter in base 36, which in Smalltalk is written as 36rEF7U6YC5. This saves me another 2 characters.

PS: how to get to the magic numbers:
`LargeInteger digitBytes:'E=mc^2' asByteArray`
-\> 55380976418117
`55380976418117 primeFactors`
-\> Bag('4728970747(\*1)' '7(\*2)' '239(\*1)')

# Answer
> 2 votes
# Lua - 74

```
c=rawset(_G,"print",function()io.write"E=mc^2\n"end)and 2 m=2 print(m*c^2)

```

A little cheaty, but not prohibited by the rules:

* Exactly 2 expressions, one for `c`, another for `m`.
* No intermediate variables
* No operator overloading

# Answer
> 1 votes
# T-SQL - ~~86 bytes~~ 75 bytes

I'm pretty proud of how competitive this one is for SQL the verbose blabbermouth.

Found myself wishing SQL had a 64-bit binary data type so I could possibly find a bigger square root than 3, but this comes out as a pretty lean one-liner anyway. And it prints the pretty Unicode version! (Which is good, because there were no squares to factor out of the number for E=mc^2)

And it *smokes* the Java entry. ;-)

Jus' kiddin' - @Victor and I are kindred spirits, more interested in playing our best game than winning the prize. Here's to we the crazy ones!

### New Hotness, 75 bytes

I was hoping for a larger improvement, but due to the vagaries of the query processor I have to explicitly declare @m as a BIGINT or SQL chooses the wrong bit size and the binary result is wrong. Still, better is better.

```
DECLARE @m BIGINT=33042591394;SELECT CAST(CAST(@m*3*3 AS BINARY(5))AS CHAR)

```

### Original Submission, 86 bytes

```
DECLARE @c INT=3,@m BIGINT=33042591394;SELECT CAST(CAST(@m*@c*@c AS BINARY(5))AS CHAR)

```

SQLFiddle Here.

Output:

```
E=mc²

```

# Answer
> 0 votes
## C# 180 176 171 170 165

```
using System;namespace N{class P{static void Main(){var m=0x1072699BD55;var c=7;Console.Write(System.Text.Encoding.UTF8.GetString(BitConverter.GetBytes(m*c*c)));}}}

```

Concept like the Smalltalk version, just for C#.
Output: `E=mc^2`
Use the longer version `var m=0x391DAF9277DEA5D;` for `E=mc²` (actually followed by two spaces)

Edits:
180 to 176: remove 4 spaces
176 to 171: inline usings
171 to 170: Use UTF8 encoding
170 to 165: WriteLine-\>Write, outline using System; (thanks for the comments)

---
Tags: code-golf
---


# Question
Title: Find the overall period from a list of frequencies
Inspired by http://xkcd.com/1331/

In this xkcd comic, there are several gifs that all blink with different frequency. I want to know what the period would be if was all a single GIF. Given a list of numbers representing the individual frequencies, output the period of the overall GIF.

**Formal Definition**

Input:

```
N
f1
f2
.
.
.
fN

```

Output:

```
P

```

Where N is the number of frequencies, fi is the ith frequency, and P is the resulting period of the total GIF.

You may choose to use any delimiting character you want(instead of \n), and you may exclude the N if you wish, and it will be inferred by the number of delimeters.

**Some specifics**

Frequencies are the closest double-precision floating point representation of the numbers provided as input.

The outputted period is a 64-bit unsigned integer, rounded(up on 0.5) to the nearest whole. Any input that would produce a period bigger than 2^64-1 is considered undefined behaviour.

Likewise any input \<= 0 is considered undefined behaviour.

**Win Condition**

Code golf so shortest code wins!

# Answer
> 8 votes
# APL, 4

```
∧/∘÷

```

is both logical AND and numerical LCM (with domain over integers, floats, complex, rationals, whatever number stack is supported by the APL implementation) so `∧/` is reduction by LCM, or computing the LCM of an array.

Monadic `÷` is numeric inverse. So the composition `∧/∘÷` is the LCM of the inverses of the numbers supplied.

The other formula, inverse of the GCD, would be `÷∘(∨/)`, where the parentheses are needed to fix the precedence between  and `/`.

You can try it online on http://tryapl.com/

**Examples**

```
      ∧/∘÷ .12 .02 3.9 .15 .99
100
      ∧/∘÷ (16÷5)(2÷3)(2.35)(1÷7)
420

```

# Answer
> 4 votes
# Mathematica ~~43~~ 28

## Second try

My first attempt was not correct, although it did have some of the necessary ingredients (LCM,Rationalize). The complete solution requires taking into account both the numerator and denominator of each frequency (expressed as a common fraction).

`l` is the list of frequencies.

Rationalizing 2.35 converts it to the common fraction 235/100.

```
f@l_:=LCM@@(1/Rationalize@l)

```

Assume that all GIFs fire at t=0.

The following approach does not require that the frequencies be expressed as "real numbers", ie. as decimal fractions. They may be other sort of fractions. The example below is a case where the fractions are in fifths, thirds, hundredths and sevenths.

If two or more frequencies are incommensurate (in which case at least one must be an irrational number) then there is no solution. In other words, there will be no point in time, t\>0, at which all components fire at the same time.

**Example1**

```
f[{50, 10}]

```

> 1/10

---

**Example 2**

```
f[{16/5, 2/3, 2.35, 1/7}]

```

> 420

If we multiply the least overall period by each of the frequencies, we find a whole number of cycles in each case:

```
420*{16/5, 2/3, 2.35, 1/7}

```

> {1344, 280, 987., 60}

(1344 hops of 16/5 units) lands at 420. (280 hops of 2/3 units) lands at 420. (987 hops of 2.35 units) lands at 420. (60 hops of 7 units) lands at 420.

# Answer
> 2 votes
## Javascript: 191 characters

The input format that I chose (within the rules) is the frequency numbers separated by commas. No spaces allowed and no newlines. The initial N must not be given. Each number must be just a serie of at least one \[0-9\] digits with an optional dot somewhere within. If the input is malformed, the behaviour is undefined.

**How it works:**

> The period of some integer frequency numbers is the GCD of these numbers. If the given numbers are not integer, it sucessively multiplies they by 10 until it gets everything as an integer number (this exploit the fact that the non-integer numbers are given in base 10). After calculating the GCD, it divides the result by the power of ten used to multiply the input numbers, and hence getting the overall frequency. Inverting this we get the period.
> *Note: I am pretty sure that now that I gave this answer, somebody will code the same in APL or J and beat it. :(*

**The code:**

```
d=1,s=prompt().split(",");for(a in s){s[a]=parseFloat(s[a]);while(s[a]*d%1>0)d*=10}g=s[0]*d;for(a in s){u=g;v=s[a]*=d;p=2;q=1;while(u>=p&v>=p)if(u%p|v%p)p++;else{u/=p;v/=p;q*=p}g=q}alert(d/g)

```

**Testing it:**

```
Input: 50,10
Output: 0.1
Interpretation: One GIF blinks 10 times per second (period = 0.1s) and the other 50 times (period = 0.02s). So a combined GIF would repeat itself in 0.1 seconds.

Input: 2.7,3.4
Output: 10
Interpretation: One blinking at 2.7 times per second will blink 27 times in 10 seconds. One blinking 3.4 times per second will blink 34 times in 10 seconds. So, 10 seconds is a period, and since GCD(27,34)=1, it is the smallest.

Input: 4.8,7.2
Output: 0.4166666666666667
Interpretation: One blinking at 4.8 times per second and the other at 7.2 times per second, gives a frequency of 2.4 times per second, which is a period 0.41666... seconds.

Input: 0.6,12,7.9,4.33
Output: 100
Interpretation: Similar to second case. 60, 1200, 790 and 433 times each 100 seconds. The GCD of these numbers is 1.

Input: 400,200,25,350
Output: 0.04
Interpretation: The slowest is the 25 times per second, which is the overall frequency. 25 times per second is a period of 0.04 seconds.

Input: 440,200,35,360
Output: 0.2
Interpretation: In 0.2 seconds, we have 88, 40, 7 and 72 blinks.

```

---
Tags: code-golf
---


title: Array Shuffling

text:
# Question
Title: Array Shuffling
Write a program that takes a sorted integer array, shuffles all the elements in such a way that for every `i` there must exist a `j` such that, one of the following is satisfied:

```
a[i] < a[j] < a[i+1]
a[i] > a[j] > a[i+1]

```

`i` and `j` are within the bounds of array.

If there are not many distinct elements, you must show an error.

For example,

```
Input: 1, 2
Output: Error

Input: 1, 2, 3, 4, 5, 6, 7
Output: 7, 1, 4, 2, 5, 3, 6

Input: 1, 2, 2, 4, 5, 6, 7
Output: 1, 4, 6, 2, 5, 2, 7

Input: 1, 2, 2, 3
Output: Error

Input: 1, 5, 7, 7, 11
Output: Error

```

There may be more than one possible correctly shuffled arrays. You just have to solve for 1 correct solution.

Input array can have repeated elements, this requirement makes the solution tricky, otherwise a sort and skip would have worked.

Being able to have duplicates in input also makes it different from The Strange Unsorting Machine for Nefarious Purposes . And a correct solution is much trickier than the that.

The output must be of same size as input array and all elements from the input array must exist at some position in the output array.

**How to take input:** The program must take input either through console input or a simple delimited text file.

**How to output:** The program must output to the console.

**What to output:** Program must output both the input and the output array in following format

```
Input: 1, 2, 3, 4, 5, 6, 7
Output: 7, 1, 4, 2, 5, 3, 6

```

If input cannot be shuffled as required, the output should look like

```
Input: 1, 2, 3
Output: Error

```

Shortest code (byte count) wins.

**BONUS 1:** Deduct 10 points from your count if your solution can work on unsorted inputs.

**BONUS 2:** Deduct 20 points from your count if your solution can find more than 1 (not all) solutions for the same input. To qualify for this bonus, your additional solution must not be just a reversed output of the other solution.

# Answer
> 1 votes
# Haskell, ~~311~~276 (-30 bonus=246)

```
import Data.List
m=map
w=putStrLn
b=(intercalate",").(m show)
o="Output: "
z[]=[o++"Error"]
z a=m((o++).b)a
main=do
 r<-getLine
 let q=m read(words r)::[Int]
 w$"Input: "++b q
 mapM_ w$z$filter(\d->and$m(\(a,b)->any(\x->(a<x&&x<b)||(a>x&&x>b))d)$zip d(tail d))$permutations q

```

Compile with `ghc`, Run from the command line, input is a single line with space delimited numbers, eg `echo 1 2 3 4|shuffle`. This is a brute force solution so is quite likely to be slow for large input lists. It prints all the solutions.

---
Tags: code-golf
---


title: Reflective evolutionary algorithm

text:
# Question
Title: Reflective evolutionary algorithm
You have to write a program, implementing a function `digitsum(int i)`. The program has to modify its own code (for languages, where this is not possible with f.e. reflection, please be creative) to get itself to solve the goal.

You start with

```
function digitsum(int i){
    return i;
}

```

and implement an evolutionary algorithm that will modify the above function until it returns valid digitsums on function call.

As this is a popularity contest, you have very much free hands, please be creative!

**Guidelines:**

* Start with the defined function (translated to your language of course).
* Print out at least the fittest function of each generation.
* Print out your working solution tested for 0 \< i \< 10000.
* Be creative!

**Do not:**

* Hint your program to the solution, please use your whole language options!
* Throw errors to the console.
* Use any external input. You can write and save to files created by your program. No internet.

The valid solution with the most upvotes wins!

# Answer
> 3 votes
# C#

Almost entirely random and raw assembly solution. As far as C# and pretty much any other platform goes, this is as low level as possible. Luckily, C# allows you to define methods during runtime in IL (IL is intermediate language, the byte-code of .NET, similar to assembly). The only limitation of this code is that I chose some opcodes (out of hundreds) with an arbitrary distribution which would be necessary for the perfect solution. If we allow all opcodes, chances of a working program are slim to none, so this is necessary (as you can imagine, there are many many ways that random assembly instructions can crash, but luckily, they don't bring down the whole program in .NET). Other than the range of possible opcodes, it's completely random slicing and dicing IL opcodes without any kind of hinting. I am pretty surprised but this actually seems to work, some generated programs do not crash and do produce results!

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Threading;

namespace codegolf
{
    class Program
    {
        // decompile this into IL to find out the opcodes needed for the perfect algo
        static int digitsumbest(int i)
        {
            var ret = 0;
            while (i > 0)
            {
                ret += i % 10;
                i /= 10;
            }
            return ret;
        }

        delegate int digitsumdelegate(int num);

        static Thread bgthread;

        // actually runs the generated code for one index
        // it is invoked in a background thread, which we save so that it can be aborted in case of an infinite loop
        static int run(digitsumdelegate del, int num)
        {
            bgthread = Thread.CurrentThread;
            try
            {
                return del(num);
            }
            catch (ThreadAbortException)
            {
                bgthread = null;
                throw;
            }
        }

        // evaluates a generated code for some inputs and calculates an error level
        // also supports a full run with logging
        static long evaluate(digitsumdelegate del, TextWriter sw)
        {
            var error = 0L;

            List<int> numbers;
            if (sw == null) // quick evaluation
                numbers = Enumerable.Range(1, 30).Concat(Enumerable.Range(1, 70).Select(x => 5000 + x * 31)).ToList();
            else // full run
                numbers = Enumerable.Range(1, 9999).ToList();

            foreach (var num in numbers)
            {
                try
                {
                    Func<digitsumdelegate, int, int> f = run;
                    bgthread = null;
                    var iar = f.BeginInvoke(del, num, null, null);
                    if (!iar.AsyncWaitHandle.WaitOne(10))
                    {
                        bgthread.Abort();
                        while (bgthread != null) ;
                        throw new Exception("timeout");
                    }
                    var result = f.EndInvoke(iar);
                    if (sw != null)
                        sw.WriteLine("{0};{1};{2};", num, digitsumbest(num), result);
                    var diff = result == 0 ? 15 : (result - digitsumbest(num));
                    if (diff > 50 || diff < -50)
                        diff = 50;
                    error += diff * diff;
                }
                catch (InvalidProgramException)
                {
                    // invalid IL code, happens a lot, so let's make a shortcut
                    if (sw != null)
                        sw.WriteLine("invalid program");
                    return numbers.Count * (50 * 50) + 1;
                }
                catch (Exception ex)
                {
                    if (sw != null)
                        sw.WriteLine("{0};{1};;{2}", num, digitsumbest(num), ex.Message);
                    error += 50 * 50;
                }
            }
            return error;
        }

        // generates code from the given byte array
        static digitsumdelegate emit(byte[] ops)
        {
            var dm = new DynamicMethod("w", typeof(int), new[] { typeof(int) });
            var ilg = dm.GetILGenerator();
            var loc = ilg.DeclareLocal(typeof(int));

            // to support jumping anywhere, we will assign a label to every single opcode
            var labels = Enumerable.Range(0, ops.Length).Select(x => ilg.DefineLabel()).ToArray();

            for (var i = 0; i < ops.Length; i++)
            {
                ilg.MarkLabel(labels[i]);

                // 3 types of jumps with 23 distribution each, 11 types of other opcodes with 17 distribution each = all 256 possibilities
                // the opcodes were chosen based on the hand-coded working solution
                var c = ops[i];
                if (c < 23)
                    ilg.Emit(OpCodes.Br_S, labels[(i + 1 + c) % labels.Length]);
                else if (c < 46)
                    ilg.Emit(OpCodes.Bgt_S, labels[(i + 1 + c - 23) % labels.Length]);
                else if (c < 69)
                    ilg.Emit(OpCodes.Bge_S, labels[(i + 1 + c - 46) % labels.Length]);
                else if (c < 86)
                    ilg.Emit(OpCodes.Ldc_I4, c - 70); // stack: +1
                else if (c < 103)
                    ilg.Emit(OpCodes.Dup); // stack: +1
                else if (c < 120)
                    ilg.Emit(OpCodes.Ldarg_0); // stack: +1
                else if (c < 137)
                    ilg.Emit(OpCodes.Starg_S, 0); // stack: -1
                else if (c < 154)
                    ilg.Emit(OpCodes.Ldloc, loc); // stack: +1
                else if (c < 171)
                    ilg.Emit(OpCodes.Stloc, loc); // stack: -1
                else if (c < 188)
                    ilg.Emit(OpCodes.Mul); // stack: -1
                else if (c < 205)
                    ilg.Emit(OpCodes.Div); // stack: -1
                else if (c < 222)
                    ilg.Emit(OpCodes.Rem); // stack: -1
                else if (c < 239)
                    ilg.Emit(OpCodes.Add); // stack: -1
                else
                    ilg.Emit(OpCodes.Sub); // stack: -1
            }

            ilg.Emit(OpCodes.Ret);
            return (digitsumdelegate)dm.CreateDelegate(typeof(digitsumdelegate));
        }

        static void Main(string[] args)
        {
            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;

            var rnd = new Random();

            // the first list is just 10 small random ones
            var best = new List<byte[]>();
            for (var i = 0; i < 10; i++)
            {
                var initial = new byte[5];
                for (var j = 0; j < initial.Length; j++)
                    initial[j] = (byte)rnd.Next(256);
                best.Add(initial);
            }

            // load the best result from the previous run, if it exists
            if (File.Exists("best.txt"))
                best[0] = File.ReadAllLines("best.txt").Select(x => byte.Parse(x)).ToArray();

            var stop = false;

            // handle nice stopping with ctrl-c
            Console.CancelKeyPress += (s, e) =>
            {
                stop = true;
                e.Cancel = true;
            };

            while (!stop)
            {
                var candidates = new List<byte[]>();

                // leave the 10 best arrays, plus generate 9 consecutive mutations for each of them = 100 candidates
                for (var i = 0; i < 10; i++)
                {
                    var s = best[i];
                    candidates.Add(s);
                    for (var j = 0; j < 9; j++)
                    {
                        // the optimal solution is about 20 opcodes, we keep the program length between 15 and 40
                        switch (rnd.Next(s.Length >= 40 ? 2 : 0, s.Length <= 15 ? 3 : 5))
                        {
                            case 0: // insert
                            case 1:
                                var c = new byte[s.Length + 1];
                                var idx = rnd.Next(0, s.Length);
                                Array.Copy(s, 0, c, 0, idx);
                                c[idx] = (byte)rnd.Next(256);
                                Array.Copy(s, idx, c, idx + 1, s.Length - idx);
                                candidates.Add(c);
                                s = c;
                                break;
                            case 2: // change
                                c = (byte[])s.Clone();
                                idx = rnd.Next(0, s.Length);
                                c[idx] = (byte)rnd.Next(256);
                                candidates.Add(c);
                                s = c;
                                break;
                            case 3: // remove
                            case 4: // remove
                                c = new byte[s.Length - 1];
                                idx = rnd.Next(0, s.Length);
                                Array.Copy(s, 0, c, 0, idx);
                                Array.Copy(s, idx + 1, c, idx, s.Length - idx - 1);
                                candidates.Add(c);
                                s = c;
                                break;
                        }
                    }
                }

                // score the candidates and select the best 10
                var scores = Enumerable.Range(0, 100).ToDictionary(i => i, i => evaluate(emit(candidates[i]), null));
                var bestidxes = scores.OrderBy(x => x.Value).Take(10).Select(x => x.Key).ToList();
                Console.WriteLine("best score so far: {0}", scores[bestidxes[0]]);
                best = bestidxes.Select(i => candidates[i]).ToList();
            }

            // output the code of the best solution
            using (var sw = new StreamWriter("best.txt"))
            {
                foreach (var b in best[0])
                    sw.WriteLine(b);
            }

            // create a CSV file with the best solution
            using (var sw = new StreamWriter("best.csv"))
            {
                sw.WriteLine("index;actual;generated;error");
                evaluate(emit(best[0]), sw);
            }
        }
    }
}

```

Sorry I have no results so far because even with testing for 1..99 (instead of 1..9999) is pretty slow and I am too tired. Will get back to you tomorrow.

EDIT: I finished the program and tweaked it a lot. Now, if you press CTRL-C, it will finish the current run and output the results in files. Currently, the only viable solutions it produces are programs which always return a constant number. I'm starting to think that the chances of a more advanced working program are astronomically small. Anyway I will keep it running for some time.

EDIT: I keep tweaking the algorithm, it's a perfect toy for a geek like me. I once saw a generated program which actually did some random math and didn't always return a constant number. It would be awesome to run it on a few million CPU's at once :). Will keep running it.

EDIT: Here's the result of some completely random math. It jumps around and stays at 17 for the rest of the indices. It won't become conscious anytime soon.

EDIT: It's getting more complicated. Of course, as you would expect, it looks nothing like the proper digitsum algorithm, but it's trying hard. Look, a computer generated assembly program!

# Answer
> 3 votes
# C#

This might not be completeley what you envisioned, but this is the best I could do right now. (At least with C# and CodeDom).

So how it works:

1. It calculates the digitsum base 2 (the base wasn't specified in the statement)
2. It tries to generate an expression with a lot of terms that look like `((i & v1) >> v2)`. These terms will be the genes that will be mutated through the run.
3. The fitness function simply compares the values with a pre-calculated array, and uses the sum of the absolute value of the differences. This means a 0 value means we have arrived to the solution, and the less the value the fitter the solution.

The code:

```
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;

namespace Evol
{
    class MainClass
    {
        const int BASE = 2;
        static int[] correctValues;
        static List<Evolution> values = new List<Evolution>();

        public static CodeCompileUnit generateCompileUnit(CodeStatementCollection statements) {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace samples = new CodeNamespace("CodeGolf");
            compileUnit.Namespaces.Add(samples);
            samples.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclaration digitSumClass = new CodeTypeDeclaration("DigitSum");
            samples.Types.Add(digitSumClass);
            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "digitsum";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            method.ReturnType = new CodeTypeReference (typeof(int));
            method.Parameters.Add (new CodeParameterDeclarationExpression (typeof(int), "i"));
            method.Statements.AddRange (statements);
            digitSumClass.Members.Add(method);
            return compileUnit;
        }

        public static long CompileAndInvoke(CodeStatementCollection statements, bool printCode) {
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add( "System.dll" );
            cp.GenerateInMemory = true;
            CodeGeneratorOptions cgo = new CodeGeneratorOptions ();
            CodeDomProvider cpd = new CSharpCodeProvider ();
            CodeCompileUnit cu = generateCompileUnit (statements);
            StringWriter sw = new StringWriter();
            cpd.GenerateCodeFromCompileUnit(cu, sw, cgo);
            if (printCode) {
                System.Console.WriteLine (sw.ToString ());
            }

            var result = cpd.CompileAssemblyFromDom (cp, cu);

            if (result.Errors.Count != 0) {
                return -1;
            } else {
                var assembly = result.CompiledAssembly;
                var type = assembly.GetType ("CodeGolf.DigitSum");
                var method = type.GetMethod ("digitsum");
                long fitness = CalcFitness (method);
                return fitness;
            }
        }

        public static long CalcFitness(MethodInfo method) {
            long result = 0;
            for (int i = 0; i < correctValues.Length; i++) {
                int r = (int)method.Invoke (null, new Object[] { i });
                result += Math.Abs (r - correctValues[i]);
            }
            return result;
        }

        public static CodeStatementCollection generateCodeDomFromString (Term[] terms) {
            CodeStatementCollection statements = new CodeStatementCollection ();
            CodeExpression expression = null;
            foreach (Term term in terms) {
                CodeExpression inner = new CodeArgumentReferenceExpression ("i");
                if (term.and.HasValue) {
                    inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.BitwiseAnd, new CodePrimitiveExpression(term.and.Value));
                }
                if (term.shift.HasValue) {
                    inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.Divide, new CodePrimitiveExpression(Math.Pow (2, term.shift.Value)));
                }
                if (expression == null) {
                    expression = inner;
                } else {
                    expression = new CodeBinaryOperatorExpression (expression, CodeBinaryOperatorType.Add, inner);
                }
            }
            statements.Add (new CodeMethodReturnStatement (expression));
            return statements;
        }

        public static void Main (string[] args)
        {
            correctValues = new int[10001];
            for (int i = 0; i < correctValues.Length; i++) {
                int result = 0;
                int num = i;
                while (num != 0) {
                    result += num % BASE;
                    num /= BASE;
                }
                correctValues [i] = result;
            }
            values.Add (new Evolution (new Term[] { new Term (null, null) }));
            Random rnd = new Random ();
            while (true) {
                // run old generation
                foreach (var val in values) {
                    CodeStatementCollection stat = generateCodeDomFromString (val.term);
                    long fitness = CompileAndInvoke (stat, false);
                    val.score = fitness;
                    System.Console.WriteLine ("Fitness: {0}", fitness);
                }
                Evolution best = values.Aggregate ((i1, i2) => i1.score < i2.score ? i1 : i2);
                CodeStatementCollection bestcoll = generateCodeDomFromString (best.term);
                CompileAndInvoke (bestcoll, true);
                System.Console.WriteLine ("Best fitness for this run: {0}", best.score);

                if (best.score == 0)
                    break;

                // generate new generation
                List<Evolution> top = values.OrderBy (i => i.score).Take (3).ToList();
                values = new List<Evolution> ();
                foreach (var e in top) {
                    values.Add (e);
                    if (e.term.Length < 16) {
                        Term[] newTerm = new Term[e.term.Length + 1];
                        for (int i = 0; i < e.term.Length; i++) {
                            newTerm [i] = e.term [i];
                        }
                        int rrr = rnd.Next (0, 17);
                        newTerm [e.term.Length] = new Term ((int)Math.Pow(2,rrr), rrr);
                        values.Add (new Evolution (newTerm));
                    }
                    {
                        int r = rnd.Next (0, e.term.Length);
                        Term[] newTerm = (Term[])e.term.Clone ();
                        int rrr = rnd.Next (0, 17);
                        newTerm [r] = new Term ((int)Math.Pow(2,rrr), rrr);
                        values.Add (new Evolution (newTerm));
                    }
                }
            }
        }

        public struct Term {
            public int? and;
            public int? shift;

            public Term(int? and, int? shift) {
                if (and!=0) {
                    this.and = and;
                } else this.and = null;
                if (shift!=0) {
                    this.shift = shift;
                } else this.shift=null;
            }
        }

        public class Evolution {
            public Term[] term;
            public long score;

            public Evolution(Term[] term) {
                this.term = term;
            }
        }
    }
}

```

Tested on OSX with Mono C# compiler version 3.2.6.0.

At each iteration it prints the fitness value of the current calculation. At the end it will print the best solution along with its fitness. The loop will run until one of the results have a fitness value of 0.

This is how it starts:

```
// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return i;
        }
    }
}

Best fitness for this run: 49940387

```

And after a while (takes around 30 minutes), this is how it ends (showing the last and almost last iteration):

```
// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return ((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 128) / 128)) + ((i & 65536) / 65536)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048));
        }
    }
}

Best fitness for this run: 4992
Fitness: 4992
Fitness: 7040
Fitness: 4993
Fitness: 4992
Fitness: 0
Fitness: 4992
Fitness: 4992
Fitness: 7496
// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return (((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 64) / 64)) + ((i & 32768) / 32768)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048)) + ((i & 32768) / 32768));
        }
    }
}

Best fitness for this run: 0

```

Notes:

1. CodeDOM doesn't support the left shift operator so instead of `a >> b` I'm using `a / 2^b`
2. The initial iteration is just a `return i;` as required by the problem.
3. In the first few iterations priority is given to adding new terms (genes) to the sum. Later there is more priority in changing values (mutation) in terms randomly.
4. I'm generating terms that look like `i & a >> a` instead of `i & a >> b`, as in the latter case the evolution was simply too slow to be practical.
5. This is also why the solution is limited to finding an answer in the form `return (i&a>>b)+(i&c>>d)+...`, as any other kind (like trying to generate a "proper" code, with loops, assignments, condition checks, etc.) would simply converge too slowly. Also this way it is very easy to define the genes (each of the term), and is very easy to mutate them.
6. This is also the reason why I'm adding the digits in base 2 (the base wasn't specified in the problem statement, so I consider this fine). A base 10 solution would've been just to slow, and also it would've been really hard to define the actual genes. Adding a loop would also mean that you have to manage the running code, and find a possible way to kill it, before it enters a potentially infinite loop.
7. Genes are only mutated, there is no crossover in this solution. I don't know whether adding that would speed up the evolution process or not.
8. The solution is only tested for numbers `0..10000` (if you check the found solution you can see that it won't work for numbers larger than 16384)
9. The whole evolution process can be checked at this gist.

# Answer
> 3 votes
## Javascript

Well, I got some floating point precision issue with my answer - that can probably be solved using a BigDecimal library - when input numbers are larger than `55`.
Yes, that's far from `10000` so I don't expect to win but still an interesting method based on this topic.
It compute a \[polynomial interpolation\] (http://en.wikipedia.org/wiki/Polynomial\_interpolation) based on a set of points, so it use only multiplication, division and addition, no modulo or bitwise operators.

```
//used to compute real values
function correct(i) {
  var s = i.toString();
  var o=0;
  for (var i=0; i<s.length; i++) {
    o+=parseInt(s[i]);
  }
  return o;
}

function digitsum(i){return i}
//can be replaced by anything like :
//function digitsum(i){return (Math.sin(i*i)+2*Math.sqrt(i)))}

for (var j=0; j<60; j++) {
  var p = correct(j+1)-digitsum(j+1);
  if (p != 0) {
    var g='Math.round(1';
    for (var k=0; k<j+1; k++) {
      g+='*((i-'+k+')/'+(j+1-k)+')';
    }
    g+=')';
    eval(digitsum.toString().replace(/{return (.*)}/, function (m,v) {
      return "{return "+v+"+"+p+"*"+g+"}";
    }));
  }
}

console.log(digitsum);

```

Output function :

```
function digitsum(i){return i+-9*Math.round(1*((i-0)/10)*((i-1)/9)*((i-2)/8)*((i-3)/7)*((i-4)/6)*((i-5)/5)*((i-6)/4)*((i-7)/3)*((i-8)/2)*((i-9)/1))+90*Math.round(1*((i-0)/11)*((i-1)/10)*((i-2)/9)*((i-3)/8)*((i-4)/7)*((i-5)/6)*((i-6)/5)*((i-7)/4)*((i-8)/3)*((i-9)/2)*((i-10)/1))+-495*Math.round(1*((i-0)/12)*((i-1)/11)*((i-2)/10)*((i-3)/9)*((i-4)/8)*((i-5)/7)*((i-6)/6)*((i-7)/5)*((i-8)/4)*((i-9)/3)*((i-10)/2)*((i-11)/1))+1980*Math.round(1*((i-0)/13)*((i-1)/12)*((i-2)/11)*((i-3)/10)*((i-4)/9)*((i-5)/8)*((i-6)/7)*((i-7)/6)*((i-8)/5)*((i-9)/4)*((i-10)/3)*((i-11)/2)*((i-12)/1))+-6435*Math.round(1*((i-0)/14)*((i-1)/13)*((i-2)/12)*((i-3)/11)*((i-4)/10)*((i-5)/9)*((i-6)/8)*((i-7)/7)*((i-8)/6)*((i-9)/5)*((i-10)/4)*((i-11)/3)*((i-12)/2)*((i-13)/1))+18018*Math.round(1*((i-0)/15)*((i-1)/14)*((i-2)/13)*((i-3)/12)*((i-4)/11)*((i-5)/10)*((i-6)/9)*((i-7)/8)*((i-8)/7)*((i-9)/6)*((i-10)/5)*((i-11)/4)*((i-12)/3)*((i-13)/2)*((i-14)/1))+-45045*Math.round(1*((i-0)/16)*((i-1)/15)*((i-2)/14)*((i-3)/13)*((i-4)/12)*((i-5)/11)*((i-6)/10)*((i-7)/9)*((i-8)/8)*((i-9)/7)*((i-10)/6)*((i-11)/5)*((i-12)/4)*((i-13)/3)*((i-14)/2)*((i-15)/1))+102960*Math.round(1*((i-0)/17)*((i-1)/16)*((i-2)/15)*((i-3)/14)*((i-4)/13)*((i-5)/12)*((i-6)/11)*((i-7)/10)*((i-8)/9)*((i-9)/8)*((i-10)/7)*((i-11)/6)*((i-12)/5)*((i-13)/4)*((i-14)/3)*((i-15)/2)*((i-16)/1))+-218790*Math.round(1*((i-0)/18)*((i-1)/17)*((i-2)/16)*((i-3)/15)*((i-4)/14)*((i-5)/13)*((i-6)/12)*((i-7)/11)*((i-8)/10)*((i-9)/9)*((i-10)/8)*((i-11)/7)*((i-12)/6)*((i-13)/5)*((i-14)/4)*((i-15)/3)*((i-16)/2)*((i-17)/1))+437580*Math.round(1*((i-0)/19)*((i-1)/18)*((i-2)/17)*((i-3)/16)*((i-4)/15)*((i-5)/14)*((i-6)/13)*((i-7)/12)*((i-8)/11)*((i-9)/10)*((i-10)/9)*((i-11)/8)*((i-12)/7)*((i-13)/6)*((i-14)/5)*((i-15)/4)*((i-16)/3)*((i-17)/2)*((i-18)/1))+-831411*Math.round(1*((i-0)/20)*((i-1)/19)*((i-2)/18)*((i-3)/17)*((i-4)/16)*((i-5)/15)*((i-6)/14)*((i-7)/13)*((i-8)/12)*((i-9)/11)*((i-10)/10)*((i-11)/9)*((i-12)/8)*((i-13)/7)*((i-14)/6)*((i-15)/5)*((i-16)/4)*((i-17)/3)*((i-18)/2)*((i-19)/1))+1511820*Math.round(1*((i-0)/21)*((i-1)/20)*((i-2)/19)*((i-3)/18)*((i-4)/17)*((i-5)/16)*((i-6)/15)*((i-7)/14)*((i-8)/13)*((i-9)/12)*((i-10)/11)*((i-11)/10)*((i-12)/9)*((i-13)/8)*((i-14)/7)*((i-15)/6)*((i-16)/5)*((i-17)/4)*((i-18)/3)*((i-19)/2)*((i-20)/1))+-2647260*Math.round(1*((i-0)/22)*((i-1)/21)*((i-2)/20)*((i-3)/19)*((i-4)/18)*((i-5)/17)*((i-6)/16)*((i-7)/15)*((i-8)/14)*((i-9)/13)*((i-10)/12)*((i-11)/11)*((i-12)/10)*((i-13)/9)*((i-14)/8)*((i-15)/7)*((i-16)/6)*((i-17)/5)*((i-18)/4)*((i-19)/3)*((i-20)/2)*((i-21)/1))+4490640*Math.round(1*((i-0)/23)*((i-1)/22)*((i-2)/21)*((i-3)/20)*((i-4)/19)*((i-5)/18)*((i-6)/17)*((i-7)/16)*((i-8)/15)*((i-9)/14)*((i-10)/13)*((i-11)/12)*((i-12)/11)*((i-13)/10)*((i-14)/9)*((i-15)/8)*((i-16)/7)*((i-17)/6)*((i-18)/5)*((i-19)/4)*((i-20)/3)*((i-21)/2)*((i-22)/1))+-7434405*Math.round(1*((i-0)/24)*((i-1)/23)*((i-2)/22)*((i-3)/21)*((i-4)/20)*((i-5)/19)*((i-6)/18)*((i-7)/17)*((i-8)/16)*((i-9)/15)*((i-10)/14)*((i-11)/13)*((i-12)/12)*((i-13)/11)*((i-14)/10)*((i-15)/9)*((i-16)/8)*((i-17)/7)*((i-18)/6)*((i-19)/5)*((i-20)/4)*((i-21)/3)*((i-22)/2)*((i-23)/1))+12150072*Math.round(1*((i-0)/25)*((i-1)/24)*((i-2)/23)*((i-3)/22)*((i-4)/21)*((i-5)/20)*((i-6)/19)*((i-7)/18)*((i-8)/17)*((i-9)/16)*((i-10)/15)*((i-11)/14)*((i-12)/13)*((i-13)/12)*((i-14)/11)*((i-15)/10)*((i-16)/9)*((i-17)/8)*((i-18)/7)*((i-19)/6)*((i-20)/5)*((i-21)/4)*((i-22)/3)*((i-23)/2)*((i-24)/1))+-19980675*Math.round(1*((i-0)/26)*((i-1)/25)*((i-2)/24)*((i-3)/23)*((i-4)/22)*((i-5)/21)*((i-6)/20)*((i-7)/19)*((i-8)/18)*((i-9)/17)*((i-10)/16)*((i-11)/15)*((i-12)/14)*((i-13)/13)*((i-14)/12)*((i-15)/11)*((i-16)/10)*((i-17)/9)*((i-18)/8)*((i-19)/7)*((i-20)/6)*((i-21)/5)*((i-22)/4)*((i-23)/3)*((i-24)/2)*((i-25)/1))+34041150*Math.round(1*((i-0)/27)*((i-1)/26)*((i-2)/25)*((i-3)/24)*((i-4)/23)*((i-5)/22)*((i-6)/21)*((i-7)/20)*((i-8)/19)*((i-9)/18)*((i-10)/17)*((i-11)/16)*((i-12)/15)*((i-13)/14)*((i-14)/13)*((i-15)/12)*((i-16)/11)*((i-17)/10)*((i-18)/9)*((i-19)/8)*((i-20)/7)*((i-21)/6)*((i-22)/5)*((i-23)/4)*((i-24)/3)*((i-25)/2)*((i-26)/1))+-62162100*Math.round(1*((i-0)/28)*((i-1)/27)*((i-2)/26)*((i-3)/25)*((i-4)/24)*((i-5)/23)*((i-6)/22)*((i-7)/21)*((i-8)/20)*((i-9)/19)*((i-10)/18)*((i-11)/17)*((i-12)/16)*((i-13)/15)*((i-14)/14)*((i-15)/13)*((i-16)/12)*((i-17)/11)*((i-18)/10)*((i-19)/9)*((i-20)/8)*((i-21)/7)*((i-22)/6)*((i-23)/5)*((i-24)/4)*((i-25)/3)*((i-26)/2)*((i-27)/1))+124324200*Math.round(1*((i-0)/29)*((i-1)/28)*((i-2)/27)*((i-3)/26)*((i-4)/25)*((i-5)/24)*((i-6)/23)*((i-7)/22)*((i-8)/21)*((i-9)/20)*((i-10)/19)*((i-11)/18)*((i-12)/17)*((i-13)/16)*((i-14)/15)*((i-15)/14)*((i-16)/13)*((i-17)/12)*((i-18)/11)*((i-19)/10)*((i-20)/9)*((i-21)/8)*((i-22)/7)*((i-23)/6)*((i-24)/5)*((i-25)/4)*((i-26)/3)*((i-27)/2)*((i-28)/1))+-270405144*Math.round(1*((i-0)/30)*((i-1)/29)*((i-2)/28)*((i-3)/27)*((i-4)/26)*((i-5)/25)*((i-6)/24)*((i-7)/23)*((i-8)/22)*((i-9)/21)*((i-10)/20)*((i-11)/19)*((i-12)/18)*((i-13)/17)*((i-14)/16)*((i-15)/15)*((i-16)/14)*((i-17)/13)*((i-18)/12)*((i-19)/11)*((i-20)/10)*((i-21)/9)*((i-22)/8)*((i-23)/7)*((i-24)/6)*((i-25)/5)*((i-26)/4)*((i-27)/3)*((i-28)/2)*((i-29)/1))+620410320*Math.round(1*((i-0)/31)*((i-1)/30)*((i-2)/29)*((i-3)/28)*((i-4)/27)*((i-5)/26)*((i-6)/25)*((i-7)/24)*((i-8)/23)*((i-9)/22)*((i-10)/21)*((i-11)/20)*((i-12)/19)*((i-13)/18)*((i-14)/17)*((i-15)/16)*((i-16)/15)*((i-17)/14)*((i-18)/13)*((i-19)/12)*((i-20)/11)*((i-21)/10)*((i-22)/9)*((i-23)/8)*((i-24)/7)*((i-25)/6)*((i-26)/5)*((i-27)/4)*((i-28)/3)*((i-29)/2)*((i-30)/1))+-1451529585*Math.round(1*((i-0)/32)*((i-1)/31)*((i-2)/30)*((i-3)/29)*((i-4)/28)*((i-5)/27)*((i-6)/26)*((i-7)/25)*((i-8)/24)*((i-9)/23)*((i-10)/22)*((i-11)/21)*((i-12)/20)*((i-13)/19)*((i-14)/18)*((i-15)/17)*((i-16)/16)*((i-17)/15)*((i-18)/14)*((i-19)/13)*((i-20)/12)*((i-21)/11)*((i-22)/10)*((i-23)/9)*((i-24)/8)*((i-25)/7)*((i-26)/6)*((i-27)/5)*((i-28)/4)*((i-29)/3)*((i-30)/2)*((i-31)/1))+3378846240*Math.round(1*((i-0)/33)*((i-1)/32)*((i-2)/31)*((i-3)/30)*((i-4)/29)*((i-5)/28)*((i-6)/27)*((i-7)/26)*((i-8)/25)*((i-9)/24)*((i-10)/23)*((i-11)/22)*((i-12)/21)*((i-13)/20)*((i-14)/19)*((i-15)/18)*((i-16)/17)*((i-17)/16)*((i-18)/15)*((i-19)/14)*((i-20)/13)*((i-21)/12)*((i-22)/11)*((i-23)/10)*((i-24)/9)*((i-25)/8)*((i-26)/7)*((i-27)/6)*((i-28)/5)*((i-29)/4)*((i-30)/3)*((i-31)/2)*((i-32)/1))+-7716754980*Math.round(1*((i-0)/34)*((i-1)/33)*((i-2)/32)*((i-3)/31)*((i-4)/30)*((i-5)/29)*((i-6)/28)*((i-7)/27)*((i-8)/26)*((i-9)/25)*((i-10)/24)*((i-11)/23)*((i-12)/22)*((i-13)/21)*((i-14)/20)*((i-15)/19)*((i-16)/18)*((i-17)/17)*((i-18)/16)*((i-19)/15)*((i-20)/14)*((i-21)/13)*((i-22)/12)*((i-23)/11)*((i-24)/10)*((i-25)/9)*((i-26)/8)*((i-27)/7)*((i-28)/6)*((i-29)/5)*((i-30)/4)*((i-31)/3)*((i-32)/2)*((i-33)/1))+17178273288*Math.round(1*((i-0)/35)*((i-1)/34)*((i-2)/33)*((i-3)/32)*((i-4)/31)*((i-5)/30)*((i-6)/29)*((i-7)/28)*((i-8)/27)*((i-9)/26)*((i-10)/25)*((i-11)/24)*((i-12)/23)*((i-13)/22)*((i-14)/21)*((i-15)/20)*((i-16)/19)*((i-17)/18)*((i-18)/17)*((i-19)/16)*((i-20)/15)*((i-21)/14)*((i-22)/13)*((i-23)/12)*((i-24)/11)*((i-25)/10)*((i-26)/9)*((i-27)/8)*((i-28)/7)*((i-29)/6)*((i-30)/5)*((i-31)/4)*((i-32)/3)*((i-33)/2)*((i-34)/1))+-37189436130*Math.round(1*((i-0)/36)*((i-1)/35)*((i-2)/34)*((i-3)/33)*((i-4)/32)*((i-5)/31)*((i-6)/30)*((i-7)/29)*((i-8)/28)*((i-9)/27)*((i-10)/26)*((i-11)/25)*((i-12)/24)*((i-13)/23)*((i-14)/22)*((i-15)/21)*((i-16)/20)*((i-17)/19)*((i-18)/18)*((i-19)/17)*((i-20)/16)*((i-21)/15)*((i-22)/14)*((i-23)/13)*((i-24)/12)*((i-25)/11)*((i-26)/10)*((i-27)/9)*((i-28)/8)*((i-29)/7)*((i-30)/6)*((i-31)/5)*((i-32)/4)*((i-33)/3)*((i-34)/2)*((i-35)/1))+78299888041*Math.round(1*((i-0)/37)*((i-1)/36)*((i-2)/35)*((i-3)/34)*((i-4)/33)*((i-5)/32)*((i-6)/31)*((i-7)/30)*((i-8)/29)*((i-9)/28)*((i-10)/27)*((i-11)/26)*((i-12)/25)*((i-13)/24)*((i-14)/23)*((i-15)/22)*((i-16)/21)*((i-17)/20)*((i-18)/19)*((i-19)/18)*((i-20)/17)*((i-21)/16)*((i-22)/15)*((i-23)/14)*((i-24)/13)*((i-25)/12)*((i-26)/11)*((i-27)/10)*((i-28)/9)*((i-29)/8)*((i-30)/7)*((i-31)/6)*((i-32)/5)*((i-33)/4)*((i-34)/3)*((i-35)/2)*((i-36)/1))+-160520791904*Math.round(1*((i-0)/38)*((i-1)/37)*((i-2)/36)*((i-3)/35)*((i-4)/34)*((i-5)/33)*((i-6)/32)*((i-7)/31)*((i-8)/30)*((i-9)/29)*((i-10)/28)*((i-11)/27)*((i-12)/26)*((i-13)/25)*((i-14)/24)*((i-15)/23)*((i-16)/22)*((i-17)/21)*((i-18)/20)*((i-19)/19)*((i-20)/18)*((i-21)/17)*((i-22)/16)*((i-23)/15)*((i-24)/14)*((i-25)/13)*((i-26)/12)*((i-27)/11)*((i-28)/10)*((i-29)/9)*((i-30)/8)*((i-31)/7)*((i-32)/6)*((i-33)/5)*((i-34)/4)*((i-35)/3)*((i-36)/2)*((i-37)/1))+321041584713*Math.round(1*((i-0)/39)*((i-1)/38)*((i-2)/37)*((i-3)/36)*((i-4)/35)*((i-5)/34)*((i-6)/33)*((i-7)/32)*((i-8)/31)*((i-9)/30)*((i-10)/29)*((i-11)/28)*((i-12)/27)*((i-13)/26)*((i-14)/25)*((i-15)/24)*((i-16)/23)*((i-17)/22)*((i-18)/21)*((i-19)/20)*((i-20)/19)*((i-21)/18)*((i-22)/17)*((i-23)/16)*((i-24)/15)*((i-25)/14)*((i-26)/13)*((i-27)/12)*((i-28)/11)*((i-29)/10)*((i-30)/9)*((i-31)/8)*((i-32)/7)*((i-33)/6)*((i-34)/5)*((i-35)/4)*((i-36)/3)*((i-37)/2)*((i-38)/1))+-627938339760*Math.round(1*((i-0)/40)*((i-1)/39)*((i-2)/38)*((i-3)/37)*((i-4)/36)*((i-5)/35)*((i-6)/34)*((i-7)/33)*((i-8)/32)*((i-9)/31)*((i-10)/30)*((i-11)/29)*((i-12)/28)*((i-13)/27)*((i-14)/26)*((i-15)/25)*((i-16)/24)*((i-17)/23)*((i-18)/22)*((i-19)/21)*((i-20)/20)*((i-21)/19)*((i-22)/18)*((i-23)/17)*((i-24)/16)*((i-25)/15)*((i-26)/14)*((i-27)/13)*((i-28)/12)*((i-29)/11)*((i-30)/10)*((i-31)/9)*((i-32)/8)*((i-33)/7)*((i-34)/6)*((i-35)/5)*((i-36)/4)*((i-37)/3)*((i-38)/2)*((i-39)/1))+1204809019815*Math.round(1*((i-0)/41)*((i-1)/40)*((i-2)/39)*((i-3)/38)*((i-4)/37)*((i-5)/36)*((i-6)/35)*((i-7)/34)*((i-8)/33)*((i-9)/32)*((i-10)/31)*((i-11)/30)*((i-12)/29)*((i-13)/28)*((i-14)/27)*((i-15)/26)*((i-16)/25)*((i-17)/24)*((i-18)/23)*((i-19)/22)*((i-20)/21)*((i-21)/20)*((i-22)/19)*((i-23)/18)*((i-24)/17)*((i-25)/16)*((i-26)/15)*((i-27)/14)*((i-28)/13)*((i-29)/12)*((i-30)/11)*((i-31)/10)*((i-32)/9)*((i-33)/8)*((i-34)/7)*((i-35)/6)*((i-36)/5)*((i-37)/4)*((i-38)/3)*((i-39)/2)*((i-40)/1))+-2276206770520*Math.round(1*((i-0)/42)*((i-1)/41)*((i-2)/40)*((i-3)/39)*((i-4)/38)*((i-5)/37)*((i-6)/36)*((i-7)/35)*((i-8)/34)*((i-9)/33)*((i-10)/32)*((i-11)/31)*((i-12)/30)*((i-13)/29)*((i-14)/28)*((i-15)/27)*((i-16)/26)*((i-17)/25)*((i-18)/24)*((i-19)/23)*((i-20)/22)*((i-21)/21)*((i-22)/20)*((i-23)/19)*((i-24)/18)*((i-25)/17)*((i-26)/16)*((i-27)/15)*((i-28)/14)*((i-29)/13)*((i-30)/12)*((i-31)/11)*((i-32)/10)*((i-33)/9)*((i-34)/8)*((i-35)/7)*((i-36)/6)*((i-37)/5)*((i-38)/4)*((i-39)/3)*((i-40)/2)*((i-41)/1))+4254673762574*Math.round(1*((i-0)/43)*((i-1)/42)*((i-2)/41)*((i-3)/40)*((i-4)/39)*((i-5)/38)*((i-6)/37)*((i-7)/36)*((i-8)/35)*((i-9)/34)*((i-10)/33)*((i-11)/32)*((i-12)/31)*((i-13)/30)*((i-14)/29)*((i-15)/28)*((i-16)/27)*((i-17)/26)*((i-18)/25)*((i-19)/24)*((i-20)/23)*((i-21)/22)*((i-22)/21)*((i-23)/20)*((i-24)/19)*((i-25)/18)*((i-26)/17)*((i-27)/16)*((i-28)/15)*((i-29)/14)*((i-30)/13)*((i-31)/12)*((i-32)/11)*((i-33)/10)*((i-34)/9)*((i-35)/8)*((i-36)/7)*((i-37)/6)*((i-38)/5)*((i-39)/4)*((i-40)/3)*((i-41)/2)*((i-42)/1))+-7914840120452*Math.round(1*((i-0)/44)*((i-1)/43)*((i-2)/42)*((i-3)/41)*((i-4)/40)*((i-5)/39)*((i-6)/38)*((i-7)/37)*((i-8)/36)*((i-9)/35)*((i-10)/34)*((i-11)/33)*((i-12)/32)*((i-13)/31)*((i-14)/30)*((i-15)/29)*((i-16)/28)*((i-17)/27)*((i-18)/26)*((i-19)/25)*((i-20)/24)*((i-21)/23)*((i-22)/22)*((i-23)/21)*((i-24)/20)*((i-25)/19)*((i-26)/18)*((i-27)/17)*((i-28)/16)*((i-29)/15)*((i-30)/14)*((i-31)/13)*((i-32)/12)*((i-33)/11)*((i-34)/10)*((i-35)/9)*((i-36)/8)*((i-37)/7)*((i-38)/6)*((i-39)/5)*((i-40)/4)*((i-41)/3)*((i-42)/2)*((i-43)/1))+14755713366633*Math.round(1*((i-0)/45)*((i-1)/44)*((i-2)/43)*((i-3)/42)*((i-4)/41)*((i-5)/40)*((i-6)/39)*((i-7)/38)*((i-8)/37)*((i-9)/36)*((i-10)/35)*((i-11)/34)*((i-12)/33)*((i-13)/32)*((i-14)/31)*((i-15)/30)*((i-16)/29)*((i-17)/28)*((i-18)/27)*((i-19)/26)*((i-20)/25)*((i-21)/24)*((i-22)/23)*((i-23)/22)*((i-24)/21)*((i-25)/20)*((i-26)/19)*((i-27)/18)*((i-28)/17)*((i-29)/16)*((i-30)/15)*((i-31)/14)*((i-32)/13)*((i-33)/12)*((i-34)/11)*((i-35)/10)*((i-36)/9)*((i-37)/8)*((i-38)/7)*((i-39)/6)*((i-40)/5)*((i-41)/4)*((i-42)/3)*((i-43)/2)*((i-44)/1))+-27776520662160*Math.round(1*((i-0)/46)*((i-1)/45)*((i-2)/44)*((i-3)/43)*((i-4)/42)*((i-5)/41)*((i-6)/40)*((i-7)/39)*((i-8)/38)*((i-9)/37)*((i-10)/36)*((i-11)/35)*((i-12)/34)*((i-13)/33)*((i-14)/32)*((i-15)/31)*((i-16)/30)*((i-17)/29)*((i-18)/28)*((i-19)/27)*((i-20)/26)*((i-21)/25)*((i-22)/24)*((i-23)/23)*((i-24)/22)*((i-25)/21)*((i-26)/20)*((i-27)/19)*((i-28)/18)*((i-29)/17)*((i-30)/16)*((i-31)/15)*((i-32)/14)*((i-33)/13)*((i-34)/12)*((i-35)/11)*((i-36)/10)*((i-37)/9)*((i-38)/8)*((i-39)/7)*((i-40)/6)*((i-41)/5)*((i-42)/4)*((i-43)/3)*((i-44)/2)*((i-45)/1))+53164054207611*Math.round(1*((i-0)/47)*((i-1)/46)*((i-2)/45)*((i-3)/44)*((i-4)/43)*((i-5)/42)*((i-6)/41)*((i-7)/40)*((i-8)/39)*((i-9)/38)*((i-10)/37)*((i-11)/36)*((i-12)/35)*((i-13)/34)*((i-14)/33)*((i-15)/32)*((i-16)/31)*((i-17)/30)*((i-18)/29)*((i-19)/28)*((i-20)/27)*((i-21)/26)*((i-22)/25)*((i-23)/24)*((i-24)/23)*((i-25)/22)*((i-26)/21)*((i-27)/20)*((i-28)/19)*((i-29)/18)*((i-30)/17)*((i-31)/16)*((i-32)/15)*((i-33)/14)*((i-34)/13)*((i-35)/12)*((i-36)/11)*((i-37)/10)*((i-38)/9)*((i-39)/8)*((i-40)/7)*((i-41)/6)*((i-42)/5)*((i-43)/4)*((i-44)/3)*((i-45)/2)*((i-46)/1))+-103975831339140*Math.round(1*((i-0)/48)*((i-1)/47)*((i-2)/46)*((i-3)/45)*((i-4)/44)*((i-5)/43)*((i-6)/42)*((i-7)/41)*((i-8)/40)*((i-9)/39)*((i-10)/38)*((i-11)/37)*((i-12)/36)*((i-13)/35)*((i-14)/34)*((i-15)/33)*((i-16)/32)*((i-17)/31)*((i-18)/30)*((i-19)/29)*((i-20)/28)*((i-21)/27)*((i-22)/26)*((i-23)/25)*((i-24)/24)*((i-25)/23)*((i-26)/22)*((i-27)/21)*((i-28)/20)*((i-29)/19)*((i-30)/18)*((i-31)/17)*((i-32)/16)*((i-33)/15)*((i-34)/14)*((i-35)/13)*((i-36)/12)*((i-37)/11)*((i-38)/10)*((i-39)/9)*((i-40)/8)*((i-41)/7)*((i-42)/6)*((i-43)/5)*((i-44)/4)*((i-45)/3)*((i-46)/2)*((i-47)/1))+208138306632137*Math.round(1*((i-0)/49)*((i-1)/48)*((i-2)/47)*((i-3)/46)*((i-4)/45)*((i-5)/44)*((i-6)/43)*((i-7)/42)*((i-8)/41)*((i-9)/40)*((i-10)/39)*((i-11)/38)*((i-12)/37)*((i-13)/36)*((i-14)/35)*((i-15)/34)*((i-16)/33)*((i-17)/32)*((i-18)/31)*((i-19)/30)*((i-20)/29)*((i-21)/28)*((i-22)/27)*((i-23)/26)*((i-24)/25)*((i-25)/24)*((i-26)/23)*((i-27)/22)*((i-28)/21)*((i-29)/20)*((i-30)/19)*((i-31)/18)*((i-32)/17)*((i-33)/16)*((i-34)/15)*((i-35)/14)*((i-36)/13)*((i-37)/12)*((i-38)/11)*((i-39)/10)*((i-40)/9)*((i-41)/8)*((i-42)/7)*((i-43)/6)*((i-44)/5)*((i-45)/4)*((i-46)/3)*((i-47)/2)*((i-48)/1))+-425620349055645*Math.round(1*((i-0)/50)*((i-1)/49)*((i-2)/48)*((i-3)/47)*((i-4)/46)*((i-5)/45)*((i-6)/44)*((i-7)/43)*((i-8)/42)*((i-9)/41)*((i-10)/40)*((i-11)/39)*((i-12)/38)*((i-13)/37)*((i-14)/36)*((i-15)/35)*((i-16)/34)*((i-17)/33)*((i-18)/32)*((i-19)/31)*((i-20)/30)*((i-21)/29)*((i-22)/28)*((i-23)/27)*((i-24)/26)*((i-25)/25)*((i-26)/24)*((i-27)/23)*((i-28)/22)*((i-29)/21)*((i-30)/20)*((i-31)/19)*((i-32)/18)*((i-33)/17)*((i-34)/16)*((i-35)/15)*((i-36)/14)*((i-37)/13)*((i-38)/12)*((i-39)/11)*((i-40)/10)*((i-41)/9)*((i-42)/8)*((i-43)/7)*((i-44)/6)*((i-45)/5)*((i-46)/4)*((i-47)/3)*((i-48)/2)*((i-49)/1))+884722839970606*Math.round(1*((i-0)/51)*((i-1)/50)*((i-2)/49)*((i-3)/48)*((i-4)/47)*((i-5)/46)*((i-6)/45)*((i-7)/44)*((i-8)/43)*((i-9)/42)*((i-10)/41)*((i-11)/40)*((i-12)/39)*((i-13)/38)*((i-14)/37)*((i-15)/36)*((i-16)/35)*((i-17)/34)*((i-18)/33)*((i-19)/32)*((i-20)/31)*((i-21)/30)*((i-22)/29)*((i-23)/28)*((i-24)/27)*((i-25)/26)*((i-26)/25)*((i-27)/24)*((i-28)/23)*((i-29)/22)*((i-30)/21)*((i-31)/20)*((i-32)/19)*((i-33)/18)*((i-34)/17)*((i-35)/16)*((i-36)/15)*((i-37)/14)*((i-38)/13)*((i-39)/12)*((i-40)/11)*((i-41)/10)*((i-42)/9)*((i-43)/8)*((i-44)/7)*((i-45)/6)*((i-46)/5)*((i-47)/4)*((i-48)/3)*((i-49)/2)*((i-50)/1))+-1857183748827153*Math.round(1*((i-0)/52)*((i-1)/51)*((i-2)/50)*((i-3)/49)*((i-4)/48)*((i-5)/47)*((i-6)/46)*((i-7)/45)*((i-8)/44)*((i-9)/43)*((i-10)/42)*((i-11)/41)*((i-12)/40)*((i-13)/39)*((i-14)/38)*((i-15)/37)*((i-16)/36)*((i-17)/35)*((i-18)/34)*((i-19)/33)*((i-20)/32)*((i-21)/31)*((i-22)/30)*((i-23)/29)*((i-24)/28)*((i-25)/27)*((i-26)/26)*((i-27)/25)*((i-28)/24)*((i-29)/23)*((i-30)/22)*((i-31)/21)*((i-32)/20)*((i-33)/19)*((i-34)/18)*((i-35)/17)*((i-36)/16)*((i-37)/15)*((i-38)/14)*((i-39)/13)*((i-40)/12)*((i-41)/11)*((i-42)/10)*((i-43)/9)*((i-44)/8)*((i-45)/7)*((i-46)/6)*((i-47)/5)*((i-48)/4)*((i-49)/3)*((i-50)/2)*((i-51)/1))+3909404796652936*Math.round(1*((i-0)/53)*((i-1)/52)*((i-2)/51)*((i-3)/50)*((i-4)/49)*((i-5)/48)*((i-6)/47)*((i-7)/46)*((i-8)/45)*((i-9)/44)*((i-10)/43)*((i-11)/42)*((i-12)/41)*((i-13)/40)*((i-14)/39)*((i-15)/38)*((i-16)/37)*((i-17)/36)*((i-18)/35)*((i-19)/34)*((i-20)/33)*((i-21)/32)*((i-22)/31)*((i-23)/30)*((i-24)/29)*((i-25)/28)*((i-26)/27)*((i-27)/26)*((i-28)/25)*((i-29)/24)*((i-30)/23)*((i-31)/22)*((i-32)/21)*((i-33)/20)*((i-34)/19)*((i-35)/18)*((i-36)/17)*((i-37)/16)*((i-38)/15)*((i-39)/14)*((i-40)/13)*((i-41)/12)*((i-42)/11)*((i-43)/10)*((i-44)/9)*((i-45)/8)*((i-46)/7)*((i-47)/6)*((i-48)/5)*((i-49)/4)*((i-50)/3)*((i-51)/2)*((i-52)/1))+-8195615777370807*Math.round(1*((i-0)/54)*((i-1)/53)*((i-2)/52)*((i-3)/51)*((i-4)/50)*((i-5)/49)*((i-6)/48)*((i-7)/47)*((i-8)/46)*((i-9)/45)*((i-10)/44)*((i-11)/43)*((i-12)/42)*((i-13)/41)*((i-14)/40)*((i-15)/39)*((i-16)/38)*((i-17)/37)*((i-18)/36)*((i-19)/35)*((i-20)/34)*((i-21)/33)*((i-22)/32)*((i-23)/31)*((i-24)/30)*((i-25)/29)*((i-26)/28)*((i-27)/27)*((i-28)/26)*((i-29)/25)*((i-30)/24)*((i-31)/23)*((i-32)/22)*((i-33)/21)*((i-34)/20)*((i-35)/19)*((i-36)/18)*((i-37)/17)*((i-38)/16)*((i-39)/15)*((i-40)/14)*((i-41)/13)*((i-42)/12)*((i-43)/11)*((i-44)/10)*((i-45)/9)*((i-46)/8)*((i-47)/7)*((i-48)/6)*((i-49)/5)*((i-50)/4)*((i-51)/3)*((i-52)/2)*((i-53)/1))+16994979589974346*Math.round(1*((i-0)/55)*((i-1)/54)*((i-2)/53)*((i-3)/52)*((i-4)/51)*((i-5)/50)*((i-6)/49)*((i-7)/48)*((i-8)/47)*((i-9)/46)*((i-10)/45)*((i-11)/44)*((i-12)/43)*((i-13)/42)*((i-14)/41)*((i-15)/40)*((i-16)/39)*((i-17)/38)*((i-18)/37)*((i-19)/36)*((i-20)/35)*((i-21)/34)*((i-22)/33)*((i-23)/32)*((i-24)/31)*((i-25)/30)*((i-26)/29)*((i-27)/28)*((i-28)/27)*((i-29)/26)*((i-30)/25)*((i-31)/24)*((i-32)/23)*((i-33)/22)*((i-34)/21)*((i-35)/20)*((i-36)/19)*((i-37)/18)*((i-38)/17)*((i-39)/16)*((i-40)/15)*((i-41)/14)*((i-42)/13)*((i-43)/12)*((i-44)/11)*((i-45)/10)*((i-46)/9)*((i-47)/8)*((i-48)/7)*((i-49)/6)*((i-50)/5)*((i-51)/4)*((i-52)/3)*((i-53)/2)*((i-54)/1))+-34598925396029428*Math.round(1*((i-0)/56)*((i-1)/55)*((i-2)/54)*((i-3)/53)*((i-4)/52)*((i-5)/51)*((i-6)/50)*((i-7)/49)*((i-8)/48)*((i-9)/47)*((i-10)/46)*((i-11)/45)*((i-12)/44)*((i-13)/43)*((i-14)/42)*((i-15)/41)*((i-16)/40)*((i-17)/39)*((i-18)/38)*((i-19)/37)*((i-20)/36)*((i-21)/35)*((i-22)/34)*((i-23)/33)*((i-24)/32)*((i-25)/31)*((i-26)/30)*((i-27)/29)*((i-28)/28)*((i-29)/27)*((i-30)/26)*((i-31)/25)*((i-32)/24)*((i-33)/23)*((i-34)/22)*((i-35)/21)*((i-36)/20)*((i-37)/19)*((i-38)/18)*((i-39)/17)*((i-40)/16)*((i-41)/15)*((i-42)/14)*((i-43)/13)*((i-44)/12)*((i-45)/11)*((i-46)/10)*((i-47)/9)*((i-48)/8)*((i-49)/7)*((i-50)/6)*((i-51)/5)*((i-52)/4)*((i-53)/3)*((i-54)/2)*((i-55)/1))+68349348631526670*Math.round(1*((i-0)/57)*((i-1)/56)*((i-2)/55)*((i-3)/54)*((i-4)/53)*((i-5)/52)*((i-6)/51)*((i-7)/50)*((i-8)/49)*((i-9)/48)*((i-10)/47)*((i-11)/46)*((i-12)/45)*((i-13)/44)*((i-14)/43)*((i-15)/42)*((i-16)/41)*((i-17)/40)*((i-18)/39)*((i-19)/38)*((i-20)/37)*((i-21)/36)*((i-22)/35)*((i-23)/34)*((i-24)/33)*((i-25)/32)*((i-26)/31)*((i-27)/30)*((i-28)/29)*((i-29)/28)*((i-30)/27)*((i-31)/26)*((i-32)/25)*((i-33)/24)*((i-34)/23)*((i-35)/22)*((i-36)/21)*((i-37)/20)*((i-38)/19)*((i-39)/18)*((i-40)/17)*((i-41)/16)*((i-42)/15)*((i-43)/14)*((i-44)/13)*((i-45)/12)*((i-46)/11)*((i-47)/10)*((i-48)/9)*((i-49)/8)*((i-50)/7)*((i-51)/6)*((i-52)/5)*((i-53)/4)*((i-54)/3)*((i-55)/2)*((i-56)/1))+-126849859681465840*Math.round(1*((i-0)/58)*((i-1)/57)*((i-2)/56)*((i-3)/55)*((i-4)/54)*((i-5)/53)*((i-6)/52)*((i-7)/51)*((i-8)/50)*((i-9)/49)*((i-10)/48)*((i-11)/47)*((i-12)/46)*((i-13)/45)*((i-14)/44)*((i-15)/43)*((i-16)/42)*((i-17)/41)*((i-18)/40)*((i-19)/39)*((i-20)/38)*((i-21)/37)*((i-22)/36)*((i-23)/35)*((i-24)/34)*((i-25)/33)*((i-26)/32)*((i-27)/31)*((i-28)/30)*((i-29)/29)*((i-30)/28)*((i-31)/27)*((i-32)/26)*((i-33)/25)*((i-34)/24)*((i-35)/23)*((i-36)/22)*((i-37)/21)*((i-38)/20)*((i-39)/19)*((i-40)/18)*((i-41)/17)*((i-42)/16)*((i-43)/15)*((i-44)/14)*((i-45)/13)*((i-46)/12)*((i-47)/11)*((i-48)/10)*((i-49)/9)*((i-50)/8)*((i-51)/7)*((i-52)/6)*((i-53)/5)*((i-54)/4)*((i-55)/3)*((i-56)/2)*((i-57)/1))+189776303470473200*Math.round(1*((i-0)/59)*((i-1)/58)*((i-2)/57)*((i-3)/56)*((i-4)/55)*((i-5)/54)*((i-6)/53)*((i-7)/52)*((i-8)/51)*((i-9)/50)*((i-10)/49)*((i-11)/48)*((i-12)/47)*((i-13)/46)*((i-14)/45)*((i-15)/44)*((i-16)/43)*((i-17)/42)*((i-18)/41)*((i-19)/40)*((i-20)/39)*((i-21)/38)*((i-22)/37)*((i-23)/36)*((i-24)/35)*((i-25)/34)*((i-26)/33)*((i-27)/32)*((i-28)/31)*((i-29)/30)*((i-30)/29)*((i-31)/28)*((i-32)/27)*((i-33)/26)*((i-34)/25)*((i-35)/24)*((i-36)/23)*((i-37)/22)*((i-38)/21)*((i-39)/20)*((i-40)/19)*((i-41)/18)*((i-42)/17)*((i-43)/16)*((i-44)/15)*((i-45)/14)*((i-46)/13)*((i-47)/12)*((i-48)/11)*((i-49)/10)*((i-50)/9)*((i-51)/8)*((i-52)/7)*((i-53)/6)*((i-54)/5)*((i-55)/4)*((i-56)/3)*((i-57)/2)*((i-58)/1))+51028516348018696*Math.round(1*((i-0)/60)*((i-1)/59)*((i-2)/58)*((i-3)/57)*((i-4)/56)*((i-5)/55)*((i-6)/54)*((i-7)/53)*((i-8)/52)*((i-9)/51)*((i-10)/50)*((i-11)/49)*((i-12)/48)*((i-13)/47)*((i-14)/46)*((i-15)/45)*((i-16)/44)*((i-17)/43)*((i-18)/42)*((i-19)/41)*((i-20)/40)*((i-21)/39)*((i-22)/38)*((i-23)/37)*((i-24)/36)*((i-25)/35)*((i-26)/34)*((i-27)/33)*((i-28)/32)*((i-29)/31)*((i-30)/30)*((i-31)/29)*((i-32)/28)*((i-33)/27)*((i-34)/26)*((i-35)/25)*((i-36)/24)*((i-37)/23)*((i-38)/22)*((i-39)/21)*((i-40)/20)*((i-41)/19)*((i-42)/18)*((i-43)/17)*((i-44)/16)*((i-45)/15)*((i-46)/14)*((i-47)/13)*((i-48)/12)*((i-49)/11)*((i-50)/10)*((i-51)/9)*((i-52)/8)*((i-53)/7)*((i-54)/6)*((i-55)/5)*((i-56)/4)*((i-57)/3)*((i-58)/2)*((i-59)/1))}

```

This polynomial function (simplified to degree 25 and without rounding) plotted, look at values for whole numbers (readable for \[6;19\]) :

>

Tests :

```
for (var i=0; i<60; i++) { console.log(i + ' : ' + digitsum(i)) }
0 : 0
1 : 1
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 8
9 : 9
10 : 1
11 : 2
12 : 3
13 : 4
14 : 5
15 : 6
16 : 7
17 : 8
18 : 9
19 : 10
20 : 2
21 : 3
22 : 4
23 : 5
24 : 6
25 : 7
26 : 8
27 : 9
28 : 10
29 : 11
30 : 3
31 : 4
32 : 5
33 : 6
34 : 7
35 : 8
36 : 9
37 : 10
38 : 11
39 : 12
40 : 4
41 : 5
42 : 6
43 : 7
44 : 8
45 : 9
46 : 10
47 : 11
48 : 12
49 : 13
50 : 5
51 : 6
52 : 7
53 : 8
54 : 9
55 : 10
56 : 12 //precision issue starts here
57 : 16
58 : 16
59 : 0

```

---
Tags: popularity-contest
---