Abelian sandpile model/Identity

Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).

E.g. s1 =

    1 2 0
    2 1 1
    0 1 3

and s2 =

    2 1 3
    1 0 1
    0 1 0

Addition on sandpiles is done by adding numbers in corresponding grid areas,
so for the above:

              1 2 0     2 1 3     3 3 3
    s1 + s2 = 2 1 1  +  1 0 1  =  3 1 2
              0 1 3     0 1 0     0 2 3

If the addition would result in more than 3 "grains of sand" in any area then
those areas cause the whole sandpile to become "unstable" and the sandpile
areas are "toppled" in an "avalanche" until the "stable" result is obtained.

Any unstable area (with a number >= 4), is "toppled" by loosing one grain of
sand to each of its four horizontal or vertical neighbours. Grains are lost
at the edge of the grid, but otherwise increase the number in neighbouring
cells by one, whilst decreasing the count in the toppled cell by four in each
toppling.

A toppling may give an adjacent area more than four grains of sand leading to
a chain of topplings called an "avalanche".
E.g.

    4 3 3     0 4 3     1 0 4     1 1 0     2 1 0
    3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3
    0 2 3     0 2 3     0 2 3     0 2 3     1 2 3

The final result is the stable sandpile on the right.

'''Note:''' The order in which cells are toppled does not affect the final result.

;Task:
* Create a class or datastructure and functions to represent and operate on sandpiles.
* Confirm the result of the avalanche of topplings shown above
* Confirm that s1 + s2 == s2 + s1  # Show the stable results
* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:

    2 1 2
    1 0 1
    2 1 2

* Show that s3 + s3_id == s3
* Show that s3_id + s3_id == s3_id

Show confirming output here, with your examples.

;References:
*    https://www.youtube.com/watch?v=1MtEUErz7Gg
*    https://en.wikipedia.org/wiki/Abelian_sandpile_model

Solution:
'''Abelian Sandpile – Identity'''

from operator import add, eq

# -------------------------- TEST --------------------------
# main :: IO ()
def main():
    '''Tests of cascades and additions'''
    s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]
    s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]
    s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]
    s3 = [[3, 3, 3], [3, 3, 3], [3, 3, 3]]
    s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]

    series = list(cascadeSeries(s0))
    for expr in [
            'Cascade:',
            showSandPiles(
                [(' ', series[0])] + [
                    (':', xs) for xs in series[1:]
                ]
            ),
            '',
            f's1 + s2 == s2 + s1 -> {addSand(s1)(s2) == addSand(s2)(s1)}',
            showSandPiles([
                (' ', s1),
                ('+', s2),
                ('=', addSand(s1)(s2))
            ]),
            '',
            showSandPiles([
                (' ', s2),
                ('+', s1),
                ('=', addSand(s2)(s1))
            ]),
            '',
            f's3 + s3_id == s3 -> {addSand(s3)(s3_id) == s3}',
            showSandPiles([
                (' ', s3),
                ('+', s3_id),
                ('=', addSand(s3)(s3_id))
            ]),
            '',
            f's3_id + s3_id == s3_id -> {addSand(s3_id)(s3_id) == s3_id}',
            showSandPiles([
                (' ', s3_id),
                ('+', s3_id),
                ('=', addSand(s3_id)(s3_id))
            ]),

    ]:
        print(expr)

# ----------------------- SANDPILES ------------------------

# addSand :: [[Int]] -> [[Int]] -> [[Int]]
def addSand(xs):
    '''The stabilised sum of two sandpiles.
    '''
    def go(ys):
        return cascadeSeries(
            chunksOf(len(xs))(
                map(
                    add,
                    concat(xs),
                    concat(ys)
                )
            )
        )[-1]
    return go

# cascadeSeries :: [[Int]] -> [[[Int]]]
def cascadeSeries(rows):
    '''The sequence of states from a given
       sand pile to a stable condition.
    '''
    xs = list(rows)
    w = len(xs)
    return [
        list(chunksOf(w)(x)) for x
        in convergence(eq)(
            iterate(nextState(w))(
                concat(xs)
            )
        )
    ]

# convergence :: (a -> a -> Bool) -> [a] -> [a]
def convergence(p):
    '''All items of xs to the point where the binary
       p returns True over two successive values.
    '''
    def go(xs):
        def conv(prev, ys):
            y = next(ys)
            return [prev] + (
                [] if p(prev, y) else conv(y, ys)
            )
        return conv(next(xs), xs)
    return go

# nextState Int -> Int -> [Int] -> [Int]
def nextState(w):
    '''The next state of a (potentially unstable)
       flattened sand-pile matrix of row length w.
    '''
    def go(xs):
        def tumble(i):
            neighbours = indexNeighbours(w)(i)
            return [
                1 + k if j in neighbours else (
                    k - (1 + w) if j == i else k
                ) for (j, k) in enumerate(xs)
            ]
        return maybe(xs)(tumble)(
            findIndex(lambda x: w < x)(xs)
        )
    return go

# indexNeighbours :: Int -> Int -> [Int]
def indexNeighbours(w):
    '''Indices vertically and horizontally adjoining the
       given index in a flattened matrix of dimension w.
    '''
    def go(i):
        lastCol = w - 1
        iSqr = (w * w)
        col = i % w
        return [
            j for j in [i - w, i + w]
            if -1 < j < iSqr
        ] + ([i - 1] if 0 != col else []) + (
            [1 + i] if lastCol != col else []
        )
    return go

# ------------------------ DISPLAY -------------------------

# showSandPiles :: [(String, [[Int]])] -> String
def showSandPiles(pairs):
    '''Indented multi-line representation
       of a sequence of matrices, delimited
       by preceding operators or indents.
    '''
    return '\n'.join([
        ' '.join([' '.join(map(str, seq)) for seq in tpl])
        for tpl in zip(*[
            zip(
                *[list(str(pfx).center(len(rows)))]
                + list(zip(*rows))
            )
            for (pfx, rows) in pairs
        ])
    ])

# ------------------------ GENERIC -------------------------

# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
    '''A series of lists of length n, subdividing the
       contents of xs. Where the length of xs is not evenly
       divible, the final list will be shorter than n.
    '''
    def go(xs):
        ys = list(xs)
        return (
            ys[i:n + i] for i in range(0, len(ys), n)
        ) if 0 < n else None
    return go

# concat :: [[a]] -> [a]
def concat(xs):
    '''The concatenation of all
       elements in a list.
    '''
    return [x for lst in xs for x in lst]

# findIndex :: (a -> Bool) -> [a] -> Maybe Int
def findIndex(p):
    '''Just the first index at which an
       element in xs matches p,
       or Nothing if no elements match.
    '''
    def go(xs):
        return next(
            (i for (i, x) in enumerate(xs) if p(x)),
            None
        )
    return go

# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
    '''An infinite list of repeated
       applications of f to x.
    '''
    def go(x):
        v = x
        while True:
            yield v
            v = f(v)
    return go

# maybe :: b -> (a -> b) -> Maybe a -> b
def maybe(v):
    '''Either the default value v, if x is None,
       or the application of f to x.
    '''
    def go(f):
        def g(x):
            return v if None is x else f(x)
        return g
    return go

# MAIN ---
if __name__ == '__main__':
    main()


Abundant odd numbers

An Abundant number is a number '''n''' for which the   ''sum of divisors''   '''σ(n) > 2n''',
or,   equivalently,   the   ''sum of proper divisors''   (or aliquot sum)       '''s(n) > n'''.

;E.G.:
'''12'''   is abundant, it has the proper divisors     '''1,2,3,4 & 6'''     which sum to   '''16'''   ( > '''12''' or '''n''');
       or alternately,   has the sigma sum of   '''1,2,3,4,6 & 12'''   which sum to   '''28'''   ( > '''24''' or '''2n''').

Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers.

To make things more interesting, this task is specifically about finding   ''odd abundant numbers''.

;Task
*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.

;References:
:*   OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
:*   American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)

Solution:
#include
#include

// The following function is for odd numbers ONLY
// Please use "for (unsigned i = 2, j; i*i <= n; i ++)" for even and odd numbers
unsigned sum_proper_divisors(const unsigned n) {
  unsigned sum = 1;
  for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
  return sum;
}

int main(int argc, char const *argv[]) {
  unsigned n, c;
  for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);

  for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
  printf("\nThe one thousandth abundant odd number is: %u\n", n);

  for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
  printf("The first abundant odd number above one billion is: %u\n", n);

  return 0;
}


Abundant odd numbers

Solution:
(() => {
    'use strict';
    const main = () => {

        // abundantTuple :: Int -> [(Int, Int)]
        const abundantTuple = n => {
            // Either a list containing the tuple of N
            // and its divisor sum (if n is abundant),
            // or otherwise an empty list.
            const x = divisorSum(n);
            return n < x ? ([
                Tuple(n)(x)
            ]) : [];
        };

        // divisorSum :: Int -> Int
        const divisorSum = n => {
            // Sum of the divisors of n.
            const
                floatRoot = Math.sqrt(n),
                intRoot = Math.floor(floatRoot),
                lows = filter(x => 0 === n % x)(
                    enumFromTo(1)(intRoot)
                );
            return sum(lows.concat(map(quot(n))(
                intRoot === floatRoot ? (
                    lows.slice(1, -1)
                ) : lows.slice(1)
            )));
        };

        // TEST ---------------------------------------
        console.log(
            'First 25 abundant odd numbers, with their divisor sums:'
        )
        console.log(unlines(map(showTuple)(
            take(25)(
                concatMapGen(abundantTuple)(
                    enumFromThen(1)(3)
                )
            )
        )));
        console.log(
            '\n\n1000th abundant odd number, with its divisor sum:'
        )
        console.log(showTuple(
            take(1)(drop(999)(
                concatMapGen(abundantTuple)(
                    enumFromThen(1)(3)
                )
            ))[0]
        ))
        console.log(
            '\n\nFirst abundant odd number above 10^9, with divisor sum:'
        )
        const billion = Math.pow(10, 9);
        console.log(showTuple(
            take(1)(
                concatMapGen(abundantTuple)(
                    enumFromThen(1 + billion)(3 + billion)
                )
            )[0]
        ))
    };

    // GENERAL REUSABLE FUNCTIONS -------------------------

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a => b => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // concatMapGen :: (a -> [b]) -> Gen [a] -> Gen [b]
    const concatMapGen = f =>
        function*(xs) {
            let
                x = xs.next(),
                v = undefined;
            while (!x.done) {
                v = f(x.value);
                if (0 < v.length) {
                    yield v[0];
                }
                x = xs.next();
            }
        };

    // drop :: Int -> [a] -> [a]
    // drop :: Int -> Generator [a] -> Generator [a]
    // drop :: Int -> String -> String
    const drop = n => xs =>
        Infinity > length(xs) ? (
            xs.slice(n)
        ) : (take(n)(xs), xs);

    // dropAround :: (a -> Bool) -> [a] -> [a]
    // dropAround :: (Char -> Bool) -> String -> String
    const dropAround = p => xs => dropWhile(p)(
        dropWhileEnd(p)(xs)
    );

    // dropWhile :: (a -> Bool) -> [a] -> [a]
    // dropWhile :: (Char -> Bool) -> String -> String
    const dropWhile = p => xs => {
        const lng = xs.length;
        return 0 < lng ? xs.slice(
            until(i => i === lng || !p(xs[i]))(
                i => 1 + i
            )(0)
        ) : [];
    };

    // dropWhileEnd :: (a -> Bool) -> [a] -> [a]
    // dropWhileEnd :: (Char -> Bool) -> String -> String
    const dropWhileEnd = p => xs => {
        let i = xs.length;
        while (i-- && p(xs[i])) {}
        return xs.slice(0, i + 1);
    };

    // enumFromThen :: Int -> Int -> Gen [Int]
    const enumFromThen = x =>
        // A non-finite stream of integers,
        // starting with x and y, and continuing
        // with the same interval.
        function*(y) {
            const d = y - x;
            let v = y + d;
            yield x;
            yield y;
            while (true) {
                yield v;
                v = d + v;
            }
        };

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m => n =>
        Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);

    // filter :: (a -> Bool) -> [a] -> [a]
    const filter = f => xs => xs.filter(f);

    // Returns Infinity over objects without finite length.
    // This enables zip and zipWith to choose the shorter
    // argument when one is non-finite, like cycle, repeat etc

    // length :: [a] -> Int
    const length = xs =>
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // map :: (a -> b) -> [a] -> [b]
    const map = f => xs =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // quot :: Int -> Int -> Int
    const quot = n => m => Math.floor(n / m);

    // show :: a -> String
    const show = JSON.stringify;

    // showTuple :: Tuple -> String
    const showTuple = tpl =>
        '(' + enumFromTo(0)(tpl.length - 1)
        .map(x => unQuoted(show(tpl[x])))
        .join(',') + ')';

    // sum :: [Num] -> Num
    const sum = xs => xs.reduce((a, x) => a + x, 0);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n => xs =>
        'GeneratorFunction' !== xs.constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = p => f => x => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

    // unQuoted :: String -> String
    const unQuoted = s =>
        dropAround(x => 34 === x.codePointAt(0))(
            s
        );

    // MAIN ---
    return main();
})();


Abundant odd numbers

Solution:
#!/usr/bin/python
# Abundant odd numbers - Python

oddNumber  = 1
aCount  = 0
dSum  = 0

from math import sqrt

def divisorSum(n):
    sum = 1
    i = int(sqrt(n)+1)

    for d in range (2, i):
        if n % d == 0:
            sum += d
            otherD = n // d
            if otherD != d:
                sum += otherD
    return sum

print ("The first 25 abundant odd numbers:")
while aCount  < 25:
    dSum  = divisorSum(oddNumber )
    if dSum  > oddNumber :
        aCount  += 1
        print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
    oddNumber  += 2

while aCount  < 1000:
    dSum  = divisorSum(oddNumber )
    if dSum  > oddNumber :
        aCount  += 1
    oddNumber  += 2
print ("\n1000th abundant odd number:")
print ("    ",(oddNumber - 2)," proper divisor sum: ",dSum)

oddNumber  = 1000000001
found  = False
while not found :
    dSum  = divisorSum(oddNumber )
    if dSum  > oddNumber :
        found  = True
        print ("\nFirst abundant odd number > 1 000 000 000:")
        print ("    ",oddNumber," proper divisor sum: ",dSum)
    oddNumber  += 2


Accumulator factory

A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).

;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').
:Before you submit an example, make sure the function

:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used
:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''
:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''
:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''
: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':
:: x = foo(1);
x(5);
foo(3);
print x(2.3);
: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''

;Task:
Create a function that implements the described rules.

It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.

Where it is not possible to hold exactly to the constraints above, describe the deviations.

Solution:
#include
//~ Take a number n and return a function that takes a number i
#define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \
    static __typeof__(n) _n=n; LOGIC; }
//~ have it return n incremented by the accumulation of i
#define LOGIC return _n+=i
ACCUMULATOR(x,1.0)
ACCUMULATOR(y,3)
ACCUMULATOR(z,'a')
#undef LOGIC
int main (void) {
    printf ("%f\n", x(5));   /* 6.000000 */
    printf ("%f\n", x(2.3)); /* 8.300000 */
    printf ("%i\n", y(5.0)); /* 8 */
    printf ("%i\n", y(3.3)); /* 11 */
    printf ("%c\n", z(5));   /* f */
    return 0;
}


Accumulator factory

Solution:
function accumulator(sum) {
  return function(n) {
    return sum += n;
  }
}
var x = accumulator(1);
x(5);
console.log(accumulator(3).toString() + '');
console.log(x(2.3));


Accumulator factory

Solution:
>>> def accumulator(sum):
  def f(n):
    f.sum += n
    return f.sum
  f.sum = sum
  return f

>>> x = accumulator(1)
>>> x(5)
6
>>> x(2.3)
8.3000000000000007
>>> x = accumulator(1)
>>> x(5)
6
>>> x(2.3)
8.3000000000000007
>>> x2 = accumulator(3)
>>> x2(5)
8
>>> x2(3.3)
11.300000000000001
>>> x(0)
8.3000000000000007
>>> x2(0)
11.300000000000001


Accumulator factory

Solution:
def accumulator(sum):
  def f(n):
    nonlocal sum
    sum += n
    return sum
  return f

x = accumulator(1)
x(5)
print(accumulator(3))
print(x(2.3))


Achilles numbers

An '''Achilles number''' is a number that is powerful but imperfect. ''Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.''

A positive integer '''n''' is a powerful number if, for every prime factor '''p''' of '''n''', '''p2''' is also a divisor.

In other words, every prime factor appears at least squared in the factorization.

All '''Achilles numbers''' are powerful. However, not all powerful numbers are '''Achilles numbers''': only those that cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1'''.

A '''''strong'' Achilles number''' is an '''Achilles number''' whose '''Euler totient (𝜑)''' is also an '''Achilles number'''.

;E.G.

'''108''' is a powerful number. Its prime factorization is '''22 × 33''', and thus its prime factors are '''2''' and '''3'''. Both '''22 = 4''' and  '''32 = 9''' are divisors of '''108'''. However, '''108''' cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1''', so '''108''' is an '''Achilles number'''.

'''360''' is ''not'' an '''Achilles number''' because it is not powerful. One of its prime factors is '''5''' but '''360''' is not divisible by '''52 = 25'''.

Finally, '''784''' is ''not'' an '''Achilles number'''. It is a powerful number, because not only are '''2''' and '''7''' its only prime factors, but also '''22 = 4''' and '''72 = 49''' are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is ''not'' an '''Achilles number'''.

'''500 = 22 × 53''' is a '''''strong'' Achilles number''' as its Euler totient, '''𝜑(500)''', is '''200 = 23 × 52''' which is ''also'' an '''Achilles number'''.

;Task

* Find and show the first 50 '''Achilles numbers'''.
* Find and show at least the first 20 '''''strong'' Achilles numbers'''.
* For at least 2 through 5, show the count of '''Achilles numbers''' with that many digits.

;See also

;* Wikipedia: Achilles number
;* OEIS:A052486 - Achilles numbers - powerful but imperfect numbers
;* OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number
;* Related task: Powerful numbers
;* Related task: Totient function

Solution:
from math import gcd
from sympy import factorint

def is_Achilles(n):
    p = factorint(n).values()
    return all(i > 1 for i in p) and gcd(*p) == 1

def is_strong_Achilles(n):
    return is_Achilles(n) and is_Achilles(totient(n))

def test_strong_Achilles(nachilles, nstrongachilles):
    # task 1
    print('First', nachilles, 'Achilles numbers:')
    n, found = 0, 0
    while found < nachilles:
        if is_Achilles(n):
            found += 1
            print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
        n += 1

    # task 2
    print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
    n, found = 0, 0
    while found < nstrongachilles:
        if is_strong_Achilles(n):
            found += 1
            print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
        n += 1

    # task 3
    print('\nCount of Achilles numbers for various intervals:')
    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
    for interval in intervals:
        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))

test_strong_Achilles(50, 100)


Aliquot sequence classifications

An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the [[Proper divisors]] of the previous term.

:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.

:There are several classifications for non termination:
:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.
:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.
:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.
:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.
:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.

:And finally:
:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.

;Task:
# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
# Use it to display the classification and sequences of the numbers one to ten inclusive.
# Use it to show the classification and sequences of the following integers, in order:
:: 11, 12, 28, 496, 220, 1184,  12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.

Show all output on this page.

;Related tasks:
*   [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).
*   [[Proper divisors]]
*   [[Amicable pairs]]

Solution:
#include
#include
#include

unsigned long long raiseTo(unsigned long long base, unsigned long long power){
    unsigned long long result = 1,i;
    for (i=0; i 1)
			prod *= ((raiseTo(i,count + 1) - 1)/(i-1));
	}

	if(n>2)
		prod *= (n+1);

	return prod - temp;
}

void printSeries(unsigned long long* arr,int size,char* type){
	int i;

	printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type);

	for(i=0;i",argV[0]);
	else{
		if(strchr(argV[1],'.')!=NULL)
			processFile(argV[1]);
		else
			aliquotClassifier(strtoull(argV[1],(char**)NULL,10));
	}
	return 0;
}


Aliquot sequence classifications

Solution:
from proper_divisors import proper_divs
from functools import lru_cache

@lru_cache()
def pdsum(n):
    return sum(proper_divs(n))

def aliquot(n, maxlen=16, maxterm=2**47):
    if n == 0:
        return 'terminating', [0]
    s, slen, new = [n], 1, n
    while slen <= maxlen and new < maxterm:
        new = pdsum(s[-1])
        if new in s:
            if s[0] == new:
                if slen == 1:
                    return 'perfect', s
                elif slen == 2:
                    return 'amicable', s
                else:
                    return 'sociable of length %i' % slen, s
            elif s[-1] == new:
                return 'aspiring', s
            else:
                return 'cyclic back to %i' % new, s
        elif new == 0:
            return 'terminating', s + [0]
        else:
            s.append(new)
            slen += 1
    else:
        return 'non-terminating', s

if __name__ == '__main__':
    for n in range(1, 11):
        print('%s: %r' % aliquot(n))
    print()
    for n in [11, 12, 28, 496, 220, 1184,  12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
        print('%s: %r' % aliquot(n))


Almkvist-Giullera formula for pi

The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau
differential equations of order 4 and 5,   which were originally used to describe certain manifolds
in string theory.

The formula is:
::::: 1/π2 = (25/3)  ∑0∞  ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1

This formula can be used to calculate the constant   π-2,   and thus to calculate   π.

Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:

:::::  (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)        (***)

multiplied by a negative integer power of 10:

:::::  10-(6n + 3)

;Task:
:* Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
:* Use the complete formula to calculate and print π to 70 decimal digits of precision.

;Reference:
:*  [https://arxiv.org/pdf/1009.5202.pdf Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1].

Solution:
import esMain from 'es-main';
import { BigFloat, set_precision as SetPrecision } from 'bigfloat-esnext';

const Iterations = 52;

export const demo = function() {
  SetPrecision(-75);
  console.log("N." + "Integral part of Nth term".padStart(45) + " ×10^ =Actual value of Nth term");
  for (let i=0; i<10; i++) {
    let line = `${i}. `;
    line += `${integral(i)} `.padStart(45);
    line += `${tenExponent(i)} `.padStart(5);
    line += nthTerm(i);
    console.log(line);
  }

  let pi = approximatePi(Iterations);
  SetPrecision(-70);
  pi = pi.dividedBy(100000).times(100000);
  console.log(`\nPi after ${Iterations} iterations: ${pi}`)
}

export const bigFactorial = n => n <= 1n ? 1n : n * bigFactorial(n-1n);

// the nth integer term
export const integral = function(i) {
  let n = BigInt(i);
  const polynomial  = 532n * n * n + 126n * n + 9n;
  const numerator   = 32n * bigFactorial(6n * n) * polynomial;
  const denominator = 3n * bigFactorial(n) ** 6n;
  return numerator / denominator;
}

// the exponent for 10 in the nth term of the series
export const tenExponent = n => 3n - 6n * (BigInt(n) + 1n);

// the nth term of the series
export const nthTerm = n =>
  new BigFloat(integral(n)).dividedBy(new BigFloat(10n ** -tenExponent(n)))

// the sum of the first n terms
export const sumThrough = function(n) {
  let sum = new BigFloat(0);
  for (let i=0; i<=n; ++i) {
    sum = sum.plus(nthTerm(i));
  }
  return sum;
}

// the approximation to pi after n terms
export const approximatePi  = n =>
   new BigFloat(1).dividedBy(sumThrough(n)).sqrt();

if (esMain(import.meta))
   demo();


Almkvist-Giullera formula for pi

Solution:
import mpmath as mp

with mp.workdps(72):

    def integer_term(n):
        p = 532 * n * n + 126 * n + 9
        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)

    def exponent_term(n):
        return -(mp.mpf("6.0") * n + 3)

    def nthterm(n):
        return integer_term(n) * mp.mpf("10.0")**exponent_term(n)

    for n in range(10):
        print("Term ", n, '  ', int(integer_term(n)))

    def almkvist_guillera(floatprecision):
        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
        for n in range(100000000):
            nextadd = summed + nthterm(n)
            if abs(nextadd - summed) < 10.0**(-floatprecision):
                break

            summed = nextadd

        return nextadd

    print('\nπ to 70 digits is ', end='')
    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
    print('mpmath π is       ', end='')
    mp.nprint(mp.pi, 71)


Amb

Define and give an example of the Amb operator.

The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").

The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.

Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.

Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away.   Amb called with no arguments fails.

For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.

A pseudo-code program which satisfies this constraint might look like:

let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y

The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.

Alternatively, failure could be represented using strictly Amb():

unless x * y = 8 do Amb()

Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:

let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y

where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.

The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:

#"the" "that" "a"
#"frog" "elephant" "thing"
#"walked" "treaded" "grows"
#"slowly" "quickly"

The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.

The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.

The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.

Solution:
typedef const char * amb_t;

amb_t amb(size_t argc, ...)
{
  amb_t *choices;
  va_list ap;
  int i;

  if(argc) {
    choices = malloc(argc*sizeof(amb_t));
    va_start(ap, argc);
    i = 0;
    do { choices[i] = va_arg(ap, amb_t); } while(++i < argc);
    va_end(ap);

    i = 0;
    do { TRY(choices[i]); } while(++i < argc);
    free(choices);
  }

  FAIL;
}

int joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; }

int _main() {
  const char *w1,*w2,*w3,*w4;

  w1 = amb(3, "the", "that", "a");
  w2 = amb(3, "frog", "elephant", "thing");
  w3 = amb(3, "walked", "treaded", "grows");
  w4 = amb(2, "slowly", "quickly");

  if(!joins(w1, w2)) amb(0);
  if(!joins(w2, w3)) amb(0);
  if(!joins(w3, w4)) amb(0);

  printf("%s %s %s %s\n", w1, w2, w3, w4);

  return EXIT_SUCCESS;
}


Amb

Solution:
function ambRun(func) {
    var choices = [];
    var index;

    function amb(values) {
        if (values.length == 0) {
            fail();
        }
        if (index == choices.length) {
            choices.push({i: 0,
                          count: values.length});
        }
        var choice = choices[index++];
        return values[choice.i];
    }

    function fail() { throw fail; }

    while (true) {
        try {
            index = 0;
            return func(amb, fail);
        } catch (e) {
            if (e != fail) {
                throw e;
            }
            var choice;
            while ((choice = choices.pop()) && ++choice.i == choice.count) {}
            if (choice == undefined) {
                return undefined;
            }
            choices.push(choice);
        }
    }
}

ambRun(function(amb, fail) {
    function linked(s1, s2) {
        return s1.slice(-1) == s2.slice(0, 1);
    }

    var w1 = amb(["the", "that", "a"]);
    var w2 = amb(["frog", "elephant", "thing"]);
    if (!linked(w1, w2)) fail();

    var w3 = amb(["walked", "treaded", "grows"]);
    if (!linked(w2, w3)) fail();

    var w4 = amb(["slowly", "quickly"]);
    if (!linked(w3, w4)) fail();

    return [w1, w2, w3, w4].join(' ');
});  // "that thing grows slowly"


Amb

Solution:
import itertools as _itertools

class Amb(object):
    def __init__(self):
        self._names2values   = {}       # set of values for each global name
        self._func           = None     # Boolean constraint function
        self._valueiterator  = None     # itertools.product of names values
        self._funcargnames   = None     # Constraint parameter names

    def __call__(self, arg=None):
        if hasattr(arg, '__code__'):
            ##
            ## Called with a constraint function.
            ##
            globls = arg.__globals__ if hasattr(arg, '__globals__') else arg.func_globals
            # Names used in constraint
            argv = arg.__code__.co_varnames[:arg.__code__.co_argcount]
            for name in argv:
                if name not in self._names2values:
                    assert name in globls, \
                           "Global name %s not found in function globals" % name
                    self._names2values[name] = globls[name]
            # Gather the range of values of all names used in the constraint
            valuesets = [self._names2values[name] for name in argv]
            self._valueiterator = _itertools.product(*valuesets)
            self._func = arg
            self._funcargnames = argv
            return self
        elif arg is not None:
            ##
            ## Assume called with an iterable set of values
            ##
            arg = frozenset(arg)
            return arg
        else:
            ##
            ## blank call tries to return next solution
            ##
            return self._nextinsearch()

    def _nextinsearch(self):
        arg = self._func
        globls = arg.__globals__
        argv = self._funcargnames
        found = False
        for values in self._valueiterator:
            if arg(*values):
                # Set globals.
                found = True
                for n, v in zip(argv, values):
                    globls[n] = v
                break
        if not found: raise StopIteration
        return values

    def __iter__(self):
        return self

    def __next__(self):
        return self()
    next = __next__ # Python 2

if __name__ == '__main__':
    if True:
        amb = Amb()

        print("\nSmall Pythagorean triples problem:")
        x = amb(range(1,11))
        y = amb(range(1,11))
        z = amb(range(1,11))

        for _dummy in amb( lambda x, y, z: x*x + y*y == z*z ):
            print ('%s %s %s' % (x, y, z))

    if True:
        amb = Amb()

        print("\nRosetta Code Amb problem:")
        w1 = amb(["the", "that", "a"])
        w2 = amb(["frog", "elephant", "thing"])
        w3 = amb(["walked", "treaded", "grows"])
        w4 = amb(["slowly", "quickly"])

        for _dummy in amb( lambda w1, w2, w3, w4: \
                             w1[-1] == w2[0] and \
                             w2[-1] == w3[0] and \
                             w3[-1] == w4[0] ):
            print ('%s %s %s %s' % (w1, w2, w3, w4))

    if True:
        amb = Amb()

        print("\nAmb problem from "
            "http://www.randomhacks.net/articles/2005/10/11/amb-operator:")
        x = amb([1, 2, 3])
        y = amb([4, 5, 6])

        for _dummy in amb( lambda x, y: x * y != 8 ):
            print ('%s %s' % (x, y))


Anagrams/Deranged anagrams

Two or more words are said to be anagrams if they have the same characters, but in a different order.

By analogy with derangements we define a  ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.

;Task

Use the word list at [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict] to find and display the longest deranged anagram.

;Related
* [[Permutations/Derangements]]
* Best shuffle

Solution:
#include
#include
#include
#include
#include
#include
#include

// Letter lookup by frequency.  This is to reduce word insertion time.
const char *freq = "zqxjkvbpygfwmucldrhsnioate";
int char_to_idx[128];

// Trie structure of sorts
struct word {
	const char *w;
	struct word *next;
};

union node {
	union node *down[10];
	struct word *list[10];
};

int deranged(const char *s1, const char *s2)
{
	int i;
	for (i = 0; s1[i]; i++)
		if (s1[i] == s2[i]) return 0;
	return 1;
}

int count_letters(const char *s, unsigned char *c)
{
	int i, len;
	memset(c, 0, 26);
	for (len = i = 0; s[i]; i++) {
		if (s[i] < 'a' || s[i] > 'z')
			return 0;
		len++, c[char_to_idx[(unsigned char)s[i]]]++;
	}
	return len;
}

const char * insert(union node *root, const char *s, unsigned char *cnt)
{
	int i;
	union node *n;
	struct word *v, *w = 0;

	for (i = 0; i < 25; i++, root = n) {
		if (!(n = root->down[cnt[i]]))
			root->down[cnt[i]] = n = calloc(1, sizeof(union node));
	}

	w = malloc(sizeof(struct word));
	w->w = s;
	w->next = root->list[cnt[25]];
	root->list[cnt[25]] = w;

	for (v = w->next; v; v = v->next) {
		if (deranged(w->w, v->w))
			return v->w;
	}
	return 0;
}

int main(int c, char **v)
{
	int i, j = 0;
	char *words;
	struct stat st;

	int fd = open(c < 2 ? "unixdict.txt" : v[1], O_RDONLY);
	if (fstat(fd, &st) < 0) return 1;

	words = malloc(st.st_size);
	read(fd, words, st.st_size);
	close(fd);

	union node root = {{0}};
	unsigned char cnt[26];
	int best_len = 0;
	const char *b1, *b2;

	for (i = 0; freq[i]; i++)
		char_to_idx[(unsigned char)freq[i]] = i;

	/* count words, change newline to null */
	for (i = j = 0; i < st.st_size; i++) {
		if (words[i] != '\n') continue;
		words[i] = '\0';

		if (i - j > best_len) {
			count_letters(words + j, cnt);
			const char *match = insert(&root, words + j, cnt);

			if (match) {
				best_len = i - j;
				b1 = words + j;
				b2 = match;
			}
		}

		j = ++i;
	}

	if (best_len) printf("longest derangement: %s %s\n", b1, b2);

	return 0;
}


Anagrams/Deranged anagrams

Solution:
#!/usr/bin/env js

function main() {
    var wordList = read('unixdict.txt').split(/\s+/);
    var anagrams = findAnagrams(wordList);
    var derangedAnagrams = findDerangedAnagrams(anagrams);
    var longestPair = findLongestDerangedPair(derangedAnagrams);
    print(longestPair.join(' '));

}

function findLongestDerangedPair(danas) {
    var longestLen = danas[0][0].length;
    var longestPair = danas[0];
    for (var i in danas) {
        if (danas[i][0].length > longestLen) {
            longestLen = danas[i][0].length;
            longestPair = danas[i];
        }
    }
    return longestPair;
}

function findDerangedAnagrams(anagrams) {
    var deranged = [];

    function isDeranged(w1, w2) {
        for (var c = 0; c < w1.length; c++) {
            if (w1[c] == w2[c]) {
                return false;
            }
        }
        return true;
    }

    function findDeranged(anas) {
        for (var a = 0; a < anas.length; a++) {
            for (var b = a + 1; b < anas.length; b++) {
                if (isDeranged(anas[a], anas[b])) {
                    deranged.push([anas[a], anas[b]]);
                }
            }
        }
    }

    for (var a in anagrams) {
        var anas = anagrams[a];
        findDeranged(anas);
    }

    return deranged;
}

function findAnagrams(wordList) {
    var anagrams = {};

    for (var wordNum in wordList) {
        var word = wordList[wordNum];
        var key = word.split('').sort().join('');
        if (!(key in anagrams)) {
            anagrams[key] = [];
        }
        anagrams[key].push(word);
    }

    for (var a in anagrams) {
        if (anagrams[a].length < 2) {
            delete(anagrams[a]);
        }
    }

    return anagrams;
}

main();


Anagrams/Deranged anagrams

Solution:
import urllib.request
from collections import defaultdict
from itertools import combinations

def getwords(url='http://www.puzzlers.org/pub/wordlists/unixdict.txt'):
    return list(set(urllib.request.urlopen(url).read().decode().split()))

def find_anagrams(words):
    anagram = defaultdict(list) # map sorted chars to anagrams
    for word in words:
        anagram[tuple(sorted(word))].append( word )
    return dict((key, words) for key, words in anagram.items()
                if len(words) > 1)

def is_deranged(words):
    'returns pairs of words that have no character in the same position'
    return [ (word1, word2)
             for word1,word2 in combinations(words, 2)
             if all(ch1 != ch2 for ch1, ch2 in zip(word1, word2)) ]

def largest_deranged_ana(anagrams):
    ordered_anagrams = sorted(anagrams.items(),
                              key=lambda x:(-len(x[0]), x[0]))
    for _, words in ordered_anagrams:
        deranged_pairs = is_deranged(words)
        if deranged_pairs:
            return deranged_pairs
    return []

if __name__ == '__main__':
    words = getwords('http://www.puzzlers.org/pub/wordlists/unixdict.txt')
    print("Word count:", len(words))

    anagrams = find_anagrams(words)
    print("Anagram count:", len(anagrams),"\n")

    print("Longest anagrams with no characters in the same position:")
    print('  ' + '\n  '.join(', '.join(pairs)
                             for pairs in largest_deranged_ana(anagrams)))


Angle difference between two bearings

Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]

;Task:
Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings.

Input bearings are expressed in the range   '''-180'''   to   '''+180'''   degrees.
The  result  is also expressed in the range   '''-180'''   to   '''+180'''   degrees.

Compute the angle for the following pairs:
*  20 degrees ('''b1''') and 45 degrees ('''b2''')
* -45 and  45
* -85 and  90
* -95 and  90
* -45 and 125
* -45 and 145
*  29.4803 and  -88.6381
* -78.3251 and -159.036

;Optional extra:
Allow the input bearings to be any (finite) value.

;Test cases:
*  -70099.74233810938   and   29840.67437876723
* -165313.6666297357    and   33693.9894517456
*    1174.8380510598456 and -154146.66490124757
*   60175.77306795546   and   42213.07192354373

Solution:
#include
#include
#include

void processFile(char* name){

	int i,records;
	double diff,b1,b2;
	FILE* fp = fopen(name,"r");

	fscanf(fp,"%d\n",&records);

	for(i=0;i=180)?diff-360:diff));
	}

	fclose(fp);
}

int main(int argC,char* argV[])
{
	double diff;

	if(argC < 2)
		printf("Usage : %s ",argV[0]);
	else if(argC == 2)
		processFile(argV[1]);
	else{
		diff = fmod(atof(argV[2])-atof(argV[1]),360.0);
		printf("Difference between b2(%s) and b1(%s) is %lf",argV[2],argV[1],(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
	}

	return 0;
}


Angle difference between two bearings

Solution:
from __future__ import print_function

def getDifference(b1, b2):
	r = (b2 - b1) % 360.0
	# Python modulus has same sign as divisor, which is positive here,
	# so no need to consider negative case
	if r >= 180.0:
		r -= 360.0
	return r

if __name__ == "__main__":
	print ("Input in -180 to +180 range")
	print (getDifference(20.0, 45.0))
	print (getDifference(-45.0, 45.0))
	print (getDifference(-85.0, 90.0))
	print (getDifference(-95.0, 90.0))
	print (getDifference(-45.0, 125.0))
	print (getDifference(-45.0, 145.0))
	print (getDifference(-45.0, 125.0))
	print (getDifference(-45.0, 145.0))
	print (getDifference(29.4803, -88.6381))
	print (getDifference(-78.3251, -159.036))

	print ("Input in wider range")
	print (getDifference(-70099.74233810938, 29840.67437876723))
	print (getDifference(-165313.6666297357, 33693.9894517456))
	print (getDifference(1174.8380510598456, -154146.66490124757))
	print (getDifference(60175.77306795546, 42213.07192354373))


Anti-primes

The [https://youtu.be/2JM2oImb9Qg anti-primes]
(or [https://en.wikipedia.org/wiki/Highly_composite_number highly composite numbers], sequence [https://oeis.org/A002182 A002182] in the [https://oeis.org/ OEIS])
are the natural numbers with more factors than any smaller than itself.

;Task:
Generate and show here, the first twenty anti-primes.

;Related tasks:
:*   [[Factors of an integer]]
:*   [[Sieve of Eratosthenes]]

Solution:
#include

int countDivisors(int n) {
    int i, count;
    if (n < 2) return 1;
    count = 2; // 1 and n
    for (i = 2; i <= n/2; ++i) {
        if (n%i == 0) ++count;
    }
    return count;
}

int main() {
    int n, d, maxDiv = 0, count = 0;
    printf("The first 20 anti-primes are:\n");
    for (n = 1; count < 20; ++n) {
        d = countDivisors(n);
        if (d > maxDiv) {
            printf("%d ", n);
            maxDiv = d;
            count++;
        }
    }
    printf("\n");
    return 0;
}


Anti-primes

Solution:
from itertools import chain, count, cycle, islice, accumulate

def factors(n):
    def prime_powers(n):
        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
            if c*c > n: break
            if n%c: continue
            d,p = (), c
            while not n%c:
                n,p,d = n//c, p*c, d+(p,)
            yield d
        if n > 1: yield n,

    r = [1]
    for e in prime_powers(n):
        r += [a*b for a in r for b in e]
    return r

def antiprimes():
    mx = 0
    yield 1
    for c in count(2,2):
        if c >= 58: break
        ln = len(factors(c))
        if ln > mx:
            yield c
            mx = ln
    for c in count(60,30):
        ln = len(factors(c))
        if ln > mx:
            yield c
            mx = ln

if __name__ == '__main__':
    print(*islice(antiprimes(), 40)))


Apply a digital filter (direct form II transposed)

Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]

;Task:

Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]

The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]

;See also:
[[https://en.wikipedia.org/wiki/Butterworth_filter Wikipedia on Butterworth filters]]

Solution:
#include
#include
#include

#define MAX_LEN 1000

typedef struct{
	float* values;
	int size;
}vector;

vector extractVector(char* str){
	vector coeff;
	int i=0,count = 1;
	char* token;

	while(str[i]!=00){
		if(str[i++]==' ')
			count++;
	}

	coeff.values = (float*)malloc(count*sizeof(float));
	coeff.size = count;

	token = strtok(str," ");

	i = 0;

	while(token!=NULL){
		coeff.values[i++] = atof(token);
		token = strtok(NULL," ");
	}

	return coeff;
}

vector processSignalFile(char* fileName){
	int i,j;
	float sum;
	char str[MAX_LEN];
	vector coeff1,coeff2,signal,filteredSignal;

	FILE* fp = fopen(fileName,"r");

	fgets(str,MAX_LEN,fp);
	coeff1 = extractVector(str);

	fgets(str,MAX_LEN,fp);
	coeff2 = extractVector(str);

	fgets(str,MAX_LEN,fp);
	signal = extractVector(str);

        fclose(fp);

	filteredSignal.values = (float*)calloc(signal.size,sizeof(float));
	filteredSignal.size = signal.size;

	for(i=0;i=0)
				sum += coeff2.values[j]*signal.values[i-j];
		}

		for(j=0;j=0)
				sum -= coeff1.values[j]*filteredSignal.values[i-j];
		}

		sum /= coeff1.values[0];
		filteredSignal.values[i] = sum;
	}

	return filteredSignal;
}

void printVector(vector v, char* outputFile){
	int i;

	if(outputFile==NULL){
		printf("[");
		for(i=0;i3)
		printf("Usage : %s ",argV[0]);
	else{
		if(argC!=2){
			str = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char));
			strcpy(str,"written to ");
		}
		printf("Filtered signal %s",(argC==2)?"is:\n":strcat(str,argV[2]));
		printVector(processSignalFile(argV[1]),argV[2]);
	}
	return 0;
}


Solution:
#!/bin/python
from __future__ import print_function
from scipy import signal
import matplotlib.pyplot as plt

if __name__=="__main__":
	sig = [-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973,-1.00700480494,
		-0.404707073677,0.800482325044,0.743500089861,1.01090520172,0.741527555207,
		0.277841675195,0.400833448236,-0.2085993586,-0.172842103641,-0.134316096293,
		0.0259303398477,0.490105989562,0.549391221511,0.9047198589]

	#Create an order 3 lowpass butterworth filter
	#Generated using b, a = signal.butter(3, 0.5)
	a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]
	b = [0.16666667, 0.5, 0.5, 0.16666667]

	#Apply the filter to signal
	filt = signal.lfilter(b, a, sig)
	print (filt)

	plt.plot(sig, 'b')
	plt.plot(filt, 'r--')
	plt.show()


Approximate equality

Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.

For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.

;Task:
Create a function which returns true if two floating point numbers are approximately equal.

The function should allow for differences in the magnitude of numbers, so that, for example,
'''100000000000000.01'''   may be approximately equal to   '''100000000000000.011''',
even though   '''100.01'''   is not approximately equal to   '''100.011'''.

If the language has such a feature in its standard library, this may be used instead of a custom function.

Show the function results with comparisons on the following pairs of values:
:#     100000000000000.01,                        100000000000000.011       (note: should return ''true'')
:#     100.01,                                    100.011                                                     (note: should return ''false'')
:#     10000000000000.001 / 10000.0,   1000000000.0000001000
:#     0.001,                                     0.0010000001
:#     0.000000000000000000000101,                0.0
:#      sqrt(2) * sqrt(2),                    2.0
:#     -sqrt(2) * sqrt(2),                        -2.0
:#     3.14159265358979323846,                    3.14159265358979324

Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.

__TOC__

Solution:
#include
#include
#include

bool approxEquals(double value, double other, double epsilon) {
    return fabs(value - other) < epsilon;
}

void test(double a, double b) {
    double epsilon = 1e-18;
    printf("%f, %f => %d\n", a, b, approxEquals(a, b, epsilon));
}

int main() {
    test(100000000000000.01, 100000000000000.011);
    test(100.01, 100.011);
    test(10000000000000.001 / 10000.0, 1000000000.0000001000);
    test(0.001, 0.0010000001);
    test(0.000000000000000000000101, 0.0);
    test(sqrt(2.0) * sqrt(2.0), 2.0);
    test(-sqrt(2.0) * sqrt(2.0), -2.0);
    test(3.14159265358979323846, 3.14159265358979324);
    return 0;
}


Approximate equality

Solution:
from numpy import sqrt
from math import isclose

testvalues = [[100000000000000.01,           100000000000000.011],
              [100.01,                       100.011],
              [10000000000000.001 / 10000.0, 1000000000.0000001000],
              [0.001,                        0.0010000001],
              [0.000000000000000000000101,   0.0],
              [sqrt(2) * sqrt(2),            2.0],
              [-sqrt(2) * sqrt(2),          -2.0],
              [3.14159265358979323846,       3.14159265358979324]]

for (x, y) in testvalues:
    maybenot = "is" if isclose(x, y) else "is NOT"
    print(x, maybenot, "approximately equal to ", y)


Archimedean spiral

right

The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.

An Archimedean spiral can be described by the equation:

:\, r=a+b\theta

with real numbers ''a'' and ''b''.

;Task
Draw an Archimedean spiral.

Solution:
#include
#include
#include

#define pi M_PI

int main(){
	double a,b,cycles,incr,i;

	int steps,x=500,y=500;

	printf("Enter the parameters a and b : ");
	scanf("%lf%lf",&a,&b);

	printf("Enter cycles : ");
	scanf("%lf",&cycles);

	printf("Enter divisional steps : ");
	scanf("%d",&steps);

	incr = 1.0/steps;

	initwindow(1000,1000,"Archimedean Spiral");

	for(i=0;i<=cycles*pi;i+=incr){
		putpixel(x + (a + b*i)*cos(i),x + (a + b*i)*sin(i),15);
	}

	getch();

	closegraph();
}


Archimedean spiral

Solution:
from turtle import *
from math import *
color("blue")
down()
for i in range(200):
    t = i / 20 * pi
    x = (1 + 5 * t) * cos(t)
    y = (1 + 5 * t) * sin(t)
    goto(x, y)
up()
done()


Arena storage pool

Dynamically allocated objects take their memory from a [[heap]].

The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].

Often a call to allocator is denoted as
P := new T
where   '''T'''   is the type of an allocated object,   and   '''P'''   is a [[reference]] to the object.

The storage pool chosen by the allocator can be determined by either:
* the object type   '''T'''
* the type of pointer   '''P'''

In the former case objects can be allocated only in one storage pool.

In the latter case objects of the type can be allocated in any storage pool or on the [[stack]].

;Task:
The task is to show how allocators and user-defined storage pools are supported by the language.

In particular:
# define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups.
# allocate some objects (e.g., integers) in the pool.

Explain what controls the storage pool choice in the language.

Solution:
#include
#include
#include

// VERY rudimentary C memory management independent of C library's malloc.

// Linked list (yes, this is inefficient)
struct __ALLOCC_ENTRY__
{
    void * allocatedAddr;
    size_t size;
    struct __ALLOCC_ENTRY__ * next;
};
typedef struct __ALLOCC_ENTRY__ __ALLOCC_ENTRY__;

// Keeps track of allocated memory and metadata
__ALLOCC_ENTRY__ * __ALLOCC_ROOT__ = NULL;
__ALLOCC_ENTRY__ * __ALLOCC_TAIL__ = NULL;

// Add new metadata to the table
void _add_mem_entry(void * location, size_t size)
{

    __ALLOCC_ENTRY__ * newEntry = (__ALLOCC_ENTRY__ *) mmap(NULL, sizeof(__ALLOCC_ENTRY__), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    if (__ALLOCC_TAIL__ != NULL)
    {
        __ALLOCC_TAIL__ -> next = newEntry;
        __ALLOCC_TAIL__ = __ALLOCC_TAIL__ -> next;
    }
    else
    {
        // Create new table
        __ALLOCC_ROOT__ = newEntry;
        __ALLOCC_TAIL__ = newEntry;
    }

    __ALLOCC_ENTRY__ * tail = __ALLOCC_TAIL__;
    tail -> allocatedAddr = location;
    tail -> size = size;
    tail -> next = NULL;
    __ALLOCC_TAIL__ = tail;
}

// Remove metadata from the table given pointer
size_t _remove_mem_entry(void * location)
{
    __ALLOCC_ENTRY__ * curNode = __ALLOCC_ROOT__;

    // Nothing to do
    if (curNode == NULL)
    {
        return 0;
    }

    // First entry matches
    if (curNode -> allocatedAddr == location)
    {
        __ALLOCC_ROOT__ = curNode -> next;
        size_t chunkSize = curNode -> size;

        // No nodes left
        if (__ALLOCC_ROOT__ == NULL)
        {
            __ALLOCC_TAIL__ = NULL;
        }
        munmap(curNode, sizeof(__ALLOCC_ENTRY__));

        return chunkSize;
    }

    // If next node is null, remove it
    while (curNode -> next != NULL)
    {
        __ALLOCC_ENTRY__ * nextNode = curNode -> next;

        if (nextNode -> allocatedAddr == location)
        {
            size_t chunkSize = nextNode -> size;

            if(curNode -> next == __ALLOCC_TAIL__)
            {
                __ALLOCC_TAIL__ = curNode;
            }
            curNode -> next = nextNode -> next;
            munmap(nextNode, sizeof(__ALLOCC_ENTRY__));

            return chunkSize;
        }

        curNode = nextNode;
    }

    // Nothing was found
    return 0;
}

// Allocate a block of memory with size
// When customMalloc an already mapped location, causes undefined behavior
void * customMalloc(size_t size)
{
    // Now we can use 0 as our error state
    if (size == 0)
    {
        return NULL;
    }

    void * mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    // Store metadata
    _add_mem_entry(mapped, size);

    return mapped;
}

// Free a block of memory that has been customMalloc'ed
void customFree(void * addr)
{
    size_t size = _remove_mem_entry(addr);

    munmap(addr, size);
}

int main(int argc, char const *argv[])
{
    int *p1 = customMalloc(4*sizeof(int));  // allocates enough for an array of 4 int
    int *p2 = customMalloc(sizeof(int[4])); // same, naming the type directly
    int *p3 = customMalloc(4*sizeof *p3);   // same, without repeating the type name

    if(p1) {
        for(int n=0; n<4; ++n) // populate the array
            p1[n] = n*n;
        for(int n=0; n<4; ++n) // print it back out
            printf("p1[%d] == %d\n", n, p1[n]);
    }

    customFree(p1);
    customFree(p2);
    customFree(p3);

    return 0;
}


Arena storage pool

Solution:
In Python:
* Everything is an object.
* Objects are dynamically allocated.
* Unused objects are garbage collected.

Where objects appear from, or disappear to, is treated as an implementation detail.

Statements, such as assignments, class and function definitions, and import statements can create objects and assign names to them which can be seen as assigning a reference to objects. Objects can also be referred to from other objects e.g. in collections such as lists.<br>
When names go out of scope, or objects are explicitly destroyed, references to objects are diminished. Python's implementation keeps track of references to objects and marks objects that have no remaining references so that they become candidates for '[[wp:Garbage collection (computer science)|garbage collection]]' at a later time.


Arithmetic-geometric mean

;Task:
Write a function to compute the arithmetic-geometric mean of two numbers.

The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence:
: a_0 = a; \qquad g_0 = g
: a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}.
Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.

Demonstrate the function by calculating:
:\mathrm{agm}(1,1/\sqrt{2})

;Also see:
*   [http://mathworld.wolfram.com/Arithmetic-GeometricMean.html mathworld.wolfram.com/Arithmetic-Geometric Mean]

Solution:
/*Arithmetic Geometric Mean of 1 and 1/sqrt(2)

  Nigel_Galloway
  February 7th., 2012.
*/

#include "gmp.h"

void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
	mpf_add (out1, in1, in2);
	mpf_div_ui (out1, out1, 2);
	mpf_mul (out2, in1, in2);
	mpf_sqrt (out2, out2);
}

int main (void) {
	mpf_set_default_prec (65568);
	mpf_t x0, y0, resA, resB;

	mpf_init_set_ui (y0, 1);
	mpf_init_set_d (x0, 0.5);
	mpf_sqrt (x0, x0);
	mpf_init (resA);
	mpf_init (resB);

	for(int i=0; i<7; i++){
		agm(x0, y0, resA, resB);
		agm(resA, resB, x0, y0);
	}
	gmp_printf ("%.20000Ff\n", x0);
	gmp_printf ("%.20000Ff\n\n", y0);

	return 0;
}


Arithmetic-geometric mean

Solution:
(() => {
    'use strict';

    // ARITHMETIC-GEOMETRIC MEAN

    // agm :: Num a => a -> a -> a
    let agm = (a, g) => {
            let abs = Math.abs,
                sqrt = Math.sqrt;

            return until(
                    m => abs(m.an - m.gn) < tolerance,
                    m => {
                        return {
                            an: (m.an + m.gn) / 2,
                            gn: sqrt(m.an * m.gn)
                        };
                    }, {
                        an: (a + g) / 2,
                        gn: sqrt(a * g)
                    }
                )
                .an;
        },

        // GENERIC

        // until :: (a -> Bool) -> (a -> a) -> a -> a
        until = (p, f, x) => {
            let v = x;
            while (!p(v)) v = f(v);
            return v;
        };

    // TEST

    let tolerance = 0.000001;

    return agm(1, 1 / Math.sqrt(2));

})();


Arithmetic-geometric mean

Solution:
from math import sqrt

def agm(a0, g0, tolerance=1e-10):
    """
    Calculating the arithmetic-geometric mean of two numbers a0, g0.

    tolerance     the tolerance for the converged
                  value of the arithmetic-geometric mean
                  (default value = 1e-10)
    """
    an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)
    while abs(an - gn) > tolerance:
        an, gn = (an + gn) / 2.0, sqrt(an * gn)
    return an

print agm(1, 1 / sqrt(2))


Arithmetic-geometric mean/Calculate Pi

[http://www.maa.org/sites/default/files/pdf/upload_library/22/Ford/Almkvist-Berndt585-608.pdf Almkvist Berndt 1988] begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi.

With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:

\pi =
\frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2}
{1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)}

This allows you to make the approximation, for any large   '''N''':

\pi \approx
\frac{4\; a_N^2}
{1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}

The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi.

Solution:
#include "gmp.h"

void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
	mpf_add (out1, in1, in2);
	mpf_div_ui (out1, out1, 2);
	mpf_mul (out2, in1, in2);
	mpf_sqrt (out2, out2);
}

int main (void) {
	mpf_set_default_prec (300000);
	mpf_t x0, y0, resA, resB, Z, var;

	mpf_init_set_ui (x0, 1);
	mpf_init_set_d (y0, 0.5);
	mpf_sqrt (y0, y0);
	mpf_init (resA);
	mpf_init (resB);
	mpf_init_set_d (Z, 0.25);
	mpf_init (var);

	int n = 1;
        int i;
	for(i=0; i<8; i++){
		agm(x0, y0, resA, resB);
		mpf_sub(var, resA, x0);
		mpf_mul(var, var, var);
		mpf_mul_ui(var, var, n);
		mpf_sub(Z, Z, var);
		n += n;
		agm(resA, resB, x0, y0);
		mpf_sub(var, x0, resA);
		mpf_mul(var, var, var);
		mpf_mul_ui(var, var, n);
		mpf_sub(Z, Z, var);
		n += n;
	}
	mpf_mul(x0, x0, x0);
	mpf_div(x0, x0, Z);
	gmp_printf ("%.100000Ff\n", x0);
	return 0;
}


Arithmetic-geometric mean/Calculate Pi

Solution:
from decimal import *

D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
    x = [(a + g) * half, (a * g).sqrt()]
    var = x[0] - a
    z -= var * var * n
    n += n
    a, g = x
print(a * a / z)


Arithmetic derivative

The '''arithmetic derivative''' of an integer (more specifically, the
'''Lagarias arithmetic derivative''') is a function defined for integers, based on prime
factorization, by analogy with the product rule for the derivative of a function that is
used in mathematical analysis. Accordingly, for natural numbers n, the arithmetic
derivative D(n) is defined as follows:

;*D(0) = D(1) = 0.
;*D(p) = 1 for any prime p.
;*D(mn) = D(m)n + mD(n) for any m,n ∈ N. (Leibniz rule for derivatives).

Additionally, for negative integers the arithmetic derivative may be defined as -D(-n) (n < 0).

; Examples

D(2) = 1 and D(3) = 1 (both are prime) so if mn = 2 * 3, D(6) = (1)(3) + (1)(2) = 5.

D(9) = D(3)(3) + D(3)(3) = 6

D(27) = D(3)*9 + D(9)*3 = 9 + 18 = 27

D(30) = D(5)(6) + D(6)(5) = 6 + 5 * 5 = 31.

; Task

Find and show the arithmetic derivatives for -99 through 100.

; Stretch task

Find (the arithmetic derivative of 10^m) then divided by 7, where m is from 1 to 20.

; See also

;* OEIS:A003415 - a(n) = n' = arithmetic derivative of n.
;*Wikipedia: Arithmetic Derivative

Solution:
#include
#include

typedef uint64_t u64;

void primeFactors(u64 n, u64 *factors, int *length) {
    if (n < 2) return;
    int count = 0;
    int inc[8] = {4, 2, 4, 2, 4, 6, 2, 6};
    while (!(n%2)) {
        factors[count++] = 2;
        n /= 2;
    }
    while (!(n%3)) {
        factors[count++] = 3;
        n /= 3;
    }
    while (!(n%5)) {
        factors[count++] = 5;
        n /= 5;
    }
    for (u64 k = 7, i = 0; k*k <= n; ) {
        if (!(n%k)) {
            factors[count++] = k;
            n /= k;
        } else {
            k += inc[i];
            i = (i + 1) % 8;
        }
    }
    if (n > 1) {
        factors[count++] = n;
    }
    *length = count;
}

double D(double n) {
    if (n < 0) return -D(-n);
    if (n < 2) return 0;
    int i, length;
    double d;
    u64 f[80], g;
    if (n < 1e19) {
        primeFactors((u64)n, f, &length);
    } else {
        g = (u64)(n / 100);
        primeFactors(g, f, &length);
        f[length+1] = f[length] = 2;
        f[length+3] = f[length+2] = 5;
        length += 4;
    }
    if (length == 1) return 1;
    if (length == 2) return (double)(f[0] + f[1]);
    d = n / (double)f[0];
    return D(d) * (double)f[0] + d;
}

int main() {
    u64 ad[200];
    int n, m;
    double pow;
    for (n = -99; n < 101; ++n) {
        ad[n+99] = (int)D((double)n);
    }
    for (n = 0; n < 200; ++n) {
        printf("%4ld ", ad[n]);
        if (!((n+1)%10)) printf("\n");
    }
    printf("\n");
    pow = 1;
    for (m = 1; m < 21; ++m) {
        pow *= 10;
        printf("D(10^%-2d) / 7 = %.0f\n", m, D(pow)/7);
    }
    return 0;
}


Arithmetic derivative

Solution:
from sympy.ntheory import factorint

def D(n):
    if n < 0:
        return -D(-n)
    elif n < 2:
        return 0
    else:
        fdict = factorint(n)
        if len(fdict) == 1 and 1 in fdict: # is prime
            return 1
        return sum([n * e // p for p, e in fdict.items()])

for n in range(-99, 101):
    print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '')

print()
for m in range(1, 21):
    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))


Arithmetic evaluation

;Requirements:
* An abstract-syntax tree (AST) for the expression must be created from parsing the input.
* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
* The expression will be a string or list of symbols like "(1+3)*7".
* The four symbols + - * / must be supported as binary operators with conventional precedence rules.
* Precedence-control parentheses must also be supported.

;Note:
For those who don't remember, mathematical precedence is as follows:
* Parentheses
* Multiplication/Division (left to right)
* Addition/Subtraction (left to right)

;C.f:
* [[24 game Player]].
* [[Parsing/RPN calculator algorithm]].
* [[Parsing/RPN to infix conversion]].

Solution:
function evalArithmeticExp(s) {
  s = s.replace(/\s/g,'').replace(/^\+/,'');
  var rePara = /\([^\(\)]*\)/;
  var exp = s.match(rePara);

  while (exp = s.match(rePara)) {
    s = s.replace(exp[0], evalExp(exp[0]));
  }
  return evalExp(s);

  function evalExp(s) {
    s = s.replace(/[\(\)]/g,'');
    var reMD = /\d+\.?\d*\s*[\*\/]\s*[+-]?\d+\.?\d*/;
    var reM = /\*/;
    var reAS = /-?\d+\.?\d*\s*[\+-]\s*[+-]?\d+\.?\d*/;
    var reA  = /\d\+/;
    var exp;

    while (exp = s.match(reMD)) {
      s = exp[0].match(reM)? s.replace(exp[0], multiply(exp[0])) : s.replace(exp[0], divide(exp[0]));
    }

    while (exp = s.match(reAS)) {
      s = exp[0].match(reA)? s.replace(exp[0], add(exp[0])) : s.replace(exp[0], subtract(exp[0]));
    }

    return '' + s;

    function multiply(s, b) {
      b = s.split('*');
      return b[0] * b[1];
    }

    function divide(s, b) {
      b = s.split('/');
      return b[0] / b[1];
    }

    function add(s, b) {
      s = s.replace(/^\+/,'').replace(/\++/,'+');
      b = s.split('+');
      return Number(b[0]) + Number(b[1]);
    }

    function subtract(s, b) {
      s = s.replace(/\+-|-\+/g,'-');

      if (s.match(/--/)) {
        return add(s.replace(/--/,'+'));
      }
      b = s.split('-');
      return b.length == 3? -1 * b[1] - b[2] : b[0] - b[1];
    }
  }
}


Arithmetic evaluation

Solution:
import operator

class AstNode(object):
   def __init__( self, opr, left, right ):
      self.opr = opr
      self.l = left
      self.r = right

   def eval(self):
      return self.opr(self.l.eval(), self.r.eval())

class LeafNode(object):
   def __init__( self, valStrg ):
      self.v = int(valStrg)

   def eval(self):
      return self.v

class Yaccer(object):
   def __init__(self):
      self.operstak = []
      self.nodestak =[]
      self.__dict__.update(self.state1)

   def v1( self, valStrg ):
      # Value String
      self.nodestak.append( LeafNode(valStrg))
      self.__dict__.update(self.state2)
      #print 'push', valStrg

   def o2( self, operchar ):
      # Operator character or open paren in state1
      def openParen(a,b):
         return 0		# function should not be called

      opDict= { '+': ( operator.add, 2, 2 ),
         '-': (operator.sub, 2, 2 ),
         '*': (operator.mul, 3, 3 ),
         '/': (operator.div, 3, 3 ),
         '^': ( pow,         4, 5 ),  # right associative exponentiation for grins
         '(': ( openParen,   0, 8 )
         }
      operPrecidence = opDict[operchar][2]
      self.redeuce(operPrecidence)

      self.operstak.append(opDict[operchar])
      self.__dict__.update(self.state1)
      # print 'pushop', operchar

   def syntaxErr(self, char ):
      # Open Parenthesis
      print 'parse error - near operator "%s"' %char

   def pc2( self,operchar ):
      # Close Parenthesis
      # reduce node until matching open paren found
      self.redeuce( 1 )
      if len(self.operstak)>0:
         self.operstak.pop()		# pop off open parenthesis
      else:
         print 'Error - no open parenthesis matches close parens.'
      self.__dict__.update(self.state2)

   def end(self):
      self.redeuce(0)
      return self.nodestak.pop()

   def redeuce(self, precidence):
      while len(self.operstak)>0:
         tailOper = self.operstak[-1]
         if tailOper[1] < precidence: break

         tailOper = self.operstak.pop()
         vrgt = self.nodestak.pop()
         vlft= self.nodestak.pop()
         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
         # print 'reduce'

   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }

def Lex( exprssn, p ):
   bgn = None
   cp = -1
   for c in exprssn:
      cp += 1
      if c in '+-/*^()':         # throw in exponentiation (^)for grins
         if bgn is not None:
            p.v(p, exprssn[bgn:cp])
            bgn = None
         if c=='(': p.po(p, c)
         elif c==')':p.pc(p, c)
         else: p.o(p, c)
      elif c in ' \t':
         if bgn is not None:
            p.v(p, exprssn[bgn:cp])
            bgn = None
      elif c in '0123456789':
         if bgn is None:
            bgn = cp
      else:
         print 'Invalid character in expression'
         if bgn is not None:
            p.v(p, exprssn[bgn:cp])
            bgn = None

   if bgn is not None:
      p.v(p, exprssn[bgn:cp+1])
      bgn = None
   return p.end()

expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()


Arithmetic numbers

;Definition
A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.

Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.

;Example
30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer.

;Task
Calculate and show here:

1. The first 100 arithmetic numbers.

2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.

3. How many of the first '''x''' arithmetic numbers are composite.

Note that, technically, the arithmetic number '''1''' is neither prime nor composite.

;Stretch
Carry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.

;References

* Wikipedia: Arithmetic number
* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer

Solution:
#include

void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
                           unsigned int* psum) {
    unsigned int divisor_count = 1;
    unsigned int divisor_sum = 1;
    unsigned int power = 2;
    for (; (n & 1) == 0; power <<= 1, n >>= 1) {
        ++divisor_count;
        divisor_sum += power;
    }
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1, sum = 1;
        for (power = p; n % p == 0; power *= p, n /= p) {
            ++count;
            sum += power;
        }
        divisor_count *= count;
        divisor_sum *= sum;
    }
    if (n > 1) {
        divisor_count *= 2;
        divisor_sum *= n + 1;
    }
    *pcount = divisor_count;
    *psum = divisor_sum;
}

int main() {
    unsigned int arithmetic_count = 0;
    unsigned int composite_count = 0;

    for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
        unsigned int divisor_count;
        unsigned int divisor_sum;
        divisor_count_and_sum(n, &divisor_count, &divisor_sum);
        if (divisor_sum % divisor_count != 0)
            continue;
        ++arithmetic_count;
        if (divisor_count > 2)
            ++composite_count;
        if (arithmetic_count <= 100) {
            printf("%3u ", n);
            if (arithmetic_count % 10 == 0)
                printf("\n");
        }
        if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
            arithmetic_count == 100000 || arithmetic_count == 1000000) {
            printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
            printf("Number of composite arithmetic numbers <= %u: %u\n", n,
                   composite_count);
        }
    }
    return 0;
}


Arithmetic numbers

Solution:
def factors(n: int):
    f = set([1, n])
    i = 2
    while True:
        j = n // i
        if j < i:
            break
        if i * j == n:
            f.add(i)
            f.add(j)
        i += 1
    return f

arithmetic_count = 0
composite_count = 0
n = 1
while arithmetic_count <= 1000000:
    f = factors(n)
    if (sum(f)/len(f)).is_integer():
        arithmetic_count += 1
        if len(f) > 2:
            composite_count += 1
        if arithmetic_count <= 100:
            print(f'{n:3d} ', end='')
            if arithmetic_count % 10 == 0:
                print()
        if arithmetic_count in (1000, 10000, 100000, 1000000):
            print(f'\n{arithmetic_count}th arithmetic number is {n}')
            print(f'Number of composite arithmetic numbers <= {n}: {composite_count}')
    n += 1


Array length

;Task:
Determine the amount of elements in an array.

As an example use an array holding the strings 'apple' and 'orange'.

Solution:
#define _CRT_SECURE_NO_WARNINGS    // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS   // enable old-gold POSIX names in MSVS

#include
#include
#include
#include
#include

struct StringArray
{
    size_t sizeOfArray;
    size_t numberOfElements;
    char** elements;
};
typedef struct StringArray* StringArray;

StringArray StringArray_new(size_t size)
{
    StringArray this = calloc(1, sizeof(struct StringArray));
    if (this)
    {
        this->elements = calloc(size, sizeof(int));
        if (this->elements)
            this->sizeOfArray = size;
        else
        {
            free(this);
            this = NULL;
        }
    }
    return this;
}

void StringArray_delete(StringArray* ptr_to_this)
{
    assert(ptr_to_this != NULL);
    StringArray this = (*ptr_to_this);
    if (this)
    {
        for (size_t i = 0; i < this->sizeOfArray; i++)
            free(this->elements[i]);
        free(this->elements);
        free(this);
        this = NULL;
    }
}

void StringArray_add(StringArray this, ...)
{
    char* s;
    va_list args;
    va_start(args, this);
    while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*)))
        this->elements[this->numberOfElements++] = strdup(s);
    va_end(args);
}

int main(int argc, char* argv[])
{
    StringArray a = StringArray_new(10);
    StringArray_add(a, "apple", "orange", NULL);

    printf(
        "There are %d elements in an array with a capacity of %d elements:\n\n",
        a->numberOfElements, a->sizeOfArray);

    for (size_t i = 0; i < a->numberOfElements; i++)
        printf("    the element %d is the string \"%s\"\n", i, a->elements[i]);

    StringArray_delete(&a);

    return EXIT_SUCCESS;
}


Array length

Solution:
function last(list, defaultValue) {
   return list.length ?list[list.length-1] :defaultValue;
}


Ascending primes

Generate and show all primes with strictly ascending decimal digits.

Aside: Try solving without peeking at existing solutions. I had a weird idea for generating
a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial
but generating them quickly is at least mildly interesting.
Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is
at least one significantly better and much faster way, needing a mere 511 odd/prime tests.

;See also
;* OEIS:A052015 - Primes with distinct digits in ascending order

;Related:
*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)
*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)

Solution:
/*
 *  Ascending primes
 *
 *  Generate and show all primes with strictly ascending decimal digits.
 *
 *
 *  Solution
 *
 *  We only consider positive numbers in the range 1 to 123456789. We would
 *  get 7027260 primes, because there are so many primes smaller than 123456789
 *  (see also Wolfram Alpha).On the other hand, there are only 511 distinct
 *  nonzero positive integers having their digits arranged in ascending order.
 *  Therefore, it is better to start with numbers that have properly arranged
 *  digitsand then check if they are prime numbers.The method of generating
 *  a sequence of such numbers is not indifferent.We want this sequence to be
 *  monotonically increasing, because then additional sorting of results will
 *  be unnecessary. It turns out that by using a queue we can easily get the
 *  desired effect. Additionally, the algorithm then does not use recursion
 *  (although the program probably does not have to comply with the MISRA
 *  standard). The problem to be solved is the queue size, the a priori
 *  assumption that 1000 is good enough, but a bit magical.
 */

#include
#include
#include
#include

#if UINT_MAX < 123456789
#error "we need at least 9 decimal digits (32-bit integers)"
#endif

#define MAXSIZE 1000

unsigned queue[MAXSIZE];
unsigned primes[MAXSIZE];

unsigned begin = 0;
unsigned end = 0;
unsigned n = 0;

bool isPrime(unsigned n)
{
    if (n == 2)
    {
        return true;
    }
    if (n == 1 || n % 2 == 0)
    {
        return false;
    }
    unsigned root = sqrt(n);
    for (unsigned k = 3; k <= root; k += 2)
    {
        if (n % k == 0)
        {
            return false;
        }
    }
    return true;
}

int main(int argc, char argv[])
{
    for (int k = 1; k <= 9; k++)
    {
        queue[end++] = k;
    }

    while (begin < end)
    {
        int value = queue[begin++];
        if (isPrime(value))
        {
            primes[n++] = value;
        }
        for (int k = value % 10 + 1; k <= 9; k++)
        {
            queue[end++] = value * 10 + k;
        }
    }

    for (int k = 0; k < n; k++)
    {
        printf("%u ", primes[k]);
    }

    return EXIT_SUCCESS;
}


Ascending primes

Solution: No script, no fun. Turn on Javascript on.


Ascending primes

Solution:
from sympy import isprime

def ascending(x=0):
    for y in range(x*10 + (x%10) + 1, x*10 + 10):
        yield from ascending(y)
        yield(y)

print(sorted(x for x in ascending() if isprime(x)))


Associative array/Merging

;Task:
Define two associative arrays, where one represents the following "base" data:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 12.75
|-
| "color" || "yellow"
|}

And the other represents "update" data:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}

Merge these into a new associative array that contains every key found in either of the source ones.  Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table.  If possible, do this in a way that does not mutate the original two associative arrays.  Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}

Solution:
(() => {
    'use strict';

    console.log(JSON.stringify(
        Object.assign({}, // Fresh dictionary.
            { // Base.
                "name": "Rocket Skates",
                "price": 12.75,
                "color": "yellow"
            }, { // Update.
                "price": 15.25,
                "color": "red",
                "year": 1974
            }
        ),
        null, 2
    ))
})();


Associative array/Merging

Solution: As of Python 3.5, this can be solved with the dictionary unpacking operator.


Associative array/Merging

Solution:
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}

result = {**base, **update}

print(result)


Attractive numbers

A number is an   ''attractive number''   if the number of its prime factors (whether distinct or not) is also prime.

;Example:
The number   '''20''',   whose prime decomposition is   '''2 × 2 × 5''',   is an   ''attractive number''   because the number of its prime factors   ('''3''')   is also prime.

;Task:
Show sequence items up to   '''120'''.

;Reference:
:*   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.

Solution:
#include

#define TRUE 1
#define FALSE 0
#define MAX 120

typedef int bool;

bool is_prime(int n) {
    int d = 5;
    if (n < 2) return FALSE;
    if (!(n % 2)) return n == 2;
    if (!(n % 3)) return n == 3;
    while (d *d <= n) {
        if (!(n % d)) return FALSE;
        d += 2;
        if (!(n % d)) return FALSE;
        d += 4;
    }
    return TRUE;
}

int count_prime_factors(int n) {
    int count = 0, f = 2;
    if (n == 1) return 0;
    if (is_prime(n)) return 1;
    while (TRUE) {
        if (!(n % f)) {
            count++;
            n /= f;
            if (n == 1) return count;
            if (is_prime(n)) f = n;
        }
        else if (f >= 3) f += 2;
        else f = 3;
    }
}

int main() {
    int i, n, count = 0;
    printf("The attractive numbers up to and including %d are:\n", MAX);
    for (i = 1; i <= MAX; ++i) {
        n = count_prime_factors(i);
        if (is_prime(n)) {
            printf("%4d", i);
            if (!(++count % 20)) printf("\n");
        }
    }
    printf("\n");
    return 0;
}


Attractive numbers

Solution:
(() => {
    'use strict';

    // attractiveNumbers :: () -> Gen [Int]
    const attractiveNumbers = () =>
        // An infinite series of attractive numbers.
        filter(
            compose(isPrime, length, primeFactors)
        )(enumFrom(1));

    // ----------------------- TEST -----------------------
    // main :: IO ()
    const main = () =>
        showCols(10)(
            takeWhile(ge(120))(
                attractiveNumbers()
            )
        );

    // ---------------------- PRIMES ----------------------

    // isPrime :: Int -> Bool
    const isPrime = n => {
        // True if n is prime.
        if (2 === n || 3 === n) {
            return true
        }
        if (2 > n || 0 === n % 2) {
            return false
        }
        if (9 > n) {
            return true
        }
        if (0 === n % 3) {
            return false
        }
        return !enumFromThenTo(5)(11)(
            1 + Math.floor(Math.pow(n, 0.5))
        ).some(x => 0 === n % x || 0 === n % (2 + x));
    };

    // primeFactors :: Int -> [Int]
    const primeFactors = n => {
        // A list of the prime factors of n.
        const
            go = x => {
                const
                    root = Math.floor(Math.sqrt(x)),
                    m = until(
                        ([q, _]) => (root < q) || (0 === (x % q))
                    )(
                        ([_, r]) => [step(r), 1 + r]
                    )([
                        0 === x % 2 ? (
                            2
                        ) : 3,
                        1
                    ])[0];
                return m > root ? (
                    [x]
                ) : ([m].concat(go(Math.floor(x / m))));
            },
            step = x => 1 + (x << 2) - ((x >> 1) << 1);
        return go(n);
    };

    // ---------------- GENERIC FUNCTIONS -----------------

    // chunksOf :: Int -> [a] -> [[a]]
    const chunksOf = n =>
        xs => enumFromThenTo(0)(n)(
            xs.length - 1
        ).reduce(
            (a, i) => a.concat([xs.slice(i, (n + i))]),
            []
        );

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => x
        );

    // enumFrom :: Enum a => a -> [a]
    function* enumFrom(x) {
        // A non-finite succession of enumerable
        // values, starting with the value x.
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // enumFromThenTo :: Int -> Int -> Int -> [Int]
    const enumFromThenTo = x1 =>
        x2 => y => {
            const d = x2 - x1;
            return Array.from({
                length: Math.floor(y - x2) / d + 2
            }, (_, i) => x1 + (d * i));
        };

    // filter :: (a -> Bool) -> Gen [a] -> [a]
    const filter = p => xs => {
        function* go() {
            let x = xs.next();
            while (!x.done) {
                let v = x.value;
                if (p(v)) {
                    yield v
                }
                x = xs.next();
            }
        }
        return go(xs);
    };

    // ge :: Ord a => a -> a -> Bool
    const ge = x =>
        // True if x >= y
        y => x >= y;

    // justifyRight :: Int -> Char -> String -> String
    const justifyRight = n =>
        // The string s, preceded by enough padding (with
        // the character c) to reach the string length n.
        c => s => n > s.length ? (
            s.padStart(n, c)
        ) : s;

    // last :: [a] -> a
    const last = xs =>
        // The last item of a list.
        0 < xs.length ? xs.slice(-1)[0] : undefined;

    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite
        // length. This enables zip and zipWith to choose
        // the shorter argument when one is non-finite,
        // like cycle, repeat etc
        (Array.isArray(xs) || 'string' === typeof xs) ? (
            xs.length
        ) : Infinity;

    // map :: (a -> b) -> [a] -> [b]
    const map = f =>
        // The list obtained by applying f
        // to each element of xs.
        // (The image of xs under f).
        xs => (
            Array.isArray(xs) ? (
                xs
            ) : xs.split('')
        ).map(f);

    // showCols :: Int -> [a] -> String
    const showCols = w => xs => {
        const
            ys = xs.map(str),
            mx = last(ys).length;
        return unlines(chunksOf(w)(ys).map(
            row => row.map(justifyRight(mx)(' ')).join(' ')
        ))
    };

    // str :: a -> String
    const str = x =>
        x.toString();

    // takeWhile :: (a -> Bool) -> Gen [a] -> [a]
    const takeWhile = p => xs => {
        const ys = [];
        let
            nxt = xs.next(),
            v = nxt.value;
        while (!nxt.done && p(v)) {
            ys.push(v);
            nxt = xs.next();
            v = nxt.value
        }
        return ys;
    };

    // unlines :: [String] -> String
    const unlines = xs =>
        // A single string formed by the intercalation
        // of a list of strings with the newline character.
        xs.join('\n');

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = p => f => x => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

    // MAIN ---
    return main();
})();


Attractive numbers

Solution:
from sympy import sieve # library for primes

def get_pfct(n):
	i = 2; factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return len(factors)

sieve.extend(110) # first 110 primes...
primes=sieve._list

pool=[]

for each in xrange(0,121):
	pool.append(get_pfct(each))

for i,each in enumerate(pool):
	if each in primes:
		print i,


Average loop length

Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.

;Task:
Write a program or a script that estimates, for each N, the average length until the first such repetition.

Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.

This problem comes from the end of Donald Knuth's [http://www.youtube.com/watch?v=cI6tt9QfRdo Christmas tree lecture 2011].

Example of expected output:

 N    average    analytical    (error)
===  =========  ============  =========
  1     1.0000        1.0000  (  0.00%)
  2     1.4992        1.5000  (  0.05%)
  3     1.8784        1.8889  (  0.56%)
  4     2.2316        2.2188  (  0.58%)
  5     2.4982        2.5104  (  0.49%)
  6     2.7897        2.7747  (  0.54%)
  7     3.0153        3.0181  (  0.09%)
  8     3.2429        3.2450  (  0.07%)
  9     3.4536        3.4583  (  0.14%)
 10     3.6649        3.6602  (  0.13%)
 11     3.8091        3.8524  (  1.12%)
 12     3.9986        4.0361  (  0.93%)
 13     4.2074        4.2123  (  0.12%)
 14     4.3711        4.3820  (  0.25%)
 15     4.5275        4.5458  (  0.40%)
 16     4.6755        4.7043  (  0.61%)
 17     4.8877        4.8579  (  0.61%)
 18     4.9951        5.0071  (  0.24%)
 19     5.1312        5.1522  (  0.41%)
 20     5.2699        5.2936  (  0.45%)

Solution:
#include
#include
#include
#include

#define MAX_N 20
#define TIMES 1000000

double factorial(int n) {
	double f = 1;
	int i;
	for (i = 1; i <= n; i++) f *= i;
	return f;
}

double expected(int n) {
	double sum = 0;
	int i;
	for (i = 1; i <= n; i++)
		sum += factorial(n) / pow(n, i) / factorial(n - i);
	return sum;
}

int randint(int n) {
	int r, rmax = RAND_MAX / n * n;
	while ((r = rand()) >= rmax);
	return r / (RAND_MAX / n);
}

int test(int n, int times) {
	int i, count = 0;
	for (i = 0; i < times; i++) {
		int x = 1, bits = 0;
		while (!(bits & x)) {
			count++;
			bits |= x;
			x = 1 << randint(n);
		}
	}
	return count;
}

int main(void) {
	srand(time(0));
	puts(" n\tavg\texp.\tdiff\n-------------------------------");

	int n;
	for (n = 1; n <= MAX_N; n++) {
		int cnt = test(n, TIMES);
		double avg = (double)cnt / TIMES;
		double theory = expected(n);
		double diff = (avg / theory - 1) * 100;
		printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
	}
	return 0;
}


Average loop length

Solution:
from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange

MAX_N = 20
TIMES = 1000000

def analytical(n):
	return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))

def test(n, times):
    count = 0
    for i in range(times):
        x, bits = 1, 0
        while not (bits & x):
            count += 1
            bits |= x
            x = 1 << randrange(n)
    return count / times

if __name__ == '__main__':
    print(" n\tavg\texp.\tdiff\n-------------------------------")
    for n in range(1, MAX_N+1):
        avg = test(n, TIMES)
        theory = analytical(n)
        diff = (avg / theory - 1) * 100
        print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))