title: Find the largest fragile prime

text:
# Question
Title: Find the largest fragile prime
Consider the function `Remove(n, startIndex, count)` that removes `count` digits from the number `n` starting from the digit at position `startIndex`. Examples:

```
Remove(1234, 1, 1) = 234
Remove(123456, 2, 3) = 156
Remove(1507, 1, 2) = 07 = 7
Remove(1234, 1, 4) = 0

```

We will call the prime number X fragile if every possible `Remove` operation makes it non-prime. For example, 80651 is a fragile prime because all of the following numbers are not prime:

```
651, 51, 1, 0, 8651, 851, 81, 8, 8051, 801, 80, 8061, 806, 8065

```

## Goal

Write a program that finds the largest fragile prime. **Edit:** removed the time limit because there was a relatively fair way to circumvent it.

The score is the fragile prime number found by your program. In the event of a tie, the earlier submission wins.

## Rules

* You may use any language and any third-party libraries.
* You run the program on you own hardware.
* You may use probabilistic primality tests.
* Everything is in base 10.

## Leading entries

* 6629 digits by Qualtagh (Java)
* 5048 digits by Emil (Python 2)
* 2268 digits by Jakube (Python 2)

**Edit:** I've added my own answer.

* 28164 digits by Suboptimus Prime, based on Qualtagh's algorithm (C#)

# Answer
# Java - ~~3144~~ ~~3322~~ 6629 digits

~~`6 0{3314} 8969999`~~

```
6 0{6623} 49099

```

This solution is based on FryAmTheEggman's answer.

1. The last digit is 1 or 9.
2. If the last digit is 1 then a previous one is 0, 8 or 9.
3. If the last digit is 9 then a previous one is 0, 4, 6 or 9.
4. ...

What if we dig deeper?

It becomes a tree structure:

```
                        S
             -----------------------
             1                     9
    ------------------         ----------------
    0           8    9         0    4    6    9
---------     -----
0   8   9      ...

```

Let's call number R right composite if R and all its endings are composite.

We're gonna iterate over all right composite numbers in breadth-first manner: 1, 9, 01, 81, 91, 09, 49, 69, 99, 001, 801, 901 etc.

Numbers starting with zero are not checked for primality but are needed to build further numbers.

We will look for a target number N in the form X00...00R, where X is one of 4, 6, 8 or 9 and R is right composite. X cannot be prime. X cannot be 0. And X cannot be 1 because if R ends with 1 or 9 then N would contain 11 or 19.

If XR contains prime numbers after "remove" operation then XYR would contain them too for any Y. So we shouldn't traverse branches starting from R.

Let X be a constant, say 6.

Pseudocode:

```
X = 6;
for ( String R : breadth-first-traverse-of-all-right-composites ) {
  if ( R ends with 1 or 9 ) {
    if ( remove( X + R, i, j ) is composite for all i and j ) {
      for ( String zeros = ""; zeros.length() < LIMIT; zeros += "0" ) {
        if ( X + zeros + R is prime ) {
          // At this step these conditions hold:
          // 1. X + 0...0 is composite.
          // 2. 0...0 + R = R is composite.
          // 3. X + 0...0 + R is composite if 0...0 is shorter than zeros.
          suits = true;
          for ( E : all R endings )
            if ( X + zeros + E is prime )
              suits = false;
          if ( suits )
            print R + " is fragile prime";
          break; // try another R
                 // because ( X + zeros + 0...0 + R )
                 // would contain prime ( X + zeros + R ).
        }
      }
    }
  }
}

```

We should limit zeros quantity because it may take too long to find a prime number in form X + zeros + R (or forever if all of them are composite).

The real code is quite verbose and can be found here.

Primality testing for numbers in long int range is performed by deterministic variant of Miller test. For BigInteger numbers a trial division is performed first and then BailliePSW test. It's probabilistic but quite certain. And it's faster than Miller-Rabin test (we should do many iterations for such big numbers in Miller-Rabin to gain enough accuracy).

**Edit:** the first attempt was incorrect. We should also ignore branches starting with R if X0...0R is prime. Then X0...0YR wouldn't be fragile prime. So an additional check was added. This solution seems to be correct.

**Edit 2:** added an optimization. If ( X + R ) is divisible by 3 then ( X + zeros + R ) is also divisible by 3. So ( X + zeros + R ) cannot be prime in this case and such R's may be skipped.

**Edit 3:** it was not necessary to skip prime digits if they're not in the last or first position. So endings like 21 or 51 are ok. But it doesn't change anything much.

**Conclusions:**

1. My last answer was checking for being fragile for 100 minutes. The search of the answer (checking all preceding variants) took about 15 minutes. Yes, it makes no sense to restrict search time (we can start searching from the target number, so time would be zero). But it could be meaningful to restrict checking time like in this question.
2. The answer 60...049099 has digit 4 in the middle. If the "remove" operation touches it, the number becomes divisible by 3. So we should check remove operations in left and right sides. Right side is too short. Left side length is almost n = length( N ).
3. Primality tests like BPSW and Miller-Rabin use constant quantity of modular exponentiations. Its complexity is O( M( n ) * n ) according to this page, where M( n ) is multiplication complexity. Java uses Toom-Cook and Karatsuba algorithms but we'll take scholar algorithm for simplicity. M( n ) = n2. So primality testing complexity is O( n3 ).
4. We should check all numbers from length = 6 to 6629. Let's take min = 1 and max = n for commonality. The whole check complexity is O( 13 \+ 23 \+ ... + n3 ) = O( ( n * ( n + 1 ) / 2 )2 ) = O( n4 ).
5. Emil's answer has the same checking asymptotics. But the constant factor is lower. Digit "7" is standing in the middle of the number. Left side and right side can be almost equal. It gives ( n / 2 )4 * 2 = n4 / 8. Speedup: 8X. Numbers in the form 9...9Y9...9 can be 1.7 times longer than in the form X0...0R having the same checking time.
> 9 votes

# Answer
## Python 2 - ~~126~~ ~~1221~~ ~~1337~~ ~~1719~~ 2268 digits

```
999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999799999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999

'9' * 1944 + '7' + '9' * 323

```

There are at about len(n)^2 resulting numbers of Remove(n, startIndex, count). I tried to minimize those numbers. If there are lots of digits next to each other are the same, lots of these resulting numbers can be ignored, because they appear multiple times.

So I took it to the extreme, only 9s and a little prime in the middle. I also took a look at the fragile prime under 1 million, and saw, that there are such fragile prime. Searching for numbers with 2 9s at the end works really good, not sure why. 1 number, 3, or 4 9s at the end results in smaller fragile primes.

It uses the pyprimes module. I'm not sure, if it is any good. It uses the miller\_rabin test, so it's probabilistic.

The program find this 126-digit fragile prime in about 1 minute, and for the rest of the time it searches without success.

```
biggest_found = 80651

n = lambda a,b,c: '9'*a + b + '9'*c

for j in range(1000):
   for digit in '124578':
      for i in range(2000):
         number = int(n(i,digit,j))
         if is_prime(number):
            if (number > biggest_found):
               if all(not is_prime(int(n(i,digit,k))) for k in range(j)):
                  biggest_found = number
                  print(i+j+1, biggest_found)
            break

```

### edit:

Just saw, that you removed the time limit. I will run the program over night, maybe some really big fragile primes appear.

### edit 2:

Made my original program faster, so but still no solution with more than 126 digits. So I jumped on the train and searched for x 9s + 1 digit + y 9s. The advantage is, that you have to check O(n) numbers for primality, if you fixe y. It finds a 1221 rather quickly.

### edit 3:

For the 2268 digit number I use the same program, only divided the work on multiple cores.
> 13 votes

# Answer
## Python 2.7 - 429623069 ~~99993799~~

No optimizations whatsoever, so far. Just using some trivial observations about fragile primes (thanks to Rainbolt in chat):

1. Fragile primes must end in 1 or 9 (Primes are not even, and the final digit must not be prime)
2. Fragile primes ending in 1 must start with 8 or 9 (the first number can't be prime, and 11, 41 and 61 and are all primes)
3. Fragile primes ending in 9 must start with 4,6 or 9 (see reasoning for 1, but only 89 is prime)

Just trying to get the ball rolling :)

This technically runs slightly over 15 minutes, but it only checks a single number in the extra time.

`is_prime` is taken from here (isaacg used it here) and is probabilistic.

```
def substrings(a):
    l=len(a)
    out=set()
    for i in range(l):
        for j in range(l-i):
            out.add(a[:i]+a[len(a)-j:])
    return out

import time

n=9
while time.clock()<15*60:
    if is_prime(n):
        if not any(map(lambda n: n!='' and is_prime(int(n)), substrings(`n`))):
            print n
    t=`n`
    if n%10==9 and t[0]=='8':n+=2
    elif n%10==1 and t[0]!='8':n+=8
    elif t[0]=='1' or is_prime(int(t[0])):n+=10**~-len(t)
    else:n+=10

```

Just a note, when I start this with `n=429623069` I get up to `482704669`. The extra digit really seems to kill this strategy...
> 7 votes

# Answer
# Python 2, ~~828 digits~~ 5048 digits

```
[encoded data, 5048 characters]
155*'9'+'7'+4892*'9'

```

As @Jakube pointed out, the first prime I submitted was not actually fragile due to a bug in my code. Fixing the bug was easy but it also made the algorithm significantly slower.

I limited myself to an easily searchable subset of the fragile primes, namely those that only consist of the digit 9 and exactly one digit 7.

```
def fragile_prime_generator(x, b_max):
  bs, cs = set(), set()
  prime = dict()

  def test_prime(b,c):
    if (b,c) not in prime:
      prime[(b,c)] = is_prime(int('9'*b+`x`+'9'*c))
    return prime[(b,c)]

  def test_frag(b,c):
    for b2 in xrange(b):
      if test_prime(b2,c):
        bs.add(b2)
        return False
    for c2 in xrange(c):
      if test_prime(b,c2):
        cs.add(c2)
        return False
    return True

  a = 1
  while len(bs)<b_max:
    for b in xrange(min(a, b_max)):
      c = a-b
      if b not in bs and c not in cs and test_prime(b,c):
        bs.add(b)
        cs.add(c)
        if test_frag(b,c): yield b,c
    a += 1
  print "no more fragile primes of this form"

for b,c in fragile_prime_generator(7, 222):
  print ("%d digit fragile prime found: %d*'9'+'%d'+%d*'9'"
          % (b+c+1, b, x, c))

```

I used the same `is_prime` function (from here) as @FryAmTheEggman.

**Edit:**

I made two changes to make the algorithm faster:

* I try to skip as many primality checks as possible and only go back when a potential fragile prime is found to make sure it's really fragile. There's a small number of duplicate checks, so I crudely memoized the prime checking function.
* For the numbers of the form `b*'9' + '7' + c*'9'` I limited the size of `b`. The lower the limit, the less numbers have to be checked, but chances increase to not find any large fragile prime at all. I kind of arbitrarily chose 222 as the limit.

At a few thousand digits a single prime check already can take my program a few seconds. So, I probably can't do much better with this approach.

Please feel free to check the correctness of my submission. Due to the probabilistic primality check my number could theoretically not be prime, but if it is, it should be fragile. Or I've done something wrong. :-)
> 7 votes

# Answer
## C#, 10039 28164 digits

```
6 0{28157} 169669

```

**Edit:** I've made another program based on Qualtagh's algorithm with some minor modifications:

* I'm searching for the numbers of the form L000...000R, where L is left composite, R is right composite. I allowed the left composite number L to have multiple digits, although this is mostly a stylistic change, and it probably doesn't affect the efficiency of the algorithm.
* I've added multithreading to speed up the search.

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Mpir.NET;

class Program
{
    const int PrimeNotFound = int.MaxValue;

    private static BitArray _primeSieve;
    private static HashSet<Tuple<int, int>> _templatesToSkip = new HashSet<Tuple<int, int>>();

    static void Main(string[] args)
    {
        int bestDigitCount = 0;
        foreach (Tuple<int, int> template in GetTemplates())
        {
            int left = template.Item1;
            int right = template.Item2;
            if (SkipTemplate(left, right))
                continue;

            int zeroCount = GetZeroCountOfPrime(left, right);
            if (zeroCount != PrimeNotFound)
            {
                int digitCount = left.ToString().Length + right.ToString().Length + zeroCount;
                if (digitCount >= bestDigitCount)
                {
                    string primeStr = left + " 0{" + zeroCount + "} " + right;
                    Console.WriteLine("testing " + primeStr);
                    bool isFragile = IsFragile(left, right, zeroCount);
                    Console.WriteLine(primeStr + " is fragile: " + isFragile);

                    if (isFragile)
                        bestDigitCount = digitCount;
                }

                _templatesToSkip.Add(template);
            }
        }
    }

    private static int GetZeroCountOfPrime(int left, int right)
    {
        _zeroCount = 0;

        int threadCount = Environment.ProcessorCount;
        Task<int>[] tasks = new Task<int>[threadCount];
        for (int i = 0; i < threadCount; i++)
            tasks[i] = Task.Run(() => InternalGetZeroCountOfPrime(left, right));
        Task.WaitAll(tasks);

        return tasks.Min(task => task.Result);
    }

    private static int _zeroCount;

    private static int InternalGetZeroCountOfPrime(int left, int right)
    {
        const int maxZeroCount = 40000;
        int zeroCount = Interlocked.Increment(ref _zeroCount);
        while (zeroCount <= maxZeroCount)
        {
            if (zeroCount % 1000 == 0)
                Console.WriteLine("testing " + left + " 0{" + zeroCount + "} " + right);

            if (IsPrime(left, right, zeroCount))
            {
                Interlocked.Add(ref _zeroCount, maxZeroCount);
                return zeroCount;
            }
            else
                zeroCount = Interlocked.Increment(ref _zeroCount);
        }

        return PrimeNotFound;
    }

    private static bool SkipTemplate(int left, int right)
    {
        for (int leftDiv = 1; leftDiv <= left; leftDiv *= 10)
            for (int rightDiv = 1; rightDiv <= right; rightDiv *= 10)
                if (_templatesToSkip.Contains(Tuple.Create(left / leftDiv, right % (rightDiv * 10))))
                    return true;

        return false;
    }

    private static bool IsPrime(int left, int right, int zeroCount)
    {
        return IsPrime(left.ToString() + new string('0', zeroCount) + right.ToString());
    }

    private static bool IsPrime(string left, string right, int zeroCount)
    {
        return IsPrime(left + new string('0', zeroCount) + right);
    }

    private static bool IsPrime(string s)
    {
        using (mpz_t n = new mpz_t(s))
        {
            return n.IsProbablyPrimeRabinMiller(20);
        }
    }

    private static bool IsFragile(int left, int right, int zeroCount)
    {
        string leftStr = left.ToString();
        string rightStr = right.ToString();

        for (int startIndex = 0; startIndex < leftStr.Length - 1; startIndex++)
            for (int count = 1; count < leftStr.Length - startIndex; count++)
                if (IsPrime(leftStr.Remove(startIndex, count), rightStr, zeroCount))
                    return false;

        for (int startIndex = 1; startIndex < rightStr.Length; startIndex++)
            for (int count = 1; count <= rightStr.Length - startIndex; count++)
                if (IsPrime(leftStr, rightStr.Remove(startIndex, count), zeroCount))
                    return false;

        return true;
    }

    private static IEnumerable<Tuple<int, int>> GetTemplates()
    {
        const int maxDigitCount = 8;
        PreparePrimeSieve((int)BigInteger.Pow(10, maxDigitCount));
        for (int digitCount = 2; digitCount <= maxDigitCount; digitCount++)
        {
            for (int leftCount = 1; leftCount < digitCount; leftCount++)
            {
                int rightCount = digitCount - leftCount;
                int maxLeft = (int)BigInteger.Pow(10, leftCount);
                int maxRight = (int)BigInteger.Pow(10, rightCount);

                for (int left = maxLeft / 10; left < maxLeft; left++)
                    for (int right = maxRight / 10; right < maxRight; right++)
                        if (IsValidTemplate(left, right, leftCount, rightCount))
                            yield return Tuple.Create(left, right);
            }

        }
    }

    private static void PreparePrimeSieve(int limit)
    {
        _primeSieve = new BitArray(limit + 1, true);
        _primeSieve[0] = false;
        _primeSieve[1] = false;

        for (int i = 2; i * i <= limit; i++)
            if (_primeSieve[i])
                for (int j = i * i; j <= limit; j += i)
                    _primeSieve[j] = false;
    }

    private static bool IsValidTemplate(int left, int right, int leftCount, int rightCount)
    {
        int rightDigit = right % 10;
        if ((rightDigit != 1) && (rightDigit != 9))
            return false;

        if (left % 10 == 0)
            return false;

        if ((left + right) % 3 == 0)
            return false;

        if (!Coprime(left, right))
            return false;

        int leftDiv = 1;
        for (int i = 0; i <= leftCount; i++)
        {
            int rightDiv = 1;
            for (int j = 0; j <= rightCount; j++)
            {
                int combination = left / leftDiv * rightDiv + right % rightDiv;
                if (_primeSieve[combination])
                    return false;

                rightDiv *= 10;
            }

            leftDiv *= 10;
        }

        return true;
    }

    private static bool Coprime(int a, int b)
    {
        while (b != 0)
        {
            int t = b;
            b = a % b;
            a = t;
        }
        return a == 1;
    }
}

```

### Old answer:

```
8 0{5436} 4 0{4600} 1

```

The are a few notable patterns for fragile primes:

```
600..00X00..009
900..00X00..009
800..00X00..001
999..99X99..999

```

where X can be 1, 2, 4, 5, 7 or 8.

For such numbers we only have to consider (length - 1) possible `Remove` operations. The other `Remove` operations produce either duplicates or obviously composite numbers. I tried to search for all such numbers with up to 800 digits and noticed that 4 patterns come up more frequently than the rest: 8007001, 8004001, 9997999 and 6004009. Since Emil and Jakube are using the 999X999 pattern, I decided to use 8004001 just to add some variety.

I've added the following optimizations to the algorithm:

* I start searching from numbers with 7000 digits and then increment length by 1500 every time a fragile prime is found. If there is no fragile prime with a given length then I increment it by 1. 7000 and 1500 are just arbitrary numbers that seemed appropriate.
* I'm using multithreading to search for the numbers with different length at the same time.
* The result of each prime check is stored in a hash table to prevent duplicate checks.
* I'm using Miller-Rabin implementation from Mpir.NET, which is very fast (MPIR is a fork of GMP).

```
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Mpir.NET;

class Program
{
    const string _template = "8041";

    private static ConcurrentDictionary<Tuple<int, int>, byte> _compositeNumbers = new ConcurrentDictionary<Tuple<int, int>, byte>();
    private static ConcurrentDictionary<int, int> _leftPrimes = new ConcurrentDictionary<int, int>();
    private static ConcurrentDictionary<int, int> _rightPrimes = new ConcurrentDictionary<int, int>();

    static void Main(string[] args)
    {
        int threadCount = Environment.ProcessorCount;
        Task[] tasks = new Task[threadCount];
        for (int i = 0; i < threadCount; i++)
        {
            int index = i;
            tasks[index] = Task.Run(() => SearchFragilePrimes());
        }
        Task.WaitAll(tasks);
    }

    private const int _lengthIncrement = 1500;
    private static int _length = 7000;
    private static object _lengthLock = new object();
    private static object _consoleLock = new object();

    private static void SearchFragilePrimes()
    {
        int length;
        lock (_lengthLock)
        {
            _length++;
            length = _length;
        }

        while (true)
        {
            lock (_consoleLock)
            {
                Console.WriteLine("{0:T}: length = {1}", DateTime.Now, length);
            }

            bool found = false;
            for (int rightCount = 1; rightCount <= length - 2; rightCount++)
            {
                int leftCount = length - rightCount - 1;
                if (IsFragilePrime(leftCount, rightCount))
                {
                    lock (_consoleLock)
                    {
                        Console.WriteLine("{0:T}: {1} {2}{{{3}}} {4} {2}{{{5}}} {6}",
                            DateTime.Now, _template[0], _template[1], leftCount - 1,
                            _template[2], rightCount - 1, _template[3]);
                    }
                    found = true;
                    break;
                }
            }

            lock (_lengthLock)
            {
                if (found && (_length < length + _lengthIncrement / 2))
                    _length += _lengthIncrement;
                else
                    _length++;
                length = _length;
            }
        }
    }

    private static bool IsFragilePrime(int leftCount, int rightCount)
    {
        int count;
        if (_leftPrimes.TryGetValue(leftCount, out count))
            if (count < rightCount)
                return false;

        if (_rightPrimes.TryGetValue(rightCount, out count))
            if (count < leftCount)
                return false;

        if (!IsPrime(leftCount, rightCount))
            return false;

        for (int i = 0; i < leftCount; i++)
            if (IsPrime(i, rightCount))
                return false;

        for (int i = 0; i < rightCount; i++)
            if (IsPrime(leftCount, i))
                return false;

        return true;
    }

    private static bool IsPrime(int leftCount, int rightCount)
    {
        Tuple<int, int> tuple = Tuple.Create(leftCount, rightCount);
        if (_compositeNumbers.ContainsKey(tuple))
            return false;

        using (mpz_t n = new mpz_t(BuildStr(leftCount, rightCount)))
        {
            bool result = n.IsProbablyPrimeRabinMiller(20);

            if (result)
            {
                _leftPrimes.TryAdd(leftCount, rightCount);
                _rightPrimes.TryAdd(rightCount, leftCount);
            }
            else
                _compositeNumbers.TryAdd(tuple, 0);

            return result;
        }
    }

    private static string BuildStr(int leftCount, int rightCount)
    {
        char[] chars = new char[leftCount + rightCount + 1];
        for (int i = 0; i < chars.Length; i++)
            chars[i] = _template[1];
        chars[0] = _template[0];
        chars[leftCount + rightCount] = _template[3];
        chars[leftCount] = _template[2];
        return new string(chars);
    }
}

```
> 4 votes

# Answer
**Haskell - 1220 1277 digits** **fixed for really reals**

```
99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997999999999999999999999999999999999999999999999999999999999999999999999

9{1150} 7 9{69}

```

Better one - 1277 digits

```
9{871} 8 9{405}

```

Haskell code

```
downADigit :: Integer -> [Integer]
downADigit n = f [] 1 where
     f xs a | nma /= n = f (((n `div` a10)*a + nma):xs) a10
            | otherwise = xs where
        a10 = a * 10
        nma = n `mod` a

isFragile = all (not . isPrime') . downADigit
findNextPrime :: Integer -> Integer
findNextPrime n | even n = f (n + 1)
                | otherwise = f n where
    f n | isPrime' n  = n
        | otherwise = f (n + 2)

primesFrom n = f (findNextPrime n) where
    f n = n:f (findNextPrime $ n + 1)

primeLimit = 10000

isPrime' n | n < primeLimit = isPrime n
isPrime' n = all (millerRabinPrimality n) [2,3,5,7,11,13,17,19,984,7283,6628,8398,2983,9849,2739]

-- (eq. to) find2km (2^k * n) = (k,n)
find2km :: Integer -> (Integer,Integer)
find2km n = f 0 n
    where
        f k m
            | r == 1 = (k,m)
            | otherwise = f (k+1) q
            where (q,r) = quotRem m 2

-- n is the number to test; a is the (presumably randomly chosen) witness
millerRabinPrimality :: Integer -> Integer -> Bool
millerRabinPrimality n a
    | a <= 1 || a >= n-1 =
        error $ "millerRabinPrimality: a out of range ("
              ++ show a ++ " for "++ show n ++ ")"
    | n < 2 = False
    | even n = False
    | b0 == 1 || b0 == n' = True
    | otherwise = iter (tail b)
    where
        n' = n-1
        (k,m) = find2km n'
        b0 = powMod n a m
        b = take (fromIntegral k) $ iterate (squareMod n) b0
        iter [] = False
        iter (x:xs)
            | x == 1 = False
            | x == n' = True
            | otherwise = iter xs

-- (eq. to) pow' (*) (^2) n k = n^k
pow' :: (Num a, Integral b) => (a->a->a) -> (a->a) -> a -> b -> a
pow' _ _ _ 0 = 1
pow' mul sq x' n' = f x' n' 1
    where
        f x n y
            | n == 1 = x `mul` y
            | r == 0 = f x2 q y
            | otherwise = f x2 q (x `mul` y)
            where
                (q,r) = quotRem n 2
                x2 = sq x

mulMod :: Integral a => a -> a -> a -> a
mulMod a b c = (b * c) `mod` a
squareMod :: Integral a => a -> a -> a
squareMod a b = (b * b) `rem` a

-- (eq. to) powMod m n k = n^k `mod` m
powMod :: Integral a => a -> a -> a -> a
powMod m = pow' (mulMod m) (squareMod m)

-- simple for small primes
primes :: [Integer]
primes = 2:3:primes' where
    1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]
    primes'        = p : filter isPrime candidates
    isPrime n      = all (not . divides n)
                                   $ takeWhile (\p -> p*p <= n) primes'
    divides n p    = n `mod` p == 0
isPrime :: Integer -> Bool
isPrime n | n < 2 = False
          | otherwise = f primes where
            f (p:ps) | p*p <= n = if n `rem` p == 0 then False else f ps
                     | otherwise = True

main = do
    print . head $ filter isFragile (primesFrom $ 10^1000)

```
> 2 votes

---
Tags: code-challenge, primes
---


title: Shortest program to split special array

text:
# Question
Title: Shortest program to split special array
# Background

Imagine, you have a big array `A`, which is mostly zeroes, but contains a short subarray `B` which has only strictly positive entries. For instance:

```
|              A              |
[0   0   0   0   1   2   3   0]
               |     B     |

```

Now say, we split the array `A` into consecutive subarrays of length `d` (with a shorter final array, if the `d` doesn't divide the length of `A`). For `d = 3`:

```
[0   0   0   0   1   2   3   0]
           |           |
[0   0   0] [0   1   2] [3   0]

```

And now sum up each of those arrays:

```
[0 3 3]

```

And discard zero sums:

```
[3 3]

```

# The Challenge

You're to write a function which prints that final array of sums in any convenient array format, given the following 5 parameters (or any subset thereof, if you don't need all of them):

* The small array `B`.
* The size of the small array `B` (`3` in the above example).
* The *size* of the big array `A` (`8` in the above example).
* The index where the small array begins (`4` in the above example).
* The length `d` of the subarrays (`3` in the above example).

# The Rules

* You are not allowed to construct the big array `A` explicitly!
* You are not allowed to construct any of the subarrays of length `d` explicitly!
* That means you have to get the computation directly from the `B` and the other parameters at your disposal!

Fewest characters wins!

# Answer
# CJam, ~~34 32~~ 28 characters

```
{"ɚ광䃻噣攍圍숵셳ﶓ訙➰鑓쥾"2G#b126b:c~}

```

This is a compressed form of the following 31 bytes solution

```
{:D%0a*\+0\{+U):UD={0:U}*}%0-p}

```

~~This can be golfed further.~~

Try it online here

Input is in format of `[small_array] index_where_small_array_begins divisor`

For example:

```
[1 2 3] 5 3{"ɚ광䃻噣攍圍숵셳ﶓ訙➰鑓쥾"2G#b126b:c~}~

```

will give output

```
[1 5]

```

Explanation (outdated):

```
{                                   "Begin of function block";
 :D                                 "Store the divisor in D";
   %                                "Calculate index_where_small_array_begins%divisor";
    0a*                             "Get an array of 0 on length above number";
       \+                           "Prepend it to the small_array";
         _,{            }*          "Run this code block length(small_array) times";
            0\                      "Put 0 before small_array. This 0 marks the"
                                    "current sum of the current mini_array";
              {      }D*            "Run this code block divisor times";
               0+                   "Add 0 at the end of mini array";
                 (                  "Take out the first element from the mini array";
                  @                 "Rotate the stack to get current sum on top";
                   +                "Add the first element to the current sum";
                    \               "Swap to put current mini_array on top of stack";
                          ;]        "Pop the residual array and wrap the sums in an array";
                            0-p     "Remove 0 and print the sum_of_mini_arrays_array";
                               }    "End of function block";

```
> 2 votes

# Answer
# CJam, ~~30~~ 28 characters

```
{"ᘏ阋Յ꺂࠻䚉누୛伪"6e4b127b:c~}

```

(SE may have swallowed some unprintable characters. Please copy the code from this character counter.)

Yay for counting by characters and Unicode packing. The above string is converted to character codes, interpreted as base-216, converted to base-129, and converted back to characters, and evaluated, to give the actual code (measuring 30 bytes):

```
{:M%0a*\+{0\{_0a?(@+\}M*}h;]p}

```

This is a block, the closest thing to a function in CJam. It expects the small array, the offset, and the divisor on the stack. You can use it like

```
[1 2 3]4 3{"    ড숺ꤪ洽ὦ﮻ڤ綃掖迓湯"2G#b129b:c~}~

```

Test it here.

## Explanation

```
:M                           "Store divisor in M.";
  %                          "Take offset modulo divisor to get R.";
   0a                        "Push [0].";
     *                       "Repeat to get R zeros.";
      \+                     "Preprend to small array.";
        {              }h    "Repeat while... leaves condition on the stack.";
         0\                  "Put a 0 underneath the array to initialise sum.";
           {        }M*      "Run the block M times.";
            _0a?             "Replace the list by [0] if it's empty.";
                (            "Split off first element.";
                 @           "Pull up current sum.";
                  +\         "And and pull list back to the top.";
                         ;   "Remove leftover empty list.";
                          ]  "Wrap sums in array.";
                           p "Print string representation to STDOUT.";

```
> 1 votes

# Answer
# Pyth \- 30 ~~32~~

**Edit**: Fixed an error with mini array size 1 or very large offset.

```
D:GHYKm0GFNG~@K%/HYlGN~H1)RfTK

```

Defines a function `:` that takes `small_array`, `index_where_small_array_begins` and `divisor` as arguments. You can call it like:

```
:[1 2 3) 5 3

```

Returns: `[1, 5]`

Try it online

Explanation:

```
D:GHY                            : Define :
     Km0G                        : Make K an array of len(G) zeroes
         FNG             )       : for N in small_array
            ~@K%/HYlGN           : Add N to K[floor_div(H,Y)%len(G)]
                      ~H1        : Increment H
                          RfTK   : Return K without any zeroes

```
> 1 votes

# Answer
# JavaScript (ES6) 58

Function with 3 parameters
\- b is the small array
\- i is the index where the small array begins
\- d is the dimension of the subarrays

(t is used just as a local variable)

```
 F=(b,i,d,t=[])=>b.map((v,p)=>t[p=(p+i%d)/d|0]=v+~~t[p])&&t

```

**Test** In FireFox/FireBug console

```
F([1,2,3],4,3)

```

*Output*

```
[ 3, 3 ]

```
> 0 votes

---
Tags: code-golf, math, array
---


# Question
Title: Looking for shorter alternatives to `range(...)`
The best solution I've found so far for a golf code puzzle I'm working on includes two *rather fat-looking* invocations of `range`. I'm very new at code golf, especially in Python, so I could use a few tips.

The relevant fragment is this

```
[x for x in range(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in range(2,x))]

```

The upper limit of the first `range` is not a sharp one. It should be at least 98690, and *all else being equal* (golf-wise, that is), the smaller the difference between this upper limit and 98690 the better, performance-wise1. I'm using 76 (=117649) because `7**6` is the shortest Python expression I can come up with that fits the bill.

In contrast, the lower limit in the first `range`, as well as both limits in the second one, are firm. IOW, the program (in its current form) will produce incorrect results if those limits are changed.

Is there a way to shorten one or both of the expressions

```
range(n+1,7**6)
range(2,x)

```

?

BTW, in this case, aliasing `range` to, say, `r` gains nothing:

```
r=range;rr
rangerange

```

EDIT: FWIW, the full program is this:

```
p=lambda n:[x for x in range(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in range(2,x))][0]

```

`p(n)` should be the smallest palindromic prime greater than `n`. Also, `p` should not be recursive. Warning: It is already obscenely slow!

---

1Yes, I know: performance is irrelevant in code golf, but that's why I wrote "all else being equal (golf-wise, that is)". For example, my choice of `7**6`, and not the more immediately obvious, but poorer-performing, "golf-equivalent" alternative `9**9`. I like to actually *run* my code golf attempts, which means not letting the performance degrade to the point that it would take years to run the code. If I can help it, of course.

# Answer
## Make it a single loop

As is, you have two loops: one iterating over `x` that might be palindromic primes, another iterating over `i` to check if `x` is prime by trial division. As you noticed, loops is Python take many characters, often to write `range`, but also to write `while _:` or `for x in _`. So, a golfed Python solution should take pains to use as few loops as possible.

feersum's comment "The best-golfed programs often make surprising connections between different part of the programs" is very applicable here. The prime-checking might seem like a separate subroutine for which `all(x%i for i in range(2,x))` is the classic expression. But we'll do it another way.

The idea is to use Wilson's Theorem. For each potential prime `k`, we keep a running product of `(k-1)!`, and check is it's a multiple of `k`. We can keep track of `(k-1)!` while we test potential `k` to be prime palindromes by keeping a running product `P`.

Actually, we'll use the stronger version of Wilson's Theorem that `(k-1)! % k` equals 0 for composite `k` and only for composite numbers, except `k=4` gives `2`, and so `(k-1)!**2 % k` equals `0` exactly for composite numbers. We'll update `P` to equal `k!**2` via the update `P*=k*k`.

(See this answer for this method used to find primes in Python.)

Putting it all together:

```
def p(n):
 k=P=1
 while(`k`!=`k`[::-1])+(k<=n)+(P%k==0):P*=k*k;k+=1
 return k

```

This isn't yet fully golfed -- the condition in particular is written inefficiently. We can compress the condition to check that `k` is a palindrome while at the time enforcing the other conditions via a chained inequality.

```
def p(n):
 k=P=1
 while`k`*(P%k>0>n-k)!=`k`[::-1]:P*=k*k;k+=1
 return k

```
> 7 votes

# Answer
## AFAIK, not really.

Range is commonly used in python golfs because it is the shortest way to generate lists of increasing/decreasing numbers.

That said, it appears to be slightly (7 bytes) shorter to avoid using range and instead call a wrapped while loop:

```
def p(n):
    n+=1
    while`n`*all(n%i for i in range(2,n))!=`n`[::-1]:n+=1
    return n

```

Thanks to @xnor (as always) for improving the while condition's logic :)
> 4 votes

# Answer
When using iterative algorithms such as Newton method or calculating fractals, where you usually need to **perform iterations without actually caring about the index** you can save some characters by iterating over short strings instead.

```
for i in range(4):x=f(x)
for i in'asdf':x=f(x)

```

At seven iterations this breaks even with `range`. For more iterations use backtics and large numbers

```
for i in`9**9**5`:pass

```

This runs 56349 times which should be enough for all practical purposes. Playing around with numbers and operators lets you hardcode a wide range of numbers this way.
> 1 votes

---
Tags: code-golf, tips, python
---


title: Challenge Ulamspiral

text:
# Question
Title: Challenge Ulamspiral
**The challenge**

Get familiar with the Ulam spiral:

The aim is to print the spiral like in the picture above!

**Rules**

Write a function `ulam(n)`

where n is a odd positive integer and describes the size of the grid to print.

All non-primes numbers should be replaced with | horizontal and - vertical as in the picture above following the spiral. (Corner elements belongs to the vertical)

All numbers need to take the same amount of space visually and smaller numbers are right centered vertically:

`1000
 100
 10`

`10` needs two spaces on the left and `100` needs one space left. This property depends on the biggest number you have to calculate.

Example: (n=3)

```
 -  - 3
|     |
7   - 2
|
 -  -

```

The test for primes/sieve you have to write yourself.

Smallest byte code wins.

**Bonus** \- 25 if you can make it more pretty find some symbols so that - and | takes the same space (-25 more if you can find a pretty corner symbol) and the symbol should show the line where the spiral evolves.

# Answer
> 3 votes
## Python 3 - 506 479 bytes

```
q=range
def p(n):
 for d in q(2,n//2+1):
  if n%d==0:return 0
 return 1
w=int(input());m=w**2;z=len(str(m))
def k(n):
 if n==1:return'-'*(z-1)+'>'
 if p(n):return str(n).zfill(z)
 return'.'*z
l=[k(n+1)for n in q(m)];s=[[0for n in q(w)]for n in q(w)];x=y=w//2;t=[n//2for n in q(2,w*w)];c=[[1,0],[0,-1],[-1,0],[0,1]];j=p=0
for r in t:
 d=c[p%4];p+=1;i=0
 while i<r and j<m:
  s[y][x]=l[j]+' ';x+=d[0];y+=d[1];i+=1;j+=1
s=[''.join(l)for l in s]
for l in s:print(l)

```

I am not sure if the byte count is correct.
Also, this can most likely be made shorter (I'm new to Python).

Right now I'm just substituting all non-primes with periods. You can change this to any character.

*Note*: You should only enter odd numbers as input, as otherwise the program breaks.

Furthermore, my function to determine whether a number is prime is the most primitive it can be, for the sake of less characters, so it is not efficient. Though it ran just fine on my computer with input values less than 100 in just under a second.

*Note*: Input values above 25 or 30 won't display correctly unless you have a ridiculously wide screen.

---
Tags: code-golf
---


title: Sum of strings without converting

text:
# Question
Title: Sum of strings without converting
You have to take 2 string inputs and output the sum of these two strings **without** converting them to int or using any numeric data type.

ex.

```
string one = "123";
string two = "456";
string sum = "579";

```

Assume the strings won't be larger than 10 digits.

This is code golf and shortest answer in characters wins. An edit to the answer in C# will make me smile :).

Edit: Converting to int can be defined as anything of this nature

`Int.TryParse`, `(int)`, `Convert.ToInt` etc

# Answer
# 80836 Assembly (~~57~~ 53 bytes)

```
53 55 89 E5 8B 4D 0C 8B 55 10 B0 0A 30 DB 88 CF 00 C1 00 C2 49 4A 8A 01 8A 22 00 E0 00 D8 2C 30 30 DB 3C 39 7E 04 B3 01 2C 0A 88 01 88 22 38 CF 75 E2 5D 5B C3

```

This adds, digit by digit, right to left, without converting ascii digits `'0'-'9'` to the integers `0-9`, and carrying over as needed. The bytecode is the code for a function, which may be called in C (see below).

The above bytecode was written by hand, from the following assembly (NASM-style, commented):

```
; save ebx, ebp
push ebx        ; 53
push ebp        ; 55
; copy esp
mov ebp, esp    ; 8B EC
; load arguments
mov ecx, [ebp+0x0C] ; 8B 4D 0C
mov edx, [ebp+0x10] ; 8B 55 10
; initialize stuff
mov al, 10      ; B0 0A
xor bl, bl      ; 30 DB
mov bh, cl      ; 88 CF
; send edx, ecx to end of string
add cl, al     ; 00 C1
add dl, al     ; 00 C2

; decrement everything
dec ecx         ; 49
dec edx         ; 4A

; get rightmost unprocessed digit of each number
mov al, [ecx]   ; 8A 01
mov ah, [edx]   ; 8A 22

; add two ascii digits
add al, ah      ; 00 E0
; add carry if needed
add al, bl      ; 00 D8
; subtract 0x30 ('0') to get the resulting ascii digit
sub al, 0x30    ; 2C 30

; set bl to 0
xor bl, bl      ; 30 DB

; if greater than '9': must carry over to next place
cmp al, 0x39    ; 3C 39
jle $+6         ; 7E 04
; set bl to 1 if carrying over
mov bl, 1       ; B3 01
; subtract 10 from ascii digit if carrying over
sub al, 0x0A    ; 2C 0A

mov [ecx], al   ; 88 01
mov [edx], ah   ; 88 22

; check if loop has ended
cmp bh, cl      ; 38 CF
jne $-28        ; 75 E2

; restore ebx, ebp
pop ebp         ; 5D
pop ebx         ; 5B
; return
ret             ; C3

```

To try this in C (gcc, linux, intel processor):

```
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>

int main(){
    // bytecode from earlier
    char code[] = {
        0x53, 0x55, 0x8B, 0xEC, 0x8B, 0x4D, 0x0C, 0x8B,
        0x55, 0x10, 0x31, 0xC0, 0xB0, 0x09, 0x30, 0xDB,
        0x01, 0xC1, 0x01, 0xC2, 0x40, 0x50, 0x8A, 0x01,
        0x8A, 0x22, 0x00, 0xE0, 0x00, 0xD8, 0x2C, 0x30,
        0x30, 0xDB, 0x3C, 0x39, 0x7E, 0x04, 0xB3, 0x01,
        0x2C, 0x0A, 0x88, 0x01, 0x88, 0x22, 0x58, 0x48,
        0x49, 0x4A, 0x85, 0xC0, 0x75, 0xDF, 0x5D, 0x5B,
        0xC3,
    };
    // allocate executable memory to a function pointer called 'add'
    void __attribute__( (__cdecl__) ) (*add)(char*,char*) = mmap(0,sizeof code,PROT_WRITE|PROT_EXEC,MAP_ANON|MAP_PRIVATE,-1,0);
    memcpy(add, code, sizeof code);

    // test inputs
    char number1[] = "0878295272", number2[] = "8184206821";

    puts(number1);
    puts(number2);

    // call the bytecode as a c function
    add(number1, number2);

    // output is in the first argument
    puts(number1);

    // release allocated memory
    munmap(add, sizeof code);

    return 0;
}

```
> 15 votes

# Answer
# Ruby, 109 71

Cheesy. If you can't bring Mohammad to the mountain....

```
j=$*
r=n=d=0
(d+=x=j.count{|v|n.to_s==v}
r+=x*n
n+=1)until d>1
p r.to_s

```

Algorithm:

1. Compare an int's string representation to input 1 and input 2.
2. Add that int to the result per match.
3. Increment and repeat until you've done it twice.
4. Vomit on yourself

**Changelog**

71 shorter as an array.

85 removed method declaration and consolidate calls to `n.to_s`

92 applied some tips

101 save a char

102 use x for incrementing

109 initial commit
> 14 votes

# Answer
# sed, 359 bytes (without the fancy formatting)

I'm still not sure if this is a dup of Add without addition (or any of the 4 basic arithmetic operators). In the meantime, let me cross post my answer for that question. It's not going to win any golfing, but its a start, and I think easily meets the spec:

```
                       s/([^ ]+) ([^ ]+)/\1:0::\2:/
                       :d /^([^:]+):\1::([^:]+):/tx
                       s/(:[^:]*)9([_:])/\1_\2/g;td
s/(:[^:]*)8(_*:)/\19\2/g;s/(:[^:]*)7(_*:)/\18\2/g;s/(:[^:]*)6(_*:)/\17\2/g
s/(:[^:]*)5(_*:)/\16\2/g;s/(:[^:]*)4(_*:)/\15\2/g;s/(:[^:]*)3(_*:)/\14\2/g
s/(:[^:]*)2(_*:)/\13\2/g;s/(:[^:]*)1(_*:)/\12\2/g;s/(:[^:]*)0(_*:)/\11\2/g
                       s/:(_+:)/:1\1/g; y/_/0/; # #
                       bd;  :x  s/.*::([^:]+):/\1/;
                       # # # # # # #  # # # # # # #

```

Input is taken from STDIN in the form "x y". That is first transformed to "x:0::y:". Then we increment all numbers that come after ":" characters, until we get "x:x::(x+y):". Then we finally return (x+y).

# Output

```
$ printf "%s\n" "0 0" "0 1" "1 0" "9 999" "999 9" "12345 67890" "123 1000000000000000000000"  | sed -rf add.sed
0
1
1
1008
1008
80235
1000000000000000000123
$

```

Note that this only works for the natural numbers. However (in theory at least) it works for arbitrarily large integers. Because we are doing x increment operations on y, ordering can make a big difference to speed: x \< y will be faster than x \> y.
> 9 votes

# Answer
# Ruby - ~~485~~ ~~432~~ 265

This seems more in the spirit of what you were looking for in the question.

It basically solves the problem how a human would on paper -- by "memorizing" all single digit addition results, adding each column, and understanding how to "carry the one" when necessary.

This is also using one "numeric data type" (variable i), which is prohibited by the question, but its only for string indexing. I'll try removing this and edit my answer.

```
def s p
(y=(?0..?9).to_a).product(y).map{|x|/#{x.join}/}.zip((?0..'18').to_a.each_cons(10).to_a.flatten).each{|k,v|return v if k=~p.sort.join}
end
a,b=$*.map{|n|n.rjust(10,?0).reverse}
r=?0
c=''
(0..9).each{|i|d=s [a[i],b[i]]
c=s([d[-1],r])+c
r=d[-2]||?0}
puts r+c

```

Somewhat ungolfed:

```
def s p
  y = (?0..?9).to_a
  y.product(y).map{ |x|
    /#{x.join}/
  }.zip(
    (?0..'18').to_a.each_cons(10).to_a.flatten
  ).each{ |k,v|
    return v if k =~ p.sort.join
  }
end

a,b=$*.map{ |n| n.rjust(10,?0).reverse }

r = ?0
c = ''

(0..9).each { |i|
  d = s [ a[i], b[i] ]
  c = s([ d[-1], r ]) + c
  r = d[-2] || '0'
}

puts r+c

```

EDIT: Used some ideas from the comments to generate the "memorized" mapping table instead of just hardcoding it.
> 9 votes

# Answer
# CJam, ~~95 92 80 72 70~~ 44 characters

```
"Ǻᨌ⹝瀶噄頼୅籌◳ॶ騥箄덮庸匕帯標ឭ⹞➻䗧㩱砡࣍㤬醻孹꽬"2G#b127b:c~

```

which translates to

```
lW%'0A*+S/zW%{{A,__m*{_1b\saa*~}%\{_saa*~}%+\aa/,(s_,({(@+\}*}%_Wf<s}g

```

This can definitely be golfed a lot. I really don't know if my approach is optimal or not yet.

*UPDATE* \- Inline the sum matrix creation to save bytes. Due to this, the program now runs 10 times slower, but still a constant time for any kind of input.

Try it online here

Reads the line containing two numbers from STDIN as string and outputs as a array of characters which is a string itself.

For example:

```
123 4567

```

The output contains preceding `0`. Let me know if that is an issue.
> 4 votes

# Answer
## C# - ~~128~~ ~~108~~ 104

Thanks to Compass, BMac and Shawn for suggesting improvements.

First try at Code Golf, and using C# seems to be a handicap here...

By using `.Compute()` you can use the string values and sum them directly. As a bonus this works for other operators aside from just "+".

Golfed:

```
static void t(string a,string b){System.Console.Write(new System.Data.DataTable().Compute(a+"+"+b,""));}

```

Ungolfed:

```
static void t(string a, string b)
{
    System.Console.Write(new System.Data.DataTable().Compute(a+"+"+b,""));
}

```

Calling `t("123","456");` gets you 579.
> 4 votes

# Answer
# GNU sed, 266 bytes

Uses a different approach than DigitalTrauma's solution. As an effect, this one performs even poorer, using *O(m+n)*. Convert both operands to unary, concatenate, convert back to decimal (all using regex of course—sed doesn't have the *concept* of an integer).

As a bonus, this program sums up *all* the natural integers given on stdin (in the first line), meaning you can feed it nothing, one number or ten numbers and it'll do the right thing regardless.

The idea behind this code is vaguely inspired by an old PPCG sed submission of mine, though I don't remember for what question it is an answer.

Here it is, "pretty"-printed for your "convenience", to borrow another idea from DigitalTrauma. :D

```
                s/9/x8/g;
                s/8/x7/g;
                s/7/x6/g;
                s/6/x5/g;
                s/5/x4/g;
                s/4/x3/g;
  s/3/x2/g;s/2/x1/g;s/1/x0/g;s/0\b//g;;
  :l;s/x0/0xxxxxxxxxx/;/x0/bl;s/[^x]//g
  s/^$/0/;:m;s/x{10}/!/g;s/!\b/&0/;;;;;
  s/0x/1/;s/1x/2/;s/2x/3/;s/3x/4/;;;;;;
  s/4x/5/;s/5x/6/;s/6x/7/;s/7x/8/;;;;;;
                s/8x/9/;;
                s/!/x/g;;
                /x{10}/bm
                /x/!q;;;;
                s/^/0/;bm
                #sum.sed#

```

(To obtain the 266-byte version, remove trailing semicolons, leading whitespace and the final comment, preferably using sed.)

Borrowing some tests from DigitalTrauma:

```
% printf "%s\n" "0 0" "0 1" "1 0" "9 999" "999 9" "12345 6789" "123 100" | while read l; do sed -rf /tmp/sum.sed <<<"$l"; done
0
1
1
1008
1008
19134
223

```

I tweaked the really large tests a bit because of the terrible space (in)efficiency. Due to the use of `q` only the first line is processed, hence the `while` loop in the test.
> 3 votes

# Answer
# Java 6 (181 characters)

Not to be outdone by the handicap known as C#, Java in all its glory. So much boilerplate! Usage is providing the arguments separated by a space, i.e. `123 456`

```
import javax.script.*;class T {public static void main(String[] a) throws Exception {System.out.print(new ScriptEngineManager().getEngineByName("JavaScript").eval(a[0]+"+"+a[1]));}}

```

Ungolfed:

```
import javax.script.*;

class T {
    public static void main(String[] a) throws Exception {
        System.out.print(new ScriptEngineManager()
                .getEngineByName("JavaScript").eval(a[0] + "+" + a[1]));
    }
}

```

By using the JavaScript engine available in `javax`, we can make another language do the work for us, and technically follow the rules of not using any numeric types in the native language, or converting.

### Justification for using `eval`

We have not converted the values to int for JavaScript to eval. We've created a String that is `"123+456"` which is not a number. JS Engine digests the formula and evaluates the String as number literals, which are not numeric data types. Java cheesy logic! As an aside, this also works for `double` math.
> 2 votes

# Answer
# Perl - ~~136~~ ~~119~~ 115 bytes

I'm learning Perl, this seemed like good practice. Tips are appreciated!

Cheesy answer, to get that out of the way:

```
print$ARGV[0]+$ARGV[1]; #Adding strings

```

Actual answer:

```
($x,$y)=@ARGV;while($x.$y.$s){$s-=48-ord$&if$x=~s/.$//;$s-=48-ord$&if$y=~s/.$//;$r=chr($s%10+48).$r;$s=$s>9;}print$r;

```

Uncompressed:

```
($x,$y)=@ARGV;
while($x.$y.$s){
$s-=48-ord$&if$x=~s/.$//;
$s-=48-ord$&if$y=~s/.$//;
$r=chr($s%10+48).$r;
$s=$s>9;
}
print$r;

```
> 2 votes

# Answer
## APL (61)

I *think* this falls within the rules.

```
{⎕D[1+{∨/T←9<Z←0,⍵:∇T↓⍨~×⊃T←(1⌽T)+Z-10×T⋄⍵}+⌿⌽↑⌽¨¯1+⎕D∘⍳¨⍺⍵]}

```

This is a function that takes two string arguments, and returns a string:

```
      '123'{⎕D[1+{∨/T←9<Z←0,⍵:∇T↓⍨~×⊃T←(1⌽T)+Z-10×T⋄⍵}+⌿⌽↑⌽¨¯1+⎕D∘⍳¨⍺⍵]}'456'
579
      ⍝ show dimensions (if it was a number, this would give the empty list)
      ⍴'123'{⎕D[1+{∨/T←9<Z←0,⍵:∇T↓⍨~×⊃T←(1⌽T)+Z-10×T⋄⍵}+⌿⌽↑⌽¨¯1+⎕D∘⍳¨⍺⍵]}'456'
3

```

It's reasonably fast too, it adds the number formed by 999999 `9`s to itself in an instant.

It finds the index of each character in `⎕D` (which is the string '0123456789'), then does grade school addition on each index separately, carrying as needed, then looks up the resulting digits in `⎕D`. (I think the `⎕D` lookup falls within the rules, it's basically just doing `'x'-48`).

Explanation:

* `⎕D∘⍳¨⍺⍵`: look up the indices in `⎕D` for each character in both strings.
* `¯1+`: subtract `1` from each, because the arrays are 1-based by default.
* `⌽↑⌽¨`: reverse both, turn into a matrix (filling empty squares with zeroes), then reverse the matrix.
* `+⌿`: sum the columns of the matrix
* `{`...`}`: carry over:
    + `∨/T←9<Z←0,⍵`: add an extra `0` in front of the list. Find out which 'digits' are higher than 9, and store this in `T`. If any digits were higher than 10:
        - `Z-10×T`: subtract `10` from each position that is higher than 10,
        - `T←(1⌽T)+`: add `1` to each position next to each position that was higher than 10, and store in `T`.
        - `T↓⍨~×⊃T`: if `T` starts with a zero, remove it,
        - : apply the carry function to the result.
    + `⋄⍵`: otherwise, return the value unchanged
* `1+`: add one to each position (because the array is 1-indexed)
* `⎕D[`...`]`: use the result as indices into `⎕D`.
> 2 votes

# Answer
# Java - 257 Characters

as everyone knows java there is no better language for golfing than java

```
    class A{public static void main(String[]s){char[]a=s[0].toCharArray();char[]b=s[1].toCharArray();int c=a.length;int d=b.length;int e=0;String f="";for(int i=0;i<Math.max(c,d);i++){f=f+(((i<c?a[i]-48:0)+(i<d?b[i]-48:0)+e)%10);e/=10;}System.out.println(f);}}

```

this is ungolfed solution

```
public static void main(String[] args) {
        char[] aa = args[0].toCharArray();
        char[] bb = args[1].toCharArray();
        int aal = aa.length;
        int bbl = bb.length;

        int reminder = 0;
        String result ="";
        for(int i=0;i<Math.max(aal,bbl);i++){
            result=result+(((i<aal?aa[i]-48:0)+(i<bbl?bb[i]-48:0)+reminder)%10);
            reminder/=10;
        }
        System.out.println(result);
    }

```
> 0 votes

# Answer
# Java 7, Score = 252

Uses no integers, longs, bytes, shorts, doubles, floats, or any built in library functions for adding. Wrap in a class body and call with `t(String1,String2)`. Please pad strings with 0's so that they have equal length.

`t("123","234")` returns `"0357"`.

Golfed:

```
char c,d,e,f,g,k;String t(String a,String b){g++;char[]h=a.toCharArray(),i=b.toCharArray(),j=new char[h.length + 1];for(d=(char)h.length;d>f;)j[--d+1]=(c=(e=(char)(h[d]+i[d]-'0'+c))>'9'?g:f)==g?(char)(e-'\n'):e;j[0]=(char)('0'+c);return new String(j);}

```

Golfed Expanded with class:

```
public class T{

    public static void main(String[] args){
        System.out.println(new T().t(args[0],args[1]));
    }

    char c,d,e,f,g,k;
    String t(String a,String b){
        g++;
        char[]h=a.toCharArray(),i=b.toCharArray(),j=new char[h.length + 1];
        for(d=(char)h.length;d>f;)
            j[--d+1]=(c=(e=(char)(h[d]+i[d]-'0'+c))>'9'?g:f)==g?(char)(e-'\n'):e;
        j[0]=(char)('0'+c);
        return new String(j);
    }
}

```

Partially golfed expanded:

```
public class TrickSum{

    public static void main(String[] args){
        System.out.println(new TrickSum().trickSum(args[0], args[1]));
    }

    char carry, i, aSum,nullChar,oneChar;
    public String trickSum(String a, String b){
        oneChar++;
        char[] number1 = toCharArray(a), number2 = toCharArray(b), sum = new char[number1.length + 1];
        for (i = (char) number1.length; i > nullChar;)
            sum[--i + 1] = (carry = (aSum = (char) (number1[i] + number2[i] - '0' + carry)) > '9' ? oneChar : nullChar) == oneChar ? (char) (aSum - '\n') : aSum;
        sum[0] = (char)('0' + carry);
        return new String(sum);
    }

    char[] toCharArray(String string){
        return string.toCharArray();
    }
}

```

100% Expanded:

```
public class TrickSum{

    public static void main(String[] args){
        System.out.println(trickSum(args[0], args[1]));
    }

    public static String trickSum(String a, String b){
        char[] number1 = a.toCharArray();
        char[] number2 = b.toCharArray();
        char[] sum = new char[number1.length + 1];
        char carry = '\u0000';
        for (char i = (char)(number1.length - 1); i != '\uFFFF'; i--){
            char aSum = (char) (number1[i] + number2[i] - '0' + carry);
            carry = aSum > '9' ? '\u0001' : '\u0000';
            aSum = (carry == '\u0001') ? (char) (aSum - '\n') : aSum;
            sum[i + 1] = aSum;
        }
        sum[0] = (char)('0' + carry);
        return new String(sum);
    }
}

```
> 0 votes

# Answer
# Haskell - 98 94 bytes

```
main=do
 a<-getLine
 b<-getLine
 let c d=last$takeWhile(\e->d/=(show$e-1))[0..]
 print$c a+c b

```
> 0 votes

# Answer
# JavaScript (ES6), ~~55 66~~ 59\*

```
 f=x=>{for(i=0;i+[]!=x;i++);return i};f((p=prompt)())+f(p())

```

\*This makes a few assumptions:

* We're in an ES6 REPL environment (ex. FireFox 33.1 browser console)
* Performance does not matter (seriously, '9999999999','9999999999' took about 20 minutes to return)
* Converting from Integer to String is allowed
* ~~Input is defined in variables a and b, ex: `var a='123',b=321';`~~ Changed to getting input from prompt (+11).
* Input has no leading zeros.
> 0 votes

# Answer
## Python 2.7, 196 137 chars

version 2 (shorter by initialising the dictionary with code):

```
n={}
for i in range(10):n[`i`]=i*' '
def q(a,b):f=lambda x:''.join([10**p*n[s] for p,s in enumerate(reversed(x))]);return len(f(a)+f(b))

```

Previous version 1 (196 chars):

```
def q(a,b):n,f={0:'','1':' ','2':'  ','3':'   ','4':4*' ','5':5*' ','6':6*' ','7':7*' ','8':8*' ','9':9*' '}, lambda x:''.join(
    [10**p*n[s] for p,s in enumerate(reversed(x))]);return len(f(a)+f(b))

```

e.g.

```
>>> print q('123','111')
234

```

The dictionary keys are strings, the dictionary values only include number constants to shorten the code, and the calculation is done by concatenating two strings and getting the resulting length, so I hope it counts as "not converting them to ints".

## Python small-print rule-cheat version

```
class z(int):0
def s(a,b): return z(a)+z(b)

```

Note:

```
>>> type(z('4'))
<class '__main__.z'>

```

Type *z* is a custom type I define as: *definitely not a numeric type by whatever definition the questioner uses, but behaves close enough to a numeric type to be useful in limited circumstances*. Type *z* behaviours are only partially implemented in this code sample, and if the CPython interpreter uses 'int' to implement *z*, that's an merely an implementation detail and not related to the problem at hand.
> 0 votes

---
Tags: code-golf, string, arithmetic
---


# Question
Title: Say Hello to the Pioneers of Computer Science
Choose your favorite famous computer scientist or computer science pioneer who was **born in 1942 or earlier** (as 1943 marks the start of the creation of the 'first' computer). They should have a Wikipedia page or other site that lists their birth year and tells how their accomplishments relate to computer science. You may choose the same as someone else but choosing someone new is encouraged.

Take a name they are commonly known by. This will most likely be their first and last name but it might include abbreviations or middle names if that is more common. For example, for Tony Hoare both `Tony Hoare` and `C. A. R. Hoare` would be acceptable.

**All the characters in the name must be printable ASCII.** If the name contains characters that aren't printable ASCII it's fine if you choose something approximate. e.g. `Kurt Godel` instead of `Kurt Gödel`.

Take the set of unique characters in the name (e.g. `C. ARHoare`) and shift them up the printable ASCII scale by the birth year of your scientist, looping around from `~` to space. (Basically add the birth year modulo 95.) This will give you a (most likely) new set of printable ASCII characters.

For example, C. A. R. Hoare was born in 1934, so shifting every character in `C. ARHoare` by 1934 (34 mod 95) characters gives `ePBctj2$5(`.

This Stack Snippet will do all the shifting for you:

```
function go() {var name = document.getElementById("name").value;var year = parseInt(document.getElementById("year").value);var unique = {};for (var i = 0; i < name.length; i++) { unique[name.charAt(i)] = true; } var result = ''; for (var char in unique) { result += String.fromCharCode((char.charCodeAt(0) - 32 + year) % 95 + 32); } document.getElementById("result").value = result; }
```

```
Name: <input type="text" id="name" value="C. A. R. Hoare"><br>
Birth Year: <input type="text" id="year" value="1934"><br>
<button type="button" onclick="go()">Ok</button><br>
Result: <input type="text" id="result" readonly>
```

# Challenge

Using this set **and only this set** (no tabs, no newlines) of shifted printable ASCII characters, write a program that prints `Hello, [name]!` to stdout or closest alternative, where `[name]` is the same exact name you chose above and shifted to get your program characters. You may use multiple characters from the set or not use some at all. For example, the theoretical program `PetBee($25` prints `Hello, C. A. R. Hoare!`.

# Scoring

Your score is your code size in bytes times the number of unique characters in the name you choose. The lowest sore wins.

# Answer
# Insomnia, ~~103~~ ~~99~~ 98 * 8 = 784

George Boole, 1815

All 5 programs below have the same length (98) and same output.

```
oyoooyLyyyyoyLqoyyoyoLL*yyoLqy|oLq*yLyoyyoLqoq*yLyyLoyooLyyy*qL|yqoLq**LoooyoLqy|qLLo*qyLq*oq|L|oL
oyoooyLyyyyoyLqoyyoyoLLy*yyoLq*oqL*LqyyyoyLyooyyoLyyLoyooLyyyL*q|qoL|q*LoooyoLqyq*LLo*qyLq*o|qL|oL
oyoooyLyyyyoyLqoyyoyoLL*yyoLqy|oLq*yLyoyyoLqoq*yLyyLoyooLyyyL*qq|oL|yq*LoooyoLqyq*LLo*qyLq*o|qL|oL
oyoooyLyyyyoyLqoyyoyoLLy*yyoLq*oqL*LqyyyoyLyooyyoLyyLoyooLyyyL*q|qoL|q*LoooyoLqyq*LL|qyyLy*qq*L|oL
oyoooyLyyyyoyLqoyyoyoLL*yyoLq|oLq*yLyoyyoLyq|oLq|yq*LqooLoyyoyLyLoyyoyLoooyoLo|q|LLq|yyLooooyoLqyL

```

Prints `Hello, George Boole!`

**Insomnia, 103 * 6 = 618** (probably optimal and unique)

If `G Boole` (George Boole, 1815) is acceptable...

```
ooyoyoLoyyoyoyyLyoyoooLLoyooyyLoyyyoLooyoyoooooLyoyyoLoyoyyyoLooyyyooLoyoyooooLLyyooyoyoLyoyoooLoyooooL

```

Prints `Hello, G Boole!`

---

# Insomnia, ~~94~~ ~~92~~ ~~89~~ ~~85~~ 83 * 10 = 830

Kurt Godel, 1906.

```
kukuzkzjzkuxkujx{rxjkjxzjukukzj{ukukzjkrxujzujk{rxujjku{jxuukujrxzjuxjk{urxjxukzj{j

```

Prints `Hello, Kurt Godel!`

I wrote a program to search for the solution. My second version of the program should be closer to optimal than my first version.

As per @Martin Büttner's nitpick (~~100~~ ~~92~~ ~~88~~ 85 characters, same set of characters):

```
kukuzkzjzkuxkujx{rxjkjxzjukukzj{ukukzjkrxujzujk{rxujju{jxuukujrxuxjzxjk{urxjxjxukzj{j

```

Prints `Hello, Kurt Goedel!`

**Interpreter**
> 8 votes

# Answer
# CJam, ~~230~~ ~~117~~ ~~115~~ ~~114~~ ~~113~~ ~~110~~ ~~107~~ 106 bytes * 13 = 1378

```
23)3*c11(2#)c111(((c3*))))22 2*c32c23 3*c3))$(113))c1$)))2$)2$(32c3)))$(3)$))1($)1($)3))$)1($)1$(12$(((33c

```

Test it here.

I chose `Edsger Dijkstra`, born 1930, which gives me `c#2&$1>b()* 3` (whom I really just chose because he was the first one I found whose name yielded useful characters for CJam; I've checked a dozen names since and none looked as promising).

The code basically just builds the ASCII codes using `1`, `2`, `3`, `*`, `#` (exponentiation) and `(`, `)` (decrement, increment) and converts them to a character with `c`. To save some characters I can sometimes copy an earlier character with `$` (`0$` copies the top stack element, `1$` copies the second-to-top stack element and so on).

Here is the breakdown of the code into characters (this is also runnable):

```
23)3*c    "(23+1)*3 -> 72 -> H";
11(2#)c   "(11-1)^2+1 -> 101 -> e";
111(((c   "111-3 -> 108 -> l";
3*)       "Turn l into string lll and split off the third l.";
)))       "l+3 -> o";
22 2*c    "22*2 -> 44 -> ,";
32c       "32 -> Space";
23 3*c    "23*3 -> 69 -> E";
3))$(     "e-1 -> d";
113))c    "113+2 -> 115 -> s";
1$)))     "d+3 -> g";
2$)       "d+1 -> e";
2$(       "s+1 -> r";
32c       "32 -> Space";
3)))$(    "E-1 -> D";
3)$))     "g+2 -> i";
1($)      "i+1 -> j";
1($)      "j+1 -> k";
3))$)     "r+1 -> s";
1($)      "s+1 -> t";
1$(       "s-1 -> r";
12$(((    "d-3 -> a";
33c       "33 -> !";

```
> 15 votes

# Answer
# Marbelous, 83 bytes * 10 = 830

I've chosen `R Kowalski, 1941` which allows me to use: `{It9A+6=53`

```
++63
A66333696A5A696A6A69
A5633A..+3+6+3+9++
A56A+I
AA+6
=3
3653666665
+I+I+6+6+A++

```

This one is a bit more complex than the old answer (below) since many marbles go through multiple devices, all in all most marble just have a few things added to them before being printed though. Because I didn't have subtraction or low numerals, the lower ascii codes had to be formed by adding by merging two high value marbles, since this results in addition modulo. (I've used `=3` as a deflector since it pushes every marble not equal to 3 to the right and looks like a cute cat)

**output:**

`Hello, R Kowalski!`

**old answer:**

**Marbelous, 113 * 17 = 1921**

Marbelous does okay here, since ever marble that falls off the board gets printed, because of its 2D nature though, it needs a few numerals + some arithmetic to not let the borad get too huge.

I've chosen `Philip D. Estridge, 1937` who yields `u./26EiSj9:8*-+` as the available character set. The characters actually used are `.+-245689E`

```
22
6865
4965686866282252686968696E2244666E65686422456E6E6E6964
--..+4+4+9+4-2-2....+4..+2-2..+9..-4+4..-2..+5+6+4

```

The board is pretty simple, the first 3 rows are literals, ever group of two is a hexadecimal value, the fourth row are arithmetic operations to form the ascii codes that could not be written explicitly because of the limited character sets.

**output:**

`Hello, Philip Donald Estridge!`

You can try it out here!

I'll now look for a possible better candidate, since it looks like marbelous might actually be competitive here.
> 9 votes

# Answer
# Brainfuck,1846\*12 = 22152

Just to have a language other than CJam. Requires original spec Brainfuck with byte datatype, that overflows at 256.

Only uses 2 characters: `+` to increment the current cell, and `.` to output the current cell.

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++.+++++++++++++++++.++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.

```

**Output**

```
Hello, John McCarthy!

```

Credit goes to Coredump for revealing the following in his answer:

```
 "John McCarthy" 1927
 ("John McCarthy" "e+*;h~^|.0$5" 12)

```
> 7 votes

# Answer
# "Hello, Niklaus Emil Wirth!" (Befunge-98, 222×14=3108)

From Wikipedia:

> **Niklaus Emil Wirth** (15 February 1934 – 1 January 2024) was a Swiss computer scientist. He designed several programming languages, including Pascal, and pioneered several classic topics in software engineering. In 1984, he won the Turing Award, generally recognized as the highest distinction in computer science, “for developing a sequence of innovative computer languages”.

With a shift of 34, `Niklaus Emil Wirth` (18 characters, 14 unique) ends up as `p,./$86Bg0,/By,57+`.

## Code (try it out here):

```
88888888+++++++50p50g8+,50g88885+++++00pg,g7+,g7+,g55++,888866+++++,8888+++,50g68++,g886++5/+,g6+,g7+,50g88755+++++,g88++,g77++,8888+++,50g5+,g8+,g886++5/+,g7+,8888+++,50g887+++,g886++5/+,g85++,g87++,g88+5/+,g5/85++,50g00p

```

## Breakdown:

```
88888888+++++++ # Put eight '8's on the stack and add them together (ASCII 64 = `@`)
50p             # Save this value in row 0, column 5 (where the 6th '8' was)
50g8+,          # Fetch the value we just saved, add 8 and print it (ASCII 72 = `H`)
50g88885+++++   # Fetch it again and add 37 (4×8+5) (ASCII 101 = `e`)
00p             # Save this value in row 0, column 0 (the very first character)
g,              # Fetch & print this value (stack is empty, so coordinates will be zero)
g7+,g7+,        # Fetch it again, add 7 (ASCII 108 = `l`) and print. Repeat.
g55++,          # Print `o`
888866+++++,    # Print `,` (4×8+2×6=44)
8888+++,50g68++,g886++5/+,g6+,g7+,50g88755+++++,g  # Continue in a similar fashion,
88++,g77++,8888+++,50g5+,g8+,g886++5/+,g7+,8888++  # using integer division (`/`) in
+,50g887+++,g886++5/+,g85++,g87++,g88+5/+,g5/85++, # a few places
50g00p          # Fetch the `@` character and put it in cell (0,0)

```

The last line places a HALT character (`@`) at the beginning of the line. When the control wraps around back to this point, the program will stop. This shouldn't actually be necessary, because the `@` character at (5,0) is still there and nothing should be output before it is reached. However, the only online Befunge interpreter that will run this monstrosity won't work properly without it.

It *is* actually possible to make a working solution with just `Niklaus Wirth` (12 unique chars, `p,./$86By,57+`), but the code is much, *much* longer.

(Tagged as Befunge-98 because Befunge-93 is limited to a width of 80 characters.)
> 5 votes

# Answer
# CJam, 323 bytes * 10 = 3230

```
5((e5(((e2(((e2(((e2((e2c525e2e2(e2(((e2(e2((e2(((c525e5(e5(((e2(e2c2(($Be2(e2(((e2(e2e2((e2(e2e2(c2e2e2((e2e2(e2(((e2(e2c2(($((((((((((((B((((($(((((2e2(e2(e2e2((e2(((e2(e2e2((c2$2$((c2$2$525e2(((e2((e2((e2((e2e2(((e2((c2$2$22((((((($22(((((((((($22(((((($((((255((e2((e2(e2((e2(((e2((c22(((($Be2e2(e2(e2((e2(((e2(((e2(((c

```

Output:

```
Hello, C. A. R. Hoare!

```

# CJam, 662 bytes * 10 = 6620 8700

Not to win but just because it looks possible. It used only `2e(c`.

```
2e2e2((e2e2(((e2(((e2(((e2((e2c2e2e2(((e2e2(e2(((e2(e2((e2(((c2e2e2e2((e2((e2e2(((e2(e2c2e2e2e2((e2((e2e2(((e2(e2c2e2(e2(((e2(e2e2((e2(e2e2(c2e2((e2e2((e2e2(e2(((e2(e2c2e2((e2e2((e2(((e2(((e2((e2e2c2e2((e2(((e2e2(((e2((e2(e2(((e2(c2e2(e2(e2e2((e2(((e2(e2e2((c2e2((e2e2((e2(((e2(((e2((e2e2c2e2((e2(((e2e2(((e2((e2(e2(((e2(((c2e2(e2(e2e2((e2(((e2(e2e2((c2e2((e2e2((e2(((e2(((e2((e2e2c2e2(((e2(((e2((e2((e2((e2e2(((e2((c2e2(e2(e2e2((e2(((e2(e2e2((c2e2((e2e2((e2(((e2(((e2((e2e2c2e2e2((e2e2(((e2(((e2(((e2((e2c2e2(e2(((e2(e2e2((e2(e2e2(c2e2(((e2e2(e2(((e2(e2(((e2(((e2(((c2e2e2e2(((e2((e2(e2((e2(((e2((c2e2e2(((e2e2(e2(((e2(e2((e2(((c2e2(e2e2(e2(e2((e2(((e2(((e2(((c

```

Output:

```
Hello, C. A. R. Hoare!

```

### Generator

```
q{i
[7209 3113 41 41 41 9 1 0]
{
1$3^)4%@1$+@*4/\'(*\
}%W2tW%"e2"*
'c}%

```

The trivial answer `222(((((((((((c` (generated by `q{i222_@-'(*'c}%`) has 3420 bytes.
> 4 votes

# Answer
# CJam, 16 * ~~307~~ 288 = ~~4912~~ 4608

```
B(7*2+cB(B(*2(+cB(B*((cB(B*((cBB*7-(((c5 8*5(+c8 2*2*cBB*2/5+cBB*7-cBB*5-cBB*Bm5-(cBB*4-cBB*7-c8 2*2*cB7*(((cBB*7-(((cBB*Bm5-(cBB*B-c8 2*2*c8B*2+8-cBB*7-(((c7 2+B*(cBB*8 2*-cBB*B-c8 2*2*cB(7*2(+cBB*7-(((cBB*7-cB(B(*2(+cB(B*((cB(B*((c8 2*2*cB7*cBB*8 2*-cB(B*((cBB*B-cB(B(*2(+cBB*7-c5(8*1+c

```

Displays:

```
Hello, Arthur John Robin Gorell Milner!

```

This is my first answer using CJam, so surely this can better golfed (any hint is welcome).

---

Here is some utility code I used. Since I computed the character set for some other names, this may be useful for someone who better knows CJam (or maybe for another language).

* Find the character set, along with the number of unique characters

```
(defun character-set (name year)
  (let* ((uniques (remove-duplicates name))
         (size (length uniques))
         (buffer (make-array size
                             :element-type 'character
                             :fill-pointer 0)))
    (loop for c across uniques
          do (vector-push
              (code-char
               (+ #x20 (mod (- (+ (char-code c) year) #x20) 95)))
              buffer)
          finally (return (values buffer size)))))

```
* Define a list of well-known figures

```
(defparameter *masters*
  '("Grace Murray Hopper" 1906
    "Augusta Ada King, Countess of Lovelace" 1815
    "Augusta Ada Byron" 1815
    "Ada Lovelace" 1815
    "John von Neumann" 1903
    "Neumann Janos Lajos" 1903
    "Charles Babbage" 1791
    "John McCarthy" 1927
    "Wilhelm Ackermann" 1896
    "George Boole" 1815
    "Kurt Godel" 1906
    "Andrei Nikolaievitch Kolmogorov" 1903
    "Bertrand Arthur William Russell, 3rd Earl Russell" 1872
    "Arthur John Robin Gorell Milner" 1934))

```
* Compute the allowed printable character sets, sort by size of set

```
(sort (loop for (n y) on *masters* by #'cddr
            collect (cons n (multiple-value-list (character-set n y))))
      #'< :key #'caddr)

=>
(("George Boole" "Q|q*Lyvo" 8)
 ("Ada Lovelace" "Kn*Vy!vkmo" 10)
 ("Kurt Godel" "Q{xz&Mujkr" 10)
 ("John von Neumann" "Mkyr#Qhxpdq" 11)
 ("Charles Babbage" "5Zd^eq4TSYW" 11)
 ("Grace Murray Hopper" "MiS{g &Nuvkx" 12)
 ("Neumann Janos Lajos" "QhxpMq#Odmrv" 12)
 ("John McCarthy" "e+*;h~^|.0$5" 12)
 ("Augusta Ada Byron" "q }~Knk*L$|yx" 13)
 ("Wilhelm Ackermann" "Sedh{=_gani]j" 13)
 ("Arthur John Robin Gorell Milner" "c78l+t%i2Bo,/1(5" 16)
 ("Andrei Nikolaievitch Kolmogorov" "DqgQndhlwfk#Nopjury" 19)
 ("Augusta Ada King, Countess of Lovelace" "KnUsq6M x~}p*Vy!vkmo" 20)
 ("Bertrand Arthur William Russell, 3rd Earl Russell" "&R%XL;MQovH)EVc6YWIP" 20))

```
> 4 votes

# Answer
# Brainf\_ck - 723 * 12 = 8676

I did a crawl from Wikipedia's List of computer scientists and collected the birthyears and longest names of all the people listed there. I wrote a program to run over all these and find any I could possibly do in a common language. Sadly, I was unable to find any names that could support `echo;`, `alert()`, `console.log()` (I can hope), `print`, or `main`.

I mainly wanted to share my raw crawl data in case anyone wanted to similarly search for other languages (note: may be inaccurate and incomplete): **Crawl Data**.

**EDIT**: New crawl paste with about 40 new names from List of computing people and List of pioneers in computer science.

**EDIT**: Manually cleaned up the list.

I did find that Jean David Ichbiah (1940), chief designer of Ada, provides `+-.` (the shortest of three people to do so). I generated this BF code for him.

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------.------------.++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++.----.+++++++++++++.------------------------------------------------------------------------------.++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++++++++++++++++.-------------.-----.--------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++.+++++.------.+++++++.--------.+++++++.-----------------------------------------------------------------------.

```

Alexander Keewatin Dewdney provided the most usable BF characters (`+.<>`), but came in slightly above my answer. No one I found provided `.[]`.
> 4 votes

# Answer
## Ruby 1.8 - 250 × 18 = 4500

```
p''<<24+48<<2+99<<9+99<<9+99<<22+89<<44<<4+28<<24/4+59<<22+88<<2+95<<22+94<<22+89<<9+99<<24/4+99<<24/4+99<<4+28<<24/4+59<<9+99<<2+99<<22+98<<2+99<<2+99<<24+94<<24/4+99<<99<<5+99<<4+28<<84/4+54<<2+95<<22+92<<2+95<<22+94<<84/4+94<<22+95<<98<<2+95<<4+29

```

Characters available:

```
'()+./24589:;<>Efp

```

Output:

```
"Hello, Anatolii Alexeevich Karatsuba!"

```

Anatolii Karatsuba, born 1937, is most well known for his contributions to the field of analytic number theory (a field I personally enjoy), including the Karatsuba Algorithm, a method for fast multiplication of arbitrary precision operands.

This is the first and only name I tried.
> 4 votes

# Answer
## GolfScript (125 * 14 = 1750)

```
9)99.9-&^99)).9^..)))..)~99-&.99&.99)^999)9/.(((-9-..9(/-.((9^99((.9-9-^.).9-^).)).~--999~9/.9^.((.9^99(.(.9.~-^.))..9-^))](-

```

Online demo

Douglas Engelbart (1925 - 2013) is perhaps most famous for the "Mother of All Demos". His name and year of birth give characters `!&(),-./9]^z{~`, of which this solution uses `&()-./9]^~`

The basic structure of the code is `build list of numbers](-` which puts a lot of numbers in an array with the empty string that starts on the stack, then pulls out that string and uses it with the type promotion of `-` to turn the array of numbers into a string.

Since there's no access to elements below the top of the stack I wrote a C# program to find short snippets that take a given integer on the top of the stack and add the next integer required. This created one small problem, when the snippet for `69` (`E`) ended with `-` and the snippet for `110` (`n`) started with `9`: it cost one char to use a longer snippet for `110`.
> 3 votes

# Answer
# CaneCode, ~~458~~ 410 * 16 = ~~7328~~ 6560

```
11111111111111111111111111111111111111111111111111111111111111111111111184111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111118111111188111841111111111111111111111111111111111111111111182222222222228331184222222222222228118111111118483322222841811111111822222828483322284111182222222222222811111111111111822222222222222811111111182222228222222281111111111118418

```

Corresponding BF:

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++..+++.>++++++++++++++++++++++++++++++++++++++++++++.------------.<<++.>--------------.++.++++++++.>.<<-----.>+.++++++++.-----.-.>.<<---.>++++.-------------.++++++++++++++.--------------.+++++++++.------.-------.++++++++++++.>+.

```

Outputs:

```
Hello, Jack Elton Bresenham!

```

CaneCode is just a direct symbol substitution of Brainfuck, where `12348` correspond to `+-><.` respectively. I spent about 2 hours trying to look for a short name which gave `+-.` for normal Brainfuck, with no success.

Jack Elton Bresenham, inventor of Bresenham's line algorithm and born 1937, gives the following characters:

```
o')1Ej2:54g8+9.3

```

Unfortunately, while `5` (`[`) is available, the lack of `6` (`]`) means that the code still had to increment up the 100-ish area (for lowercase chars) the slow way.
> 2 votes

# Answer
# \>\<\> (Fish), 163 * 15 = 2445

```
47*5+:56+7*+:42)+:4+55*66*:++66+6*o:4+::o7+:oo25*+o56+:4*o42*4*o6*7+o:7+7+7+o:o:25*7++o42*:4*o45+*o:45++o:o:6+:5+o6+o:o:25*7++o24*4*o25*7*4+o:o:2+o:27*+o42)+ooooo;

```

Outputs:

```
Hello, Ivar Hjalmar Jacobson!

```

Ivar Hjalmar Jacobson, born 1939, was found thanks to BMac's crawl data. He provides the chars

```
)*+24567:;>Gopq

```

\>\<\>, like Befunge, is a 2D stack-based language. The useful \>\<\> commands are:

* `*+24567` for arithmetic (note that `47` pushes a `4` and a `7` on the stack, not `47`)
* `)` for greater than (useful for getting `1`)
* `:` for duplicating the top of the stack
* `o` for output
* `;` for program termination

`p` is also good for reflection, but I was unable to think of a good use for it. `>` is another \>\<\> command, directing program flow rightwards, but since the program already executes in that direction it was not needed.
> 2 votes

---
Tags: code-challenge, restricted-source, printable-ascii
---


title: 12 Days of Golfmas

text:
# Question
Title: 12 Days of Golfmas
## Challenge

On each of the 12 days of Christmas, output the appropriate verse of "12 days of Christmas", according to the date, otherwise output the chorus of "I Wish It Could Be Christmas Everyday".

Leading and/or trailing newlines (`\n`) and trailing spaces are permitted. You may not read from any external sources.

Basically what you have to do is read the system date and output the according verse of the "12 days of Christmas".

## 12 Days of Christmas

The Twelve Days of Christmas is the festive Christian season, beginning on Christmas Day (25 December) and ending on the 5th of January.

## Examples

If the date is the 25th of December (print out the shortest/first verse):

```
On the first day of Christmas
my true love sent to me:
a Partridge in a Pear Tree

```

If the date is the 31st of December (print the seventh verse):

```
On the seventh day of Christmas
my true love sent to me:
7 Swans a Swimming
6 Geese a Laying
5 Golden Rings
4 Calling Birds
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

```

If the date is the 5th of January (print out the longest/last/12th verse):

```
On the twelth day of Christmas
my true love sent to me:
12 Drummers Drumming
11 Pipers Piping
10 Lords a Leaping
9 Ladies Dancing
8 Maids a Milking
7 Swans a Swimming
6 Geese a Laying
5 Golden Rings
4 Calling Birds
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

```

If the date is not within the range of 25th December to 5th January inclusive:

```
Well I wish it could be Christmas every day
When the kids start singing and the band begins to play
Oh I wish it could be Christmas every day
So let the bells ring out for Christmas

```

## Happy Christmas!

# Answer
# CJam, ~~557~~ ~~550~~ ~~530~~ ~~528~~ ~~522~~ 519 bytes

```
et3<(;" Christmas":P;:(31b7+372%_C<{"On the ""first second third"S/"four fif six seven eigh nin ten eleven twelf"S/"th"f++@:X=" day of"P"
my true love sent to me:
""and a Partridge in a Pear Tree."a[D,2>Sm*"Turtle Dove
French Hen
Calling Bird
Golden Ring
Geese a Lay
Swans a Swimm
Maids a Milk
Ladies Danc
Lords a Leap
Pipers Pip
Drummers Drumm"N/'s4*"ing"a7*+]z+X)<W%N*X!{4>}*}{;"Well"" I wish it could be"P" every day
"++_"When the kids start singing and the band begins to play
Oh"\"So let the bells ring out for"P}?

```

Test it here. To try out different dates, replace `et3<(;` with something like `[12 25]`.

There's probably still room for improvement.

```
et                    "Read the current datetime as an array [year month day hour ...].":
  3<                  "Discard hours, minutes etc.";
    (;                "Discard year.";
      " Christmas":P; "Store the string in P and discard.";

:(                    "Decrement month and day.";
  31b                 "Interpret as base-31 digits. So on [12 25] we get 365 (what a coincidence).
                       On [12 31] we get 371. On [1 1] we get 0. On [1 5] we get 4.";
     7+               "Add 7.";
       372%           "Take modulo 372. Now the 12 days result in 0 to 11, others are greater.";
           _C<        "Duplicate and check if it's less than 12.";

{...}{...}?           "Run the first block for the 12 days, the second block otherwise.";

"On the 12 days:";
"On the "             "Push the string.";
"first ... third"S/   "Push first to third. Split by spaces.";
"four ... telf"S/     "Push other ordinal numbers, split by spaces.";
"th"f+                "Add th to each.";
+                     "Append to get first to twelfth.";
@:X                   "Pull day number to the top. Store in X.";
=                     "Select ordinal number.";
" day of"P            "Push ` day of Christmas`.";
"\nmy true...\n"      "Push that string, too".;
"and a Part..."a      "Push day 1 string and wrap in array.";
[                     "Remember beginning of array.";
D,2>                  "Push range [2 3 ... 12].";
Sm*                   "Append a space to each.";
"Turtle..."N/         "Push all the gifts. Split into lines.";
's4*                  "Push `ssss`.";
"ing"a7*              "Push an array with 7 copies of `ing`.";
+                     "Add the two.";
]                     "Close array, containing numbers, gifts and endings.";
z                     "Zip/transpose the array.";
+                     "Add day-1 line.";
X)                    "Push day and decrement.";
<                     "Slice off unwanted days.";
W%                    "Reverse array.";
N*                    "Join lines with line breaks.";
X!                    "Logical not of day, is 1 on day 1 and 0 on all other days.";
{4>}*                 "On day 1, remove first 4 characters (`and `).";

"On all days:";
;                     "Discard day from stack.";
"Well"                "Push the string.";
" I..."P"...day\n"    "Push the rest of the line in 3 strings.";
++_                   "Join those three into one, and duplicate.";
"When...\nOh"         "Push next line and `Oh`.";
\                     "Swap with duplicate line.";
"So ... for"P         "Push final line.";

```
> 7 votes

# Answer
# Python 2, ~~681~~ ~~676~~ ~~673~~ ~~670~~ 667 bytes

```
import time
N=time.localtime();D,M=N.tm_mday,N.tm_mon
Q=((D<6>M<2)*(31+D)+(M>11)*D)-24
print["Well%sWhen the kids start singing and the band begins to play\nOh%sSo let the bells ring out for~"%((" I wish it could be~ every day\n",)*2),"On the %s day of~\nmy true love sent to me:\n"%("twel first second third four fif six seven eigh nin ten eleven".split()[Q%12]+"th"*(Q>3))+"\n".join("%d %s"%(i,"Turtle Doves$French Hens$Calling Birds$Golden Rings$Geese a Lay$Swans a Swimm$Maids a Milk$Ladies Danc$Lords a Leap$Pipers Pip$Drummers Drumm".split("$")[i-2]+"ing"*(i>5))for i in range(Q,1,-1))+"\nand "*(Q>1)+"a Partridge in a Pear Tree"][Q>0].replace("~"," Christmas")

```

I tried competing against CJam... and failed as expected. Maybe if I could figure out how to zlib, but I dunno...

(Thanks to @FryAmTheEggman for suggestions via chat)
> 5 votes

# Answer
It's big! It's mean! It's ugly! It's...

# Java: ~~894 887 883~~ 882 bytes

Golfed:

```
class C{public static void main(String[]a){java.util.Calendar d=java.util.Calendar.getInstance();String p="a Partridge in a Pear Tree\n",t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".replaceAll("Z","I wish it could be X every day"),r="";String[]s=(" day of X\nMy true love gave to me:\nçfirstçsecondçthirdçfourthçfifthçsixthçseventhçeighthçninthçtenthçeleventhçtwelfthç Turtle Doves\nç French Hens\nç Calling Birds\nç Golden Rings\nç Geese a LayY\nç Swans a SwimmY\nç Maids a MilkY\nç Ladies DancY\nç Lords a LeapY\nç Pipers PipY\nç Drummers DrummY\n").replaceAll("Y","ing").split("ç");int n=d.get(d.DAY_OF_YEAR),o=(n>358)?(n-358):(n<6)?(n+7):-1,j;if(o==-1)r=t;else{r+=("On the "+s[o]+s[0]);for(j=o+11;j-->12;r+=(j-11+s[j]));r+=(o!=1)?"and "+p:p;}System.out.print(r.replaceAll("X","Christmas"));}}

```

Ungolfed:

```
class C {

    public static void main(String[] a) {
        java.util.Calendar d = java.util.Calendar.getInstance();
        String p = "a Partridge in a Pear Tree\n", t = "Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".replaceAll("Z", "I wish it could be X every day"), r = "";
        String[] s = (" day of X\nMy true love gave to me:\nçfirstçsecondçthirdçfourthçfifthçsixthçseventhçeighthçninthçtenthçeleventhçtwelfthç Turtle Doves\nç French Hens\nç Calling Birds\nç Golden Rings\nç Geese a LayY\nç Swans a SwimmY\nç Maids a MilkY\nç Ladies DancY\nç Lords a LeapY\nç Pipers PipY\nç Drummers DrummY\n").replaceAll("Y", "ing").split("ç");
        int n = d.get(d.DAY_OF_YEAR), o = (n > 358) ? (n - 358) : (n < 6) ? (n + 7) : -1, j;
        if (o == -1) {
            r = t;
        } else {
            r += ("On the " + s[o] + s[0]);
            for (j = o + 11; j-- > 12; r += (j - 11 + s[j]));
            r += (o != 1) ? "and " + p : p;
        }
        System.out.print(r.replaceAll("X", "Christmas"));
    }
}

```

After messing with it a lot and gaining 14 bytes, I think I'll stop fiddling with it.

And yes, I know that, on leap years, my idea may have a bit of an issue, but... it was my way to cut a few bytes off the code. Oh well.
> 4 votes

# Answer
# Erlang, 748 bytes

A 7-bit clean version without gzip-9 is 748 bytes:

```
f()->[maps:get(C,#{$N=>"ing",$x=>10,$q=>"th",$z=>" Christmas"},C)||C<-s(t(calendar:local_time()))].
t({{_,1,D},_})->D+7;t({{_,12,D},_})->D-24;t(_)->1.
s(X)when X<1;X>12->L=" I wish it could bez every dayx","Well"++L++"When qe kids start sNN and qe band begins to playxOh"++L++"So let qe bells rN out forz";
s(I)->"On qe "++element(I,{"first","second","qird","fourq","fifq","sixq","sevenq","eighq","ninq","tenq","elevenq","twelq"})++" day ofzxmy true love sent to me:x"++r(I).
r(0)->"";r(I)->element(I,{"a Partridge in a Pear Tree","2 Turtle Dovesxand ","3 French Hensx","4 CallN Birdsx","5 Golden RNsx","6 Geese a LayNx","7 Swans a SwimmNx","8 Maids a MilkNx","9 Ladies DancNx","10 Lords a LeapNx","11 Pipers PipNx","12 Drummers DrummNx"})++r(I-1).

```

A gzip-9+base64 solution is 750 bytes long:

```
f()->s(t(calendar:local_time())).
t({{_,1,D},_})->D+8;t({{_,12,D},_})->D-23;t(_)->1.
s(I)->try element(I,binary_to_term(base64:decode("g1AAAAkQeNrdlF9OGzEQxsNrJF44wXeEhtK/jyUqRQoCARLPTnYSW+u1oxlv0jz3BL1C71D1Cj1C79BDtOOQhQqpCKv0D5VW8u5a883vmxnbbte9jxfkPQ6xdGLhEiax9RXGhH3LTlJjBLQgXqEyq/6FpYBkCbWrBJIMJ4gLM31gQrXeGueXMek/QYqYe407tnfNcBbhKV0KKZiAs3ZsE6aRryPq3unxJcnUsaQcijj9QbHfrJC4Jfi4IAiFlGEaetk3OFFsdtWM4AL0kwzjnInqHm1EhSZRXdxU/bnoLs5bTp4w1B3p5xLcloc3eZJ1XJLmMV4zhYnFGwpSmvRdV7GoUbYg6x72jfe5D68UV36N4v1V36ZFEE9wEH2l43eqIHK/TB+6tru3RUxPcUAkpGIjs1KW3wr56Wo2F4pQgvkMZ0ujp9Ho6pomg/5R8s8bcnIzWwT+HEcmXzQGR87XGfNvW/mysRJcWQteKFzlSDA0YZIh/z1rX7s7qXC6Bo8wiry2MiIzz5gPwO23biZ98XEaDHDi5sSSl8z5ICuwtdP1e0m+zP8uhtw2Ta7A+mVdg/+hKN8Bkz8M5Q==")))catch _:_->s(1)end.

```

An UTF-8 encoded Erlang function is 421 characters (935 bytes).

```
f()->s(t(calendar:local_time())).
t({{_,1,D},_})->D+8;t({{_,12,D},_})->D-23;t(_)->1.
s(I)->try element(I,binary_to_term(<<<<(C-$㐀):14>>||C<-"哔㐀㐤䑸檷䵅焸伱㠱怶悑券摝汈佊玏㵊塐專㔒染孡㵯徵峆䫽㳳欄捐拵㟔㸽䒻焄䋓垐啂庐嚯栏奕挮浫柍濦斝憻䮽埅牃栺整䲸䔢仇椕斡㯜愹䙣㔭㘅溄暫玡乘㖐㶵廁㴠撞㰋䃟䨄㻗刚淥朞壽㖊娞泓拙母倅戒奴㸩娠㼷䶰䞦填显彻己㵲克㪐傊䈿䠛㭾悐戉压咀㲅夘䖧彤欸䡛㭭䨳吂焤擎䉲㷪㮛䡈䢙䕝欕䏛宠拎䫓巣㝐凩淄應东歹墝䧉㾘敞䃡䲜䡬㹒媽㧕勆屑憈䊱濚䇷扃滱䕝犍沿䥝犙㤐䟜㔇檗坷庈㬫焰厺憮潴䤱䍱䐉㹆㲎杒妷撯宥帶㧢夈㿤䁧䛨湽㮣庚㶠珥㯋䌛傜圵怓爜䗉姳䐙㯎槆匶煯液恄姅堭刨䬹䢃㓑喒㱿柖慾漻幜㾠丼撊挭圢㳏䎘㟰䋛冸婽灜䖠旃囦攤嵼柤含怭儿䧭㶾朿曨佰橍徰䎦䥶㟿届䇰㩌猌浀㐀㐀㐀">>))catch _:_->s(1)end.

```
> 1 votes

# Answer
# Javascript (665)

```
__=new Date("12/31");M=_.getMonth();D=_.getDate();d=M?(M==11)*(D-24):D+7;if(!d||d>12)s="Well K\nWhen the kids start singing and the bands begin to play\nOh K\nSo let the bells ring out for Christmas".replace(/K/g,"I wish it could be Christmas every day");else{for(s="On the "+"0first0second0third0fourth0fifth0sixth0seventh0eight0ninth0tenth0elevent0twelth".split(0)[d]+" day of Chirstmas\nmy true love sent to me:";--d;)s+="\n"+(d+1)+" "+"0Turtle Doves0French Hens0CallZ Birds0Golden RZs0Geese a LayZ0Swans a SwimmZ0Maids a MilkZ0Ladies DancZ0Lords a LeapZ0Pipers PipZ0Drummers DrummZ".split(0)[d].replace("Z","ing");s+="\n"+(D!=25?"and ":"")+"a Partridge in a Pear Tree"}alert(s)

```

You can test it by adding parentheses to the first `new Date` i.e. change:

```
_=new Date;M=_...

```

to

```
_=new Date("1/5");M=_...

```

Here it is beautified:

```
_ = new Date("12/31");
M = _.getMonth();
D = _.getDate();
d = M ? (M == 11) * (D - 24) : D + 7;
if (!d || d > 12) s = "Well K\nWhen the kids start singing and the bands begin to play\nOh K\nSo let the bells ring out for Christmas".replace(/K/g, "I wish it could be Christmas every day");
else {
    for (s = "On the " + "0first0second0third0fourth0fifth0sixth0seventh0eight0ninth0tenth0elevent0twelth".split(0)[d] + " day of Chirstmas\nmy true love sent to me:"; --d;) s += "\n" + (d + 1) + " " + "0Turtle Doves0French Hens0CallZ Birds0Golden RZs0Geese a LayZ0Swans a SwimmZ0Maids a MilkZ0Ladies DancZ0Lords a LeapZ0Pipers PipZ0Drummers DrummZ".split(0)[d].replace("Z", "ing");
    s += "\n" + (D != 25 ? "and " : "") + "a Partridge in a Pear Tree"
}
alert(s)

```
> 0 votes

# Answer
# C# In Linqpad - 866 bytes

Well, at least it beat Java ;) Leap years are handled inside the code.

**Unformated:**

```
void Main(){var w=DateTime.Now;int y=w.Year%4,d=w.DayOfYear,c=0,p=0;string t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".Replace("Z","I wish it could be X every day").Replace("X","Christmas"),o="On the ",x=" day of Christmas\nmy true love sent to me:\n";string[]z={"first","second","third","forth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelth"},b={"a Partridge in a Pear Tree\n","and ","2 Turtle Doves\n","3 French Hens\n","4 Calling Birds\n","5 Golden Rings\n","6 Geese a Laying\n","7 Swans a Swimming\n","8 Maids a Milking\n","9 Ladies Dancing\n","10 Lords a Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n"};if(y==0){p=1;}if(d>358){c=d-358-p;}else if(d<6){c=d+7;}else{t.Dump();return;}if(c==1){o+=z[0]+x+b[0];}else{o+=z[c-1]+x;for(int i=c;i>=0;i--){o+=b[i];}}o.Dump();}

```

**Formatted:**

```
void Main()
{
var w=DateTime.Now;
int y=w.Year%4,d=w.DayOfYear,c=0,p=0;
string t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".Replace("Z","I wish it could be X every day").Replace("X","Christmas"),
o="On the ",x=" day of Christmas\nmy true love sent to me:\n";

string[]z={"first","second","third","forth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelth"},

b={"a Partridge in a Pear Tree\n","and ","2 Turtle Doves\n","3 French Hens\n","4 Calling Birds\n","5 Golden Rings\n","6 Geese a Laying\n",
"7 Swans a Swimming\n","8 Maids a Milking\n","9 Ladies Dancing\n","10 Lords a Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n"};

if(y==0)
{
    p=1;
}

if(d>358)
{
    c=d-358-p;
}
else if(d<6)
{
    c=d+7;
}
else
{
    t.Dump();
    return;
}

if(c==1)
{
    o+=z[0]+x+b[0];
}
else
{
    o+=z[c-1]+x;
    for(int i=c;i>=0;i--)
    {
        o+=b[i];
    }
}
o.Dump();
}

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity
---