Evolutionary algorithm

Starting with:
* The target string: "METHINKS IT IS LIKE A WEASEL".
* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
* A fitness function that computes the ‘closeness’ of its argument to the target string.
* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
:* repeat until the parent converges, (hopefully), to the target.

;See also:
*   Wikipedia entry:   Weasel algorithm.
*   Wikipedia entry:   Evolutionary algorithm.

Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions

A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.

Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"

 (:* repeat until the parent converges, (hopefully), to the target.

Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!

As illustration of this error, the code for 8th has the following remark.

 Create a new string based on the TOS, '''changing randomly any characters which
 don't already match the target''':

''NOTE:'' this has been changed, the 8th version is completely random now

Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!

To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.

Solution:
#include
#include
#include

const char target[] = "METHINKS IT IS LIKE A WEASEL";
const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";

#define CHOICE (sizeof(tbl) - 1)
#define MUTATE 15
#define COPIES 30

/* returns random integer from 0 to n - 1 */
int irand(int n)
{
	int r, rand_max = RAND_MAX - (RAND_MAX % n);
	while((r = rand()) >= rand_max);
	return r / (rand_max / n);
}

/* number of different chars between a and b */
int unfitness(const char *a, const char *b)
{
	int i, sum = 0;
	for (i = 0; a[i]; i++)
		sum += (a[i] != b[i]);
	return sum;
}

/* each char of b has 1/MUTATE chance of differing from a */
void mutate(const char *a, char *b)
{
	int i;
	for (i = 0; a[i]; i++)
		b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];

	b[i] = '\0';
}

int main()
{
	int i, best_i, unfit, best, iters = 0;
	char specimen[COPIES][sizeof(target) / sizeof(char)];

	/* init rand string */
	for (i = 0; target[i]; i++)
		specimen[0][i] = tbl[irand(CHOICE)];
	specimen[0][i] = 0;

	do {
		for (i = 1; i < COPIES; i++)
			mutate(specimen[0], specimen[i]);

		/* find best fitting string */
		for (best_i = i = 0; i < COPIES; i++) {
			unfit = unfitness(target, specimen[i]);
			if(unfit < best || !i) {
				best = unfit;
				best_i = i;
			}
		}

		if (best_i) strcpy(specimen[0], specimen[best_i]);
		printf("iter %d, score %d: %s\n", iters++, best, specimen[0]);
	} while (best);

	return 0;
}


Evolutionary algorithm

Solution:
// ------------------------------------- Cross-browser Compatibility -------------------------------------

/* Compatibility code to reduce an array
 * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
 */
if (!Array.prototype.reduce) {
    Array.prototype.reduce = function (fun /*, initialValue */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function") throw new TypeError();

        // no value to return if no initial value and an empty array
        if (len == 0 && arguments.length == 1) throw new TypeError();

        var k = 0;
        var accumulator;
        if (arguments.length >= 2) {
            accumulator = arguments[1];
        } else {
            do {
                if (k in t) {
                    accumulator = t[k++];
                    break;
                }

                // if array contains no values, no initial value to return
                if (++k >= len) throw new TypeError();
            }
            while (true);
        }

        while (k < len) {
            if (k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t);
            k++;
        }

        return accumulator;
    };
}

/* Compatibility code to map an array
 * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Map
 */
if (!Array.prototype.map) {
    Array.prototype.map = function (fun /*, thisp */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function") throw new TypeError();

        var res = new Array(len);
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in t) res[i] = fun.call(thisp, t[i], i, t);
        }

        return res;
    };
}

/* ------------------------------------- Generator -------------------------------------
 * Generates a fixed length gene sequence via a gene strategy object.
 * The gene strategy object must have two functions:
 *	- "create": returns create a new gene
 *	- "mutate(existingGene)": returns mutation of an existing gene
 */
function Generator(length, mutationRate, geneStrategy) {
    this.size = length;
    this.mutationRate = mutationRate;
    this.geneStrategy = geneStrategy;
}

Generator.prototype.spawn = function () {
    var genes = [],
        x;
    for (x = 0; x < this.size; x += 1) {
        genes.push(this.geneStrategy.create());
    }
    return genes;
};

Generator.prototype.mutate = function (parent) {
    return parent.map(function (char) {
        if (Math.random() > this.mutationRate) {
            return char;
        }
        return this.geneStrategy.mutate(char);
    }, this);
};

/* ------------------------------------- Population -------------------------------------
 * Helper class that holds and spawns a new population.
 */
function Population(size, generator) {
    this.size = size;
    this.generator = generator;

    this.population = [];
    // Build initial popuation;
    for (var x = 0; x < this.size; x += 1) {
        this.population.push(this.generator.spawn());
    }
}

Population.prototype.spawn = function (parent) {
    this.population = [];
    for (var x = 0; x < this.size; x += 1) {
        this.population.push(this.generator.mutate(parent));
    }
};

/* ------------------------------------- Evolver -------------------------------------
 * Attempts to converge a population based a fitness strategy object.
 * The fitness strategy object must have three function
 *	- "score(individual)": returns a score for an individual.
 *	- "compare(scoreA, scoreB)": return true if scoreA is better (ie more fit) then scoreB
 *	- "done( score )": return true if score is acceptable (ie we have successfully converged).
 */
function Evolver(size, generator, fitness) {
    this.done = false;
    this.fitness = fitness;
    this.population = new Population(size, generator);
}

Evolver.prototype.getFittest = function () {
    return this.population.population.reduce(function (best, individual) {
        var currentScore = this.fitness.score(individual);
        if (best === null || this.fitness.compare(currentScore, best.score)) {
            return {
                score: currentScore,
                individual: individual
            };
        } else {
            return best;
        }
    }, null);
};

Evolver.prototype.doGeneration = function () {
    this.fittest = this.getFittest();
    this.done = this.fitness.done(this.fittest.score);
    if (!this.done) {
        this.population.spawn(this.fittest.individual);
    }
};

Evolver.prototype.run = function (onCheckpoint, checkPointFrequency) {
    checkPointFrequency = checkPointFrequency || 10; // Default to Checkpoints every 10 generations
    var generation = 0;
    while (!this.done) {
        this.doGeneration();
        if (generation % checkPointFrequency === 0) {
            onCheckpoint(generation, this.fittest);
        }
        generation += 1;
    }
    onCheckpoint(generation, this.fittest);
    return this.fittest;
};

// ------------------------------------- Exports -------------------------------------
window.Generator = Generator;
window.Evolver = Evolver;

// helper utitlity to combine elements of two arrays.
Array.prototype.zip = function (b, func) {
    var result = [],
        max = Math.max(this.length, b.length),
        x;
    for (x = 0; x < max; x += 1) {
        result.push(func(this[x], b[x]));
    }
    return result;
};

var target = "METHINKS IT IS LIKE A WEASEL", geneStrategy, fitness, target, generator, evolver, result;

geneStrategy = {
    // The allowed character set (as an array)
    characterSet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".split(""),

    /*
        Pick a random character from the characterSet
    */
    create: function getRandomGene() {
        var randomNumber = Math.floor(Math.random() * this.characterSet.length);
        return this.characterSet[randomNumber];
    }
};
geneStrategy.mutate = geneStrategy.create; // Our mutation stragtegy is to simply get a random gene
fitness = {
    // The target (as an array of characters)
    target: target.split(""),
    equal: function (geneA, geneB) {
        return (geneA === geneB ? 0 : 1);
    },
    sum: function (runningTotal, value) {
        return runningTotal + value;
    },

    /*
        We give one point to for each corect letter
    */
    score: function (genes) {
        var diff = genes.zip(this.target, this.equal); // create an array of ones and zeros
        return diff.reduce(this.sum, 0); // Sum the array values together.
    },
    compare: function (scoreA, scoreB) {
        return scoreA <= scoreB; // Lower scores are better
    },
    done: function (score) {
        return score === 0; // We have matched the target string.
    }
};

generator = new Generator(target.length, 0.05, geneStrategy);
evolver = new Evolver(100, generator, fitness);

function showProgress(generation, fittest) {
    document.write("Generation: " + generation + ", Best: " + fittest.individual.join("") + ", fitness:" + fittest.score + "");
}
result = evolver.run(showProgress);


Evolutionary algorithm

Solution:
from string import letters
from random import choice, random

target  = list("METHINKS IT IS LIKE A WEASEL")
charset = letters + ' '
parent  = [choice(charset) for _ in range(len(target))]
minmutaterate  = .09
C = range(100)

perfectfitness = float(len(target))

def fitness(trial):
    'Sum of matching chars by position'
    return sum(t==h for t,h in zip(trial, target))

def mutaterate():
    'Less mutation the closer the fit of the parent'
    return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate))

def mutate(parent, rate):
    return [(ch if random() <= rate else choice(charset)) for ch in parent]

def que():
    '(from the favourite saying of Manuel in Fawlty Towers)'
    print ("#%-4i, fitness: %4.1f%%, '%s'" %
           (iterations, fitness(parent)*100./perfectfitness, ''.join(parent)))

def mate(a, b):
    place = 0
    if choice(xrange(10)) < 7:
        place = choice(xrange(len(target)))
    else:
        return a, b

    return a, b, a[:place] + b[place:], b[:place] + a[place:]

iterations = 0
center = len(C)/2
while parent != target:
    rate = mutaterate()
    iterations += 1
    if iterations % 100 == 0: que()
    copies = [ mutate(parent, rate) for _ in C ]  + [parent]
    parent1 = max(copies[:center], key=fitness)
    parent2 = max(copies[center:], key=fitness)
    parent = max(mate(parent1, parent2), key=fitness)
que()


Executable library

The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.

'''Task detail'''

* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.

* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:
:: 2.  Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
:: 3.  Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.

* Create a second executable to calculate the following:
** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.

* Explain any extra setup/run steps needed to complete the task.

'''Notes:'''
* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.
* Interpreters are present in the runtime environment.

Solution:
#include
#include

long hailstone(long n, long **seq)
{
        long len = 0, buf_len = 4;
        if (seq)
                *seq = malloc(sizeof(long) * buf_len);

        while (1) {
                if (seq) {
                        if (len >= buf_len) {
                                buf_len *= 2;
                                *seq = realloc(*seq, sizeof(long) * buf_len);
                        }
                        (*seq)[len] = n;
                }
                len ++;
                if (n == 1) break;
                if (n & 1) n = 3 * n + 1;
                else n >>= 1;
        }
        return len;
}

void free_sequence(long * s) { free(s); }

const char my_interp[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2";
/* "ld-linux.so.2" should be whatever you use on your platform */

int hail_main() /* entry point when running along, see compiler command line */
{
        long i, *seq;

        long len = hailstone(27, &seq);
        printf("27 has %ld numbers in sequence:\n", len);
        for (i = 0; i < len; i++) {
                printf("%ld ", seq[i]);
        }
        printf("\n");
        free_sequence(seq);

        exit(0);
}


Executable library

Solution:
from collections import Counter

def function_length_frequency(func, hrange):
    return Counter(len(func(n)) for n in hrange).most_common()

if __name__ == '__main__':
    from executable_hailstone_library import hailstone

    upto = 100000
    hlen, freq = function_length_frequency(hailstone, range(1, upto))[0]
    print("The length of hailstone sequence that is most common for\n"
          "hailstone(n) where 1<=n<%i, is %i. It occurs %i times."
          % (upto, hlen, freq))


Execute Computer/Zero

;Task:
Create a [[Computer/zero Assembly]] emulator. You may consider [http://edmundgriffiths.com/czero.html this webpage] as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.

:*   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.
:*   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.

;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.

Solution:
"""Computer/zero Assembly emulator. Requires Python >= 3.7"""

import re

from typing import Dict
from typing import Iterable
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Tuple

NOP = 0b000
LDA = 0b001
STA = 0b010
ADD = 0b011
SUB = 0b100
BRZ = 0b101
JMP = 0b110
STP = 0b111

OPCODES = {
    "NOP": NOP,
    "LDA": LDA,
    "STA": STA,
    "ADD": ADD,
    "SUB": SUB,
    "BRZ": BRZ,
    "JMP": JMP,
    "STP": STP,
}

RE_INSTRUCTION = re.compile(
    r"\s*"
    r"(?:(?P\w+):)?"
    r"\s*"
    rf"(?P{'|'.join(OPCODES)})?"
    r"\s*"
    r"(?P\w+)?"
    r"\s*"
    r"(?:;(?P[\w\s]+))?"
)

class AssemblySyntaxError(Exception):
    pass

class Instruction(NamedTuple):
    label: Optional[str]
    opcode: Optional[str]
    argument: Optional[str]
    comment: Optional[str]

def parse(assembly: str) -> Tuple[List[Instruction], Dict[str, int]]:
    instructions: List[Instruction] = []
    labels: Dict[str, int] = {}
    linenum: int = 0

    for line in assembly.split("\n"):
        match = RE_INSTRUCTION.match(line)

        if not match:
            raise AssemblySyntaxError(f"{line}: {linenum}")

        instructions.append(Instruction(**match.groupdict()))
        label = match.group(1)
        if label:
            labels[label] = linenum

        linenum += 1

    return instructions, labels

def compile(instructions: List[Instruction], labels: Dict[str, int]) -> Iterable[int]:
    for instruction in instructions:
        if instruction.argument is None:
            argument = 0
        elif instruction.argument.isnumeric():
            argument = int(instruction.argument)
        else:
            argument = labels[instruction.argument]

        if instruction.opcode:
            yield OPCODES[instruction.opcode] << 5 | argument
        else:
            yield argument

def run(bytecode: bytes) -> int:
    accumulator = 0
    program_counter = 0
    memory = list(bytecode)[:32] + [0 for _ in range(32 - len(bytecode))]

    while program_counter < 32:
        operation = memory[program_counter] >> 5
        argument = memory[program_counter] & 0b11111
        program_counter += 1

        if operation == NOP:
            continue
        elif operation == LDA:
            accumulator = memory[argument]
        elif operation == STA:
            memory[argument] = accumulator
        elif operation == ADD:
            accumulator = (accumulator + memory[argument]) % 256
        elif operation == SUB:
            accumulator = (accumulator - memory[argument]) % 256
        elif operation == BRZ:
            if accumulator == 0:
                program_counter = argument
        elif operation == JMP:
            program_counter = argument
        elif operation == STP:
            break
        else:
            raise Exception(f"error: {operation} {argument}")

    return accumulator

SAMPLES = [
    """\
            LDA   x
            ADD   y       ; accumulator = x + y
            STP
    x:            2
    y:            2
    """,
    """\
    loop:   LDA   prodt
            ADD   x
            STA   prodt
            LDA   y
            SUB   one
            STA   y
            BRZ   done
            JMP   loop
    done:   LDA   prodt   ; to display it
            STP
    x:            8
    y:            7
    prodt:        0
    one:          1
    """,
    """\
    loop:   LDA   n
            STA   temp
            ADD   m
            STA   n
            LDA   temp
            STA   m
            LDA   count
            SUB   one
            BRZ   done
            STA   count
            JMP   loop
    done:   LDA   n       ; to display it
            STP
    m:            1
    n:            1
    temp:         0
    count:        8       ; valid range: 1-11
    one:          1
    """,
    """\
    start:  LDA   load
            ADD   car     ; head of list
            STA   ldcar
            ADD   one
            STA   ldcdr   ; next CONS cell
    ldcar:  NOP
            STA   value
    ldcdr:  NOP
            BRZ   done    ; 0 stands for NIL
            STA   car
            JMP   start
    done:   LDA   value   ; CAR of last CONS
            STP
    load:   LDA   0
    value:        0
    car:          28
    one:          1
                        ; order of CONS cells
                        ; in memory
                        ; does not matter
                6
                0       ; 0 stands for NIL
                2       ; (CADR ls)
                26      ; (CDDR ls) -- etc.
                5
                20
                3
                30
                1       ; value of (CAR ls)
                22      ; points to (CDR ls)
                4
                24
    """,
    """\
    p:            0       ; NOP in first round
    c:            0
    start:  STP           ; wait for p's move
    pmove:  NOP
            LDA   pmove
            SUB   cmove
            BRZ   same
            LDA   pmove
            STA   cmove   ; tit for tat
            BRZ   cdeft
            LDA   c       ; p defected, c did not
            ADD   three
            STA   c
            JMP   start
    cdeft:  LDA   p
            ADD   three
            STA   p
            JMP   start
    same:   LDA   pmove
            STA   cmove   ; tit for tat
            LDA   p
            ADD   one
            ADD   pmove
            STA   p
            LDA   c
            ADD   one
            ADD   pmove
            STA   c
            JMP   start
    cmove:        0       ; co-operate initially
    one:          1
    three:        3
    """,
    """\
    LDA  3
    SUB  4
    STP  0
         0
         255
    """,
    """\
    LDA  3
    SUB  4
    STP  0
         0
         1
    """,
    """\
    LDA  3
    ADD  4
    STP  0
         1
         255
    """,
]

def main() -> None:
    for sample in SAMPLES:
        instructions, labels = parse(sample)
        bytecode = bytes(compile(instructions, labels))
        result = run(bytecode)
        print(result)

if __name__ == "__main__":
    main()


Execute HQ9+

;Task:
Implement a   ''' [[HQ9+]] '''   interpreter or compiler.

Solution:
void runCode(const char *code)
{
    int c_len = strlen(code);
    int i, bottles;
    unsigned accumulator=0;
    for(i=0;i 0 );
                break;

            case '+':
                //Am I the only one finding this one weird? :o
                accumulator++;
                break;
        }
    }
};


Execute HQ9+

Solution:
function hq9plus(code) {
  var out = '';
  var acc = 0;

  for (var i=0; i1; j--) {
          out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n";
          out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n";
        }
        out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
            "Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
            "No more bottles of beer on the wall, no more bottles of beer.\n" +
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n";
        break;
      case '+': acc++; break;
    }
  }
  return out;
}


Execute SNUSP

An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.

Solution:
#!/usr/bin/env python3

HW = r'''
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
      \==-<<<<+>+++/ /=.>.+>.--------.-/'''

def snusp(store, code):
    ds = bytearray(store)  # data store
    dp = 0                 # data pointer
    cs = code.splitlines() # 2 dimensional code store
    ipr, ipc = 0, 0        # instruction pointers in row and column
    for r, row in enumerate(cs):
        try:
            ipc = row.index('$')
            ipr = r
            break
        except ValueError:
            pass
    rt, dn, lt, up = range(4)
    id = rt  # instruction direction.  starting direction is always rt
    def step():
        nonlocal ipr, ipc
        if id&1:
            ipr += 1 - (id&2)
        else:
            ipc += 1 - (id&2)
    while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]):
        op = cs[ipr][ipc]
        if op == '>':
            dp += 1
        elif op == '<':
            dp -= 1
        elif op == '+':
            ds[dp] += 1
        elif op == '-':
            ds[dp] -= 1
        elif op == '.':
            print(chr(ds[dp]), end='')
        elif op == ',':
            ds[dp] = input()
        elif op == '/':
            id = ~id
        elif op == '\\':
            id ^= 1
        elif op == '!':
            step()
        elif op == '?':
            if not ds[dp]:
                step()
        step()

if __name__ == '__main__':
    snusp(5, HW)


Exponentiation order

This task will demonstrate the order of exponentiation   ('''xy''')    when there are multiple exponents.

(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of  **, ^, ↑  or some such for exponentiation.)

;Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).

If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.

Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):

::::*   5**3**2
::::*   (5**3)**2
::::*   5**(3**2)

If there are other methods (or formats) of multiple exponentiations, show them as well.

;See also:
* MathWorld entry:   [http://mathworld.wolfram.com/Exponentiation.html exponentiation]

;Related tasks:
*   exponentiation operator
*   arbitrary-precision integers (included)
*   [[Exponentiation with infix operators in (or operating on) the base]]

Solution:
#include
#include

int main()
{
    printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2));
    printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2)));

    return 0;
}


Exponentiation order

Solution:
>>> 5**3**2
1953125
>>> (5**3)**2
15625
>>> 5**(3**2)
1953125
>>> # The following is not normally done
>>> try: from functools import reduce # Py3K
except: pass

>>> reduce(pow, (5, 3, 2))
15625
>>>


Exponentiation with infix operators in (or operating on) the base

(Many programming languages,   especially those with extended─precision integer arithmetic,   usually
support one of  **, ^, ↑  or some such for exponentiation.)

Some languages treat/honor infix operators when performing exponentiation   (raising
numbers to some power by the language's exponentiation operator,   if the computer
programming language has one).

Other programming languages may make use of the   '''POW'''   or some other BIF
  ('''B'''uilt─'''I'''n '''F'''function),   or some other library service.

If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.

This task will deal with the case where there is some form of an   ''infix operator''   operating
in   (or operating on)   the base.

;Example:
A negative five raised to the 3rd power could be specified as:
    -5  ** 3          or as
   -(5) ** 3          or as
   (-5) ** 3          or as something else

(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).

;Task:
:*   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
:*   Raise the following numbers   (integer or real):
:::*   -5     and
:::*   +5
:*   to the following powers:
:::*   2nd     and
:::*   3rd
:*   using the following expressions   (if applicable in your language):
:::*   -x**p
:::*   -(x)**p
:::*   (-x)**p
:::*   -(x**p)
:*   Show here (on this page) the four (or more) types of symbolic expressions for each number and power.

Try to present the results in the same format/manner as the other programming entries to make any differences apparent.

The variables may be of any type(s) that is/are applicable in your language.

;Related tasks:
*   [[Exponentiation order]]
*   [[Exponentiation operator]]
*   [[Arbitrary-precision integers (included)]]
*   [[Parsing/RPN to infix conversion]]
*   [[Operator precedence]]

;References:
* Wikipedia: Order of operations in Programming languages

Solution:
from itertools import product

xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()

print('Integer variable exponentiation')
for x, p in product(xx, pp):
    print(f'  x,p = {x:2},{p}; ', end=' ')
    x, p = int(x), int(p)
    print('; '.join(f"{t} =={eval(t):4}" for t in texts))

print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
    texts2 = [t.replace(X, x).replace(P, p) for t in texts]
    print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))


Extend your language

Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.

If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:

Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:

   if (condition1isTrue) {
      if (condition2isTrue)
         bothConditionsAreTrue();
      else
         firstConditionIsTrue();
   }
   else if (condition2isTrue)
      secondConditionIsTrue();
   else
      noConditionIsTrue();

Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.

This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:

   if2 (condition1isTrue) (condition2isTrue)
      bothConditionsAreTrue();
   else1
      firstConditionIsTrue();
   else2
      secondConditionIsTrue();
   else
      noConditionIsTrue();

Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.

Solution:
#include

#define if2(a, b) switch(((a)) + ((b)) * 2) { case 3:
#define else00	break; case 0:	/* both false */
#define else10	break; case 1:	/* true, false */
#define else01	break; case 2:	/* false, true */
#define else2	break; default: /* anything not metioned */
#define fi2	}		/* stupid end bracket */

int main()
{
	int i, j;
	for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) {
		printf("%d %d: ", i, j);
		if2 (i == 1, j == 1)
			printf("both\n");
		else10
			printf("left\n");
		else01
			printf("right\n");
		else00 { /* <-- bracket is optional, flaw */,
			printf("neither\n");
			if2 (i == 2, j == 2)
				printf("\tis 22");
				printf("\n"); /* flaw: this is part of if2! */
			else2
				printf("\tnot 22\n");
			fi2
		}
		fi2
	}

	return 0;
}


Extend your language

Solution:
a, b = 1, 0

if (c1 := a == 1) and (c2 := b == 3):
  print('a = 1 and b = 3')
elif c1:
  print('a = 1 and b <> 3')
elif c2:
  print('a <> 1 and b = 3')
else:
  print('a <> 1 and b <> 3')


Extreme floating point values

The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.

The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.

Print the values of these variables if possible; and show some arithmetic with these values and variables.

If your language can directly enter these extreme floating point values then show it.

;See also:
*   [https://www.validlab.com/goldberg/paper.pdf What Every Computer Scientist Should Know About Floating-Point Arithmetic]

;Related tasks:
*   [[Infinity]]
*   [[Detect division by zero]]
*   [[Literals/Floating point]]

Solution:
Note: Under the C standard, division by zero (of any type) is undefined behavior.

: The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

: -- C99 standard, section 6.5.5 paragraph 5

Floating-point division by zero in the following examples to obtain infinity or NaN are dependent on implementation-specific behavior.


Extreme floating point values

Solution:
#include

int main()
{
    double inf = 1/0.0;
    double minus_inf = -1/0.0;
    double minus_zero = -1/ inf ;
    double nan = 0.0/0.0;

    printf("positive infinity: %f\n",inf);
    printf("negative infinity: %f\n",minus_inf);
    printf("negative zero: %f\n",minus_zero);
    printf("not a number: %f\n",nan);

    /* some arithmetic */

    printf("+inf + 2.0 = %f\n",inf + 2.0);
    printf("+inf - 10.1 = %f\n",inf - 10.1);
    printf("+inf + -inf = %f\n",inf + minus_inf);
    printf("0.0 * +inf = %f\n",0.0 * inf);
    printf("1.0/-0.0 = %f\n",1.0/minus_zero);
    printf("NaN + 1.0 = %f\n",nan + 1.0);
    printf("NaN + NaN = %f\n",nan + nan);

    /* some comparisons */

    printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
    printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");

    return 0;
}


Extreme floating point values

Solution:
>>> # Extreme values from expressions
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> # Print
>>> for value in (inf, _inf, _zero, nan): print (value)

inf
-inf
-0.0
nan
>>> # Extreme values from other means
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>> # Some arithmetic
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan


FASTA format

In FASTA.

A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.

;Task:
Write a program that reads a FASTA file such as:

>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED

Solution:
#include
#include
#include

void main()
{
	FILE * fp;
	char * line = NULL;
	size_t len = 0;
	ssize_t read;

	fp = fopen("fasta.txt", "r");
	if (fp == NULL)
		exit(EXIT_FAILURE);

	int state = 0;
	while ((read = getline(&line, &len, fp)) != -1) {
		/* Delete trailing newline */
		if (line[read - 1] == '\n')
			line[read - 1] = 0;
		/* Handle comment lines*/
		if (line[0] == '>') {
			if (state == 1)
				printf("\n");
			printf("%s: ", line+1);
			state = 1;
		} else {
			/* Print everything else */
			printf("%s", line);
		}
	}
	printf("\n");

	fclose(fp);
	if (line)
		free(line);
	exit(EXIT_SUCCESS);
}


FASTA format

Solution:
const fs = require("fs");
const readline = require("readline");

const args = process.argv.slice(2);
if (!args.length) {
    console.error("must supply file name");
    process.exit(1);
}

const fname = args[0];

const readInterface = readline.createInterface({
    input: fs.createReadStream(fname),
    console: false,
});

let sep = "";
readInterface.on("line", (line) => {
    if (line.startsWith(">")) {
        process.stdout.write(sep);
        sep = "\n";
        process.stdout.write(line.substring(1) + ": ");
    } else {
        process.stdout.write(line);
    }
});

readInterface.on("close", () => process.stdout.write("\n"));


FASTA format

Solution:
import io

FASTA='''\
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED'''

infile = io.StringIO(FASTA)

def fasta_parse(infile):
    key = ''
    for line in infile:
        if line.startswith('>'):
            if key:
                yield key, val
            key, val = line[1:].rstrip().split()[0], ''
        elif key:
            val += line.rstrip()
    if key:
        yield key, val

print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))


Faces from a mesh

A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,

For example:
[https://drive.google.com/file/d/1qNS_L0LGIKhoo-gmBLlyDGECtjp9l7x8/view External image of two faces]
Rough textual version without edges:

      1
                        17
 7   A
             B

       11
                  23

* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
      1

 7   A

       11

* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
                  17

       B

 11
            23

Let's call the above the '''perimeter format''' as it traces around the perimeter.

;A second format:
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
* A single edge is described by the vertex numbers at its two ends, always in
ascending order.
* All edges for the face are given, but in an undefined order.

For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The  order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).

Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.

Let's call this second format the '''edge format'''.

;Task:
'''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter.  Use it to check if the following pairs of perimeters are the same:
 Q: (8, 1, 3)
 R: (1, 3, 8)

 U: (18, 8, 14, 10, 12, 17, 19)
 V: (8, 14, 10, 12, 17, 19, 18)

'''2.''' Write a routine and use it to transform the following faces from edge to perimeter format.
 E: {(1, 11), (7, 11), (1, 7)}
 F: {(11, 23), (1, 17), (17, 23), (1, 11)}
 G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
 H: {(1, 3), (9, 11), (3, 11), (1, 11)}

Show your output here.

Solution:
def perim_equal(p1, p2):
    # Cheap tests first
    if len(p1) != len(p2) or set(p1) != set(p2):
        return False
    if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):
        return True
    p2 = p2[::-1] # not inplace
    return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))

def edge_to_periphery(e):
    edges = sorted(e)
    p = list(edges.pop(0)) if edges else []
    last = p[-1] if p else None
    while edges:
        for n, (i, j) in enumerate(edges):
            if i == last:
                p.append(j)
                last = j
                edges.pop(n)
                break
            elif j == last:
                p.append(i)
                last = i
                edges.pop(n)
                break
        else:
            #raise ValueError(f'Invalid edge format: {e}')
            return ">>>Error! Invalid edge format<<<"
    return p[:-1]

if __name__ == '__main__':
    print('Perimeter format equality checks:')
    for eq_check in [
            { 'Q': (8, 1, 3),
              'R': (1, 3, 8)},
            { 'U': (18, 8, 14, 10, 12, 17, 19),
              'V': (8, 14, 10, 12, 17, 19, 18)} ]:
        (n1, p1), (n2, p2) = eq_check.items()
        eq = '==' if perim_equal(p1, p2) else '!='
        print(' ', n1, eq, n2)

    print('\nEdge to perimeter format translations:')
    edge_d = {
     'E': {(1, 11), (7, 11), (1, 7)},
     'F': {(11, 23), (1, 17), (17, 23), (1, 11)},
     'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)},
     'H': {(1, 3), (9, 11), (3, 11), (1, 11)}
            }
    for name, edges in edge_d.items():
        print(f"  {name}: {edges}\n     -> {edge_to_periphery(edges)}")


Factorial base numbers indexing permutations of a collection

You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.

I want to produce a 1 to 1 mapping between these numbers and permutations:-
        0.0.0 -> 0123
        0.0.1 -> 0132
        0.1.0 -> 0213
        0.1.1 -> 0231
        0.2.0 -> 0312
        0.2.1 -> 0321
        1.0.0 -> 1023
        1.0.1 -> 1032
        1.1.0 -> 1203
        1.1.1 -> 1230
        1.2.0 -> 1302
        1.2.1 -> 1320
        2.0.0 -> 2013
        2.0.1 -> 2031
        2.1.0 -> 2103
        2.1.1 -> 2130
        2.2.0 -> 2301
        2.2.1 -> 2310
        3.0.0 -> 3012
        3.0.1 -> 3021
        3.1.0 -> 3102
        3.1.1 -> 3120
        3.2.0 -> 3201
        3.2.1 -> 3210

The following psudo-code will do this:
Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.

If g is greater than zero, rotate the elements from m to m+g in Ω (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.

Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1

Let me work 2.0.1 and 0123
     step 1 n=0 g=2 Ω=2013
     step 2 n=1 g=0 so no action
     step 3 n=2 g=1 Ω=2031

The task:

  First use your function to recreate the above table.
  Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
     methods in rc's permutations task.
  Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
    39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
    51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
    use your function to crate the corresponding permutation of the following shoe of cards:
       A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣
  Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe

Solution:
"""

http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection

https://en.wikipedia.org/wiki/Factorial_number_system

"""

import math

def apply_perm(omega,fbn):
    """

    omega contains a list which will be permuted (scrambled)
    based on fbm.

    fbm is a list which represents a factorial base number.

    This function just translates the pseudo code in the
    Rosetta Code task.

    """
    for m in range(len(fbn)):
        g = fbn[m]
        if g > 0:
            # do rotation
            # save last number
            new_first = omega[m+g]
            # move numbers right
            omega[m+1:m+g+1] = omega[m:m+g]
            # put last number first
            omega[m] = new_first

    return omega

def int_to_fbn(i):
    """

    convert integer i to factorial based number

    """
    current = i
    divisor = 2
    new_fbn = []
    while current > 0:
        remainder = current % divisor
        current = current // divisor
        new_fbn.append(remainder)
        divisor += 1

    return list(reversed(new_fbn))

def leading_zeros(l,n):
   """

   If list l has less than n elements returns l with enough 0 elements
   in front of the list to make it length n.

   """
   if len(l) < n:
       return(([0] * (n - len(l))) + l)
   else:
       return l

def get_fbn(n):
    """

    Return the n! + 1 first Factorial Based Numbers starting with zero.

    """
    max = math.factorial(n)

    for i in range(max):
        # from Wikipedia article
        current = i
        divisor = 1
        new_fbn = int_to_fbn(i)
        yield leading_zeros(new_fbn,n-1)

def print_write(f, line):
    """

    prints to console and
    output file f

    """
    print(line)
    f.write(str(line)+'\n')

def dot_format(l):
    """
    Take a list l that is a factorial based number
    and returns it in dot format.

    i.e. [0, 2, 1] becomes 0.2.1
    """
    # empty list
    if len(l) < 1:
        return ""
    # start with just first element no dot
    dot_string = str(l[0])
    # add rest if any with dots
    for e in l[1:]:
        dot_string += "."+str(e)

    return dot_string

def str_format(l):
    """
    Take a list l and returns a string
    of those elements converted to strings.
    """
    if len(l) < 1:
        return ""

    new_string = ""

    for e in l:
        new_string += str(e)

    return new_string

with open("output.html", "w", encoding="utf-8") as f:
    f.write("\n")

    # first print list

    omega=[0,1,2,3]

    four_list = get_fbn(4)

    for l in four_list:
        print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l)))

    print_write(f," ")

    # now generate this output:
    #
    # Permutations generated = 39916800
    # compared to 11! which  = 39916800

    num_permutations = 0

    for p in get_fbn(11):
        num_permutations += 1
        if num_permutations % 1000000 == 0:
            print_write(f,"permutations so far = "+str(num_permutations))

    print_write(f," ")
    print_write(f,"Permutations generated = "+str(num_permutations))
    print_write(f,"compared to 11! which  = "+str(math.factorial(11)))

    print_write(f," ")

    """

    u"\u2660" - spade

    u"\u2665" - heart

    u"\u2666" - diamond

    u"\u2663" - club

    """

    shoe = []

    for suit in [u"\u2660",u"\u2665",u"\u2666",u"\u2663"]:
        for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']:
            shoe.append(value+suit)

    print_write(f,str_format(shoe))

    p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0]

    p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1]

    print_write(f," ")
    print_write(f,dot_format(p1))
    print_write(f," ")
    print_write(f,str_format(apply_perm(shoe[:],p1)))

    print_write(f," ")
    print_write(f,dot_format(p2))
    print_write(f," ")
    print_write(f,str_format(apply_perm(shoe[:],p2)))

    # generate random 51 digit factorial based number

    import random

    max = math.factorial(52)

    random_int = random.randint(0, max-1)

    myperm = leading_zeros(int_to_fbn(random_int),51)

    print(len(myperm))

    print_write(f," ")
    print_write(f,dot_format(myperm))
    print_write(f," ")
    print_write(f,str_format(apply_perm(shoe[:],myperm)))

    f.write("\n")


Factorial primes

;Definition
A factorial.

In other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime.

;Examples
4 corresponds to the factorial prime 4! - 1 = 23.

5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.

;Task
Find and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted.

As 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.

;Stretch
If your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.

As it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.

If a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.

;Reference
* OEIS:A088054 - Factorial primes

;Related task
* Sequence of primorial primes

Solution:
from itertools import count
from itertools import islice
from typing import Iterable
from typing import Tuple

import gmpy2

def factorials() -> Iterable[int]:
    fact = 1
    for i in count(1):
        yield fact
        fact *= i

def factorial_primes() -> Iterable[Tuple[int, int, str]]:
    for n, fact in enumerate(factorials()):
        if gmpy2.is_prime(fact - 1):
            yield (n, fact - 1, "-")
        if gmpy2.is_prime(fact + 1):
            yield (n, fact + 1, "+")

def print_factorial_primes(limit=10) -> None:
    print(f"First {limit} factorial primes.")
    for n, fact_prime, op in islice(factorial_primes(), 1, limit + 1):
        s = str(fact_prime)
        if len(s) > 40:
            s = f"{s[:20]}...{s[-20:]} ({len(s)} digits)"
        print(f"{n}! {op} 1 = {s}")

if __name__ == "__main__":
    import sys
    print_factorial_primes(int(sys.argv[1]) if len(sys.argv) > 1 else 10)


Factorions

;Definition:
A factorion is a natural number that equals the sum of the factorials of its digits.

;Example:
'''145'''   is a factorion in base '''10''' because:

 1! + 4! + 5!   =   1 + 24 + 120   =   145

It can be shown (see talk page) that no factorion in base '''10''' can exceed   '''1,499,999'''.

;Task:
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
:*   There are   '''3'''   factorions in base   '''9'''
:*   There are   '''4'''   factorions in base '''10'''
:*   There are   '''5'''   factorions in base '''11'''
:*   There are   '''2'''   factorions in base '''12'''     (up to the same upper bound as for base '''10''')

;See also:
:* '''Wikipedia article'''
:* '''OEIS:A014080 - Factorions in base 10'''
:* '''OEIS:A193163 - Factorions in base n'''

Solution:
#include

int main() {
    int n, b, d;
    unsigned long long i, j, sum, fact[12];
    // cache factorials from 0 to 11
    fact[0] = 1;
    for (n = 1; n < 12; ++n) {
        fact[n] = fact[n-1] * n;
    }

    for (b = 9; b <= 12; ++b) {
        printf("The factorions for base %d are:\n", b);
        for (i = 1; i < 1500000; ++i) {
            sum = 0;
            j = i;
            while (j > 0) {
                d = j % b;
                sum += fact[d];
                j /= b;
            }
            if (sum == i) printf("%llu ", i);
        }
        printf("\n\n");
    }
    return 0;
}


Factorions

Solution:
fact = [1] # cache factorials from 0 to 11
for n in range(1, 12):
    fact.append(fact[n-1] * n)

for b in range(9, 12+1):
    print(f"The factorions for base {b} are:")
    for i in range(1, 1500000):
        fact_sum = 0
        j = i
        while j > 0:
            d = j % b
            fact_sum += fact[d]
            j = j//b
        if fact_sum == i:
            print(i, end=" ")
    print("\n")


Fairshare between two and more

The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)

The Thue-Morse sequence of ones-and-zeroes can be generated by:
:''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"''

;Sharing fairly between two or more:
Use this method:
:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''

;Task
Counting from zero;   using a function/method/routine to express an integer count in base '''b''',
sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.

Show the first 25 terms of the fairshare sequence:
:*   For two people:
:*   For three people
:*   For five people
:*   For eleven people

;Related tasks:
:*   [[Non-decimal radices/Convert]]
:*   [[Thue-Morse]]

;See also:
:*   [https://oeis.org/A010060 A010060], [https://oeis.org/A053838 A053838], [https://oeis.org/A053840 A053840]: The On-Line Encyclopedia of Integer Sequences® (OEIS®)

Solution:
#include
#include

int turn(int base, int n) {
    int sum = 0;
    while (n != 0) {
        int rem = n % base;
        n = n / base;
        sum += rem;
    }
    return sum % base;
}

void fairshare(int base, int count) {
    int i;

    printf("Base %2d:", base);
    for (i = 0; i < count; i++) {
        int t = turn(base, i);
        printf(" %2d", t);
    }
    printf("\n");
}

void turnCount(int base, int count) {
    int *cnt = calloc(base, sizeof(int));
    int i, minTurn, maxTurn, portion;

    if (NULL == cnt) {
        printf("Failed to allocate space to determine the spread of turns.\n");
        return;
    }

    for (i = 0; i < count; i++) {
        int t = turn(base, i);
        cnt[t]++;
    }

    minTurn = INT_MAX;
    maxTurn = INT_MIN;
    portion = 0;
    for (i = 0; i < base; i++) {
        if (cnt[i] > 0) {
            portion++;
        }
        if (cnt[i] < minTurn) {
            minTurn = cnt[i];
        }
        if (cnt[i] > maxTurn) {
            maxTurn = cnt[i];
        }
    }

    printf("  With %d people: ", base);
    if (0 == minTurn) {
        printf("Only %d have a turn\n", portion);
    } else if (minTurn == maxTurn) {
        printf("%d\n", minTurn);
    } else {
        printf("%d or %d\n", minTurn, maxTurn);
    }

    free(cnt);
}

int main() {
    fairshare(2, 25);
    fairshare(3, 25);
    fairshare(5, 25);
    fairshare(11, 25);

    printf("How many times does each get a turn in 50000 iterations?\n");
    turnCount(191, 50000);
    turnCount(1377, 50000);
    turnCount(49999, 50000);
    turnCount(50000, 50000);
    turnCount(50001, 50000);

    return 0;
}


Fairshare between two and more

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

    // thueMorse :: Int -> [Int]
    const thueMorse = base =>
        // Thue-Morse sequence for a given base
        fmapGen(baseDigitsSumModBase(base))(
            enumFrom(0)
        )

    // baseDigitsSumModBase :: Int -> Int -> Int
    const baseDigitsSumModBase = base =>
        // For any integer n, the sum of its digits
        // in a given base, modulo that base.
        n => sum(unfoldl(
            x => 0 < x ? (
                Just(quotRem(x)(base))
            ) : Nothing()
        )(n)) % base

    // ------------------------TEST------------------------
    const main = () =>
        console.log(
            fTable(
                'First 25 fairshare terms for a given number of players:'
            )(str)(
                xs => '[' + map(
                    compose(justifyRight(2)(' '), str)
                )(xs) + ' ]'
            )(
                compose(take(25), thueMorse)
            )([2, 3, 5, 11])
        );

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

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

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

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        x => fs.reduceRight((a, f) => f(a), 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;
        }
    }

    // fTable :: String -> (a -> String) -> (b -> String)
    //                      -> (a -> b) -> [a] -> String
    const fTable = s => xShow => fxShow => f => xs => {
        // Heading -> x display function ->
        //           fx display function ->
        //    f -> values -> tabular string
        const
            ys = xs.map(xShow),
            w = Math.max(...ys.map(length));
        return s + '\n' + zipWith(
            a => b => a.padStart(w, ' ') + ' -> ' + b
        )(ys)(
            xs.map(x => fxShow(f(x)))
        ).join('\n');
    };

    // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
    const fmapGen = f =>
        function*(gen) {
            let v = take(1)(gen);
            while (0 < v.length) {
                yield(f(v[0]))
                v = take(1)(gen)
            }
        };

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

    // 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);

    // quotRem :: Int -> Int -> (Int, Int)
    const quotRem = m => n =>
        Tuple(Math.floor(m / n))(
            m % n
        );

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

    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        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];
        }));

    // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
    const unfoldl = f => v => {
        // Dual to reduce or foldl.
        // Where these reduce a list to a summary value, unfoldl
        // builds a list from a seed value.
        // Where f returns Just(a, b), a is appended to the list,
        // and the residual b is used as the argument for the next
        // application of f.
        // Where f returns Nothing, the completed list is returned.
        let
            xr = [v, v],
            xs = [];
        while (true) {
            const mb = f(xr[0]);
            if (mb.Nothing) {
                return xs
            } else {
                xr = mb.Just;
                xs = [xr[1]].concat(xs);
            }
        }
    };

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
        xs => ys => {
            const
                lng = Math.min(length(xs), length(ys)),
                vs = take(lng)(ys);
            return take(lng)(xs)
                .map((x, i) => f(x)(vs[i]));
        };

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


Fairshare between two and more

Solution:
from itertools import count, islice

def _basechange_int(num, b):
    """
    Return list of ints representing positive num in base b

    >>> b = 3
    >>> print(b, [_basechange_int(num, b) for num in range(11)])
    3 [[0], [1], [2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [1, 0, 0], [1, 0, 1]]
    >>>
    """
    if num == 0:
        return [0]
    result = []
    while num != 0:
        num, d = divmod(num, b)
        result.append(d)
    return result[::-1]

def fairshare(b=2):
    for i in count():
        yield sum(_basechange_int(i, b)) % b

if __name__ == '__main__':
    for b in (2, 3, 5, 11):
        print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")


Farey sequence

The   Farey sequence   ''' ''F''n'''   of order   '''n'''   is the sequence of completely reduced fractions between   '''0'''   and   '''1'''   which, when in lowest terms, have denominators less than or equal to   '''n''',   arranged in order of increasing size.

The   ''Farey sequence''   is sometimes incorrectly called a   ''Farey series''.

Each Farey sequence:
:::*   starts with the value   '''0'''   (zero),   denoted by the fraction      \frac{0}{1}
:::*   ends with the value   '''1'''   (unity),   denoted by the fraction    \frac{1}{1}.

The Farey sequences of orders   '''1'''   to   '''5'''   are:

:::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}
:
:::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}
:
:::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}
:
:::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1}
:
:::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1}

;Task
*   Compute and show the Farey sequence for orders   '''1'''   through   '''11'''   (inclusive).
*   Compute and display the   ''number''   of fractions in the Farey sequence for order   '''100'''   through   '''1,000'''   (inclusive)   by hundreds.
*   Show the fractions as    '''n/d'''    (using the solidus [or slash] to separate the numerator from the denominator).

The length   (the number of fractions)   of a Farey sequence asymptotically approaches:

:::::::::::  3 × n2   ÷   \pi2

;See also:
*    OEIS sequence           A006842 numerators of Farey series of order 1, 2, ···
*    OEIS sequence           A006843 denominators of Farey series of order 1, 2, ···
*    OEIS sequence           A005728 number of fractions in Farey series of order n
*   MathWorld entry          [http://mathworld.wolfram.com/FareySequence.html Farey sequence]
*   Wikipedia   entry   Farey sequence

Solution:
#include
#include
#include

void farey(int n)
{
	typedef struct { int d, n; } frac;
	frac f1 = {0, 1}, f2 = {1, n}, t;
	int k;

	printf("%d/%d %d/%d", 0, 1, 1, n);
	while (f2.n > 1) {
		k = (n + f1.n) / f2.n;
		t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n };
		printf(" %d/%d", f2.d, f2.n);
	}

	putchar('\n');
}

typedef unsigned long long ull;
ull *cache;
size_t ccap;

ull farey_len(int n)
{
	if (n >= ccap) {
		size_t old = ccap;
		if (!ccap) ccap = 16;
		while (ccap <= n) ccap *= 2;
		cache = realloc(cache, sizeof(ull) * ccap);
		memset(cache + old, 0, sizeof(ull) * (ccap - old));
	} else if (cache[n])
		return cache[n];

	ull len = (ull)n*(n + 3) / 2;
	int p, q = 0;
	for (p = 2; p <= n; p = q) {
		q = n/(n/p) + 1;
		len -= farey_len(n/p) * (q - p);
	}

	cache[n] = len;
	return len;
}

int main(void)
{
	int n;
	for (n = 1; n <= 11; n++) {
		printf("%d: ", n);
		farey(n);
	}

	for (n = 100; n <= 1000; n += 100)
		printf("%d: %llu items\n", n, farey_len(n));

	n = 10000000;
	printf("\n%d: %llu items\n", n, farey_len(n));
	return 0;
}


Farey sequence

Solution:
from fractions import Fraction

class Fr(Fraction):
    def __repr__(self):
        return '(%s/%s)' % (self.numerator, self.denominator)

def farey(n, length=False):
    if not length:
        return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
    else:
        #return 1         +    len({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
        return  (n*(n+3))//2 - sum(farey(n//k, True) for k in range(2, n+1))

if __name__ == '__main__':
    print('Farey sequence for order 1 through 11 (inclusive):')
    for n in range(1, 12):
        print(farey(n))
    print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:')
    print([farey(i, length=True) for i in range(100, 1001, 100)])


Fast Fourier transform

;Task:
Calculate the   FFT   (Fast Fourier Transform)   of an input sequence.

The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result.

The classic version is the recursive Cooley–Tukey FFT. [http://en.wikipedia.org/wiki/Cooley–Tukey_FFT_algorithm Wikipedia] has pseudo-code for that.
Further optimizations are possible but not required.

Solution:
#include
#include
#include

double PI;
typedef double complex cplx;

void _fft(cplx buf[], cplx out[], int n, int step)
{
	if (step < n) {
		_fft(out, buf, n, step * 2);
		_fft(out + step, buf + step, n, step * 2);

		for (int i = 0; i < n; i += 2 * step) {
			cplx t = cexp(-I * PI * i / n) * out[i + step];
			buf[i / 2]     = out[i] + t;
			buf[(i + n)/2] = out[i] - t;
		}
	}
}

void fft(cplx buf[], int n)
{
	cplx out[n];
	for (int i = 0; i < n; i++) out[i] = buf[i];

	_fft(buf, out, n, 1);
}

void show(const char * s, cplx buf[]) {
	printf("%s", s);
	for (int i = 0; i < 8; i++)
		if (!cimag(buf[i]))
			printf("%g ", creal(buf[i]));
		else
			printf("(%g, %g) ", creal(buf[i]), cimag(buf[i]));
}

int main()
{
	PI = atan2(1, 1) * 4;
	cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0};

	show("Data: ", buf);
	fft(buf, 8);
	show("\nFFT : ", buf);

	return 0;
}


Fast Fourier transform

Solution:
/*
complex fast fourier transform and inverse from
http://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B
*/
function icfft(amplitudes)
{
	var N = amplitudes.length;
	var iN = 1 / N;

	//conjugate if imaginary part is not 0
	for(var i = 0 ; i < N; ++i)
		if(amplitudes[i] instanceof Complex)
			amplitudes[i].im = -amplitudes[i].im;

	//apply fourier transform
	amplitudes = cfft(amplitudes)

	for(var i = 0 ; i < N; ++i)
	{
		//conjugate again
		amplitudes[i].im = -amplitudes[i].im;
		//scale
		amplitudes[i].re *= iN;
		amplitudes[i].im *= iN;
	}
	return amplitudes;
}

function cfft(amplitudes)
{
	var N = amplitudes.length;
	if( N <= 1 )
		return amplitudes;

	var hN = N / 2;
	var even = [];
	var odd = [];
	even.length = hN;
	odd.length = hN;
	for(var i = 0; i < hN; ++i)
	{
		even[i] = amplitudes[i*2];
		odd[i] = amplitudes[i*2+1];
	}
	even = cfft(even);
	odd = cfft(odd);

	var a = -2*Math.PI;
	for(var k = 0; k < hN; ++k)
	{
		if(!(even[k] instanceof Complex))
			even[k] = new Complex(even[k], 0);
		if(!(odd[k] instanceof Complex))
			odd[k] = new Complex(odd[k], 0);
		var p = k/N;
		var t = new Complex(0, a * p);
		t.cexp(t).mul(odd[k], t);
		amplitudes[k] = even[k].add(t, odd[k]);
		amplitudes[k + hN] = even[k].sub(t, even[k]);
	}
	return amplitudes;
}

//test code
//console.log( cfft([1,1,1,1,0,0,0,0]) );
//console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );


Fast Fourier transform

Solution:
from cmath import exp, pi

def fft(x):
    N = len(x)
    if N <= 1: return x
    even = fft(x[0::2])
    odd =  fft(x[1::2])
    T= [exp(-2j*pi*k/N)*odd[k] for k in range(N//2)]
    return [even[k] + T[k] for k in range(N//2)] + \
           [even[k] - T[k] for k in range(N//2)]

print( ' '.join("%5.3f" % abs(f)
                for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) )


Feigenbaum constant calculation

;Task:
Calculate the Feigenbaum constant.

;See:
:*   Details in the Wikipedia article:   [https://en.wikipedia.org/wiki/Feigenbaum_constants Feigenbaum constant].

Solution:
#include

void feigenbaum() {
    int i, j, k, max_it = 13, max_it_j = 10;
    double a, x, y, d, a1 = 1.0, a2 = 0.0, d1 = 3.2;
    printf(" i       d\n");
    for (i = 2; i <= max_it; ++i) {
        a = a1 + (a1 - a2) / d1;
        for (j = 1; j <= max_it_j; ++j) {
            x = 0.0;
            y = 0.0;
            for (k = 1; k <= 1 << i; ++k) {
                 y = 1.0 - 2.0 * y * x;
                 x = a - x * x;
            }
            a -= x / y;
        }
        d = (a1 - a2) / (a - a1);
        printf("%2d    %.8f\n", i, d);
        d1 = d;
        a2 = a1;
        a1 = a;
    }
}

int main() {
    feigenbaum();
    return 0;
}


Feigenbaum constant calculation

Solution:
max_it = 13
max_it_j = 10
a1 = 1.0
a2 = 0.0
d1 = 3.2
a = 0.0

print " i       d"
for i in range(2, max_it + 1):
    a = a1 + (a1 - a2) / d1
    for j in range(1, max_it_j + 1):
        x = 0.0
        y = 0.0
        for k in range(1, (1 << i) + 1):
            y = 1.0 - 2.0 * y * x
            x = a - x * x
        a = a - x / y
    d = (a1 - a2) / (a - a1)
    print("{0:2d}    {1:.8f}".format(i, d))
    d1 = d
    a2 = a1
    a1 = a


Fibonacci n-step number sequences

These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}

For small values of n, Greek numeric prefixes are sometimes used to individually name each series.

:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
|  2 ||  fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
|  3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
|  4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
|  5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
|  6 ||  hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
|  7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
|  8 ||  octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
|  9 ||  nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 ||  decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}

Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.

;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.

;Related tasks:
*   [[Fibonacci sequence]]
*   [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld]
*   [[Hofstadter Q sequence]]
*   [[Leonardo numbers]]

;Also see:
*   [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)
*   [https://www.youtube.com/watch?v=fMJflV_GUpU Tribonacci Numbers (and the Rauzy Fractal) - Numberphile] (Video)
*   Wikipedia, Lucas number
*   [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
*   [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
*   OEIS Fibonacci numbers
*   OEIS Lucas numbers

Solution:
/*
The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/

#include
#include

int *
anynacci (int *seedArray, int howMany)
{
  int *result = malloc (howMany * sizeof (int));
  int i, j, initialCardinality;

  for (i = 0; seedArray[i] != 0; i++);
  initialCardinality = i;

  for (i = 0; i < initialCardinality; i++)
    result[i] = seedArray[i];

  for (i = initialCardinality; i < howMany; i++)
    {
      result[i] = 0;
      for (j = i - initialCardinality; j < i; j++)
        result[i] += result[j];
    }
  return result;
}

int
main ()
{
  int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 };
  int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10),
      *lucas = anynacci(luca, 10);
  int i;

  printf ("\nFibonacci\tTribonacci\tTetranacci\tLucas\n");

  for (i = 0; i < 10; i++)
    printf ("\n%d\t\t%d\t\t%d\t\t%d", fibonacci[i], tribonacci[i],
            tetranacci[i], lucas[i]);

  return 0;
}


Fibonacci n-step number sequences

Solution:
function fib(arity, len) {
    return nacci(nacci([1,1], arity, arity), arity, len);
}

function lucas(arity, len) {
    return nacci(nacci([2,1], arity, arity), arity, len);
}

function nacci(a, arity, len) {
    while (a.length < len) {
        var sum = 0;
        for (var i = Math.max(0, a.length - arity); i < a.length; i++)
            sum += a[i];
        a.push(sum);
    }
    return a;
}

function main() {
    for (var arity = 2; arity <= 10; arity++)
        console.log("fib(" + arity + "): " + fib(arity, 15));
    for (var arity = 2; arity <= 10; arity++)
        console.log("lucas(" + arity + "): " + lucas(arity, 15));
}

main();


Fibonacci n-step number sequences

Solution:
>>> class Fiblike():
	def __init__(self, start):
		self.addnum = len(start)
		self.memo = start[:]
	def __call__(self, n):
		try:
			return self.memo[n]
		except IndexError:
			ans = sum(self(i) for i in range(n-self.addnum, n))
			self.memo.append(ans)
			return ans

>>> fibo = Fiblike([1,1])
>>> [fibo(i) for i in range(10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> lucas = Fiblike([2,1])
>>> [lucas(i) for i in range(10)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
>>> for n, name in zip(range(2,11), 'fibo tribo tetra penta hexa hepta octo nona deca'.split()) :
	fibber = Fiblike([1] + [2**i for i in range(n-1)])
	print('n=%2i, %5snacci -> %s ...' % (n, name, ' '.join(str(fibber(i)) for i in range(15))))

n= 2,  fibonacci -> 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
n= 3, tribonacci -> 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
n= 4, tetranacci -> 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
n= 5, pentanacci -> 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
n= 6,  hexanacci -> 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
n= 7, heptanacci -> 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
n= 8,  octonacci -> 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
n= 9,  nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10,  decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>>


Fibonacci word

The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence    [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf as described here]:

     Define   F_Word1   as   '''1'''
     Define   F_Word2   as   '''0'''
     Form     F_Word3   as   F_Word2     concatenated with   F_Word1    i.e.:   '''01'''
     Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2

;Task:
Perform the above steps for     n = 37.

You may display the first few but not the larger values of   n.
{Doing so will get the task's author into trouble with them what be (again!).}

Instead, create a table for   F_Words   '''1'''   to   '''37'''   which shows:
::*   The number of characters in the word
::*   The word's [[Entropy]]

;Related tasks:
*   Fibonacci word/fractal
*   [[Entropy]]
*   [[Entropy/Narcissist]]

Solution:
#include
#include
#include
#include

void print_headings()
{
	printf("%2s", "N");
	printf(" %10s", "Length");
	printf(" %-20s", "Entropy");
	printf(" %-40s", "Word");
	printf("\n");
}

double calculate_entropy(int ones, int zeros)
{
	double result = 0;

	int total = ones + zeros;
	result -= (double) ones / total * log2((double) ones / total);
	result -= (double) zeros / total * log2((double) zeros / total);

	if (result != result) { // NAN
		result = 0;
	}

	return result;
}

void print_entropy(char *word)
{
	int ones = 0;
	int zeros = 0;

	int i;
	for (i = 0; word[i]; i++) {
		char c = word[i];

		switch (c) {
			case '0':
				zeros++;
				break;
			case '1':
				ones++;
				break;
		}
	}

	double entropy = calculate_entropy(ones, zeros);
	printf(" %-20.18f", entropy);
}

void print_word(int n, char *word)
{
	printf("%2d", n);

	printf(" %10ld", strlen(word));

	print_entropy(word);

	if (n < 10) {
		printf(" %-40s", word);
	} else {
		printf(" %-40s", "...");
	}

	printf("\n");
}

int main(int argc, char *argv[])
{
	print_headings();

	char *last_word = malloc(2);
	strcpy(last_word, "1");

	char *current_word = malloc(2);
	strcpy(current_word, "0");

	print_word(1, last_word);
	int i;
	for (i = 2; i <= 37; i++) {
		print_word(i, current_word);

		char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);
		strcpy(next_word, current_word);
		strcat(next_word, last_word);

		free(last_word);
		last_word = current_word;
		current_word = next_word;
	}

	free(last_word);
	free(current_word);
	return 0;
}


Fibonacci word

Solution:
//makes outputting a table possible in environments
//that don't support console.table()
function console_table(xs) {
    function pad(n,s) {
        var res = s;
        for (var i = s.length; i < n; i++)
            res += " ";
        return res;
    }

    if (xs.length === 0)
        console.log("No data");
    else {
        var widths = [];
        var cells = [];
        for (var i = 0; i <= xs.length; i++)
            cells.push([]);

        for (var s in xs[0]) {
            var len = s.length;
            cells[0].push(s);

            for (var i = 0; i < xs.length; i++) {
                var ss = "" + xs[i][s];
                len = Math.max(len, ss.length);
                cells[i+1].push(ss);
            }
            widths.push(len);
        }
        var s = "";
        for (var x = 0; x < cells.length; x++) {
            for (var y = 0; y < widths.length; y++)
                s += "|" + pad(widths[y], cells[x][y]);
            s += "|\n";
        }
        console.log(s);
    }
}

//returns the entropy of a string as a number
function entropy(s) {
     //create an object containing each individual char
	//and the amount of iterations per char
    function prob(s) {
        var h = Object.create(null);
        s.split('').forEach(function(c) {
           h[c] && h[c]++ || (h[c] = 1);
        });
        return h;
    }

    s = s.toString(); //just in case
    var e = 0, l = s.length, h = prob(s);

    for (var i in h ) {
        var p = h[i]/l;
        e -= p * Math.log(p) / Math.log(2);
    }
    return e;
}

//creates Fibonacci Word to n as described on Rosetta Code
//see rosettacode.org/wiki/Fibonacci_word
function fibWord(n) {
    var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = [];

    for (var i = 0; i < n; i++) {
        if (i === 0 || i === 1) {
            w = wNth[i];
        } else {
            w = wNth[i - 1] + wNth[i - 2];
            wNth.push(w);
        }
        var l = w.length;
        var e = entropy(w);

        if (l <= 21) {
        	o.push({
            	N: i + 1,
            	Length: l,
            	Entropy: e,
            	Word: w
        	});
        } else {
        	o.push({
            	N: i + 1,
            	Length: l,
            	Entropy: e,
            	Word: "..."
        	});
        }
    }

    try {
    	console.table(o);
    } catch (err) {
    	console_table(o);
    }
}

fibWord(37);


Fibonacci word

Solution:
>>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
...     p, lns = Counter(s), float(len(s))
...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
...     fwords = ['1', '0']
...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
...     def pr(n, fwords):
...         while len(fwords) < n:
...             fwords += [''.join(fwords[-2:][::-1])]
...         v = fwords[n-1]
...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else ''))
...     for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N       Length Entropy    Fibword
  1          1         -0 1
  2          1         -0 0
  3          2          1 01
  4          3  0.9182958 010
  5          5  0.9709506 01001
  6          8   0.954434 01001010
  7         13  0.9612366 0100101001001
  8         21  0.9587119
  9         34  0.9596869
 10         55   0.959316
 11         89  0.9594579
 12        144  0.9594038
 13        233  0.9594244
 14        377  0.9594165
 15        610  0.9594196
 16        987  0.9594184
 17       1597  0.9594188
 18       2584  0.9594187
 19       4181  0.9594187
 20       6765  0.9594187
 21      10946  0.9594187
 22      17711  0.9594187
 23      28657  0.9594187
 24      46368  0.9594187
 25      75025  0.9594187
 26     121393  0.9594187
 27     196418  0.9594187
 28     317811  0.9594187
 29     514229  0.9594187
 30     832040  0.9594187
 31    1346269  0.9594187
 32    2178309  0.9594187
 33    3524578  0.9594187
 34    5702887  0.9594187
 35    9227465  0.9594187
 36   14930352  0.9594187
 37   24157817  0.9594187
>>>


File extension is in extensions list

Filename extensions are a rudimentary but commonly used way of identifying files types.

;Task:
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.

Notes:
* The check should be case insensitive.
* The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
* You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.

;''Extra credit:''
: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
   archive.tar.gz
: Please state clearly whether or not your solution does this.

The following test cases all assume this list of extensions:   zip, rar, 7z, gz, archive, A##

:::::::: {| class="wikitable"
|-
! Filename
! Result
|-
| MyData.a##       || true
|-
| MyData.tar.Gz    || true
|-
| MyData.gzip      || false
|-
| MyData.7z.backup || false
|-
| MyData...        || false
|-
| MyData           || false
|}

If your solution does the extra credit requirement, add tar.bz2  to the list of extensions, and check the following additional test cases:

:::::::: {| class="wikitable"
|-
! Filename
! Result
|-
| MyData_v1.0.tar.bz2 || true
|-
| MyData_v1.0.bz2     || false
|}

Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.

It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.

For these reasons, this task exists in addition to the [[Extract file extension]] task.

;Related tasks:
* [[Extract file extension]]
* [[String matching]]

Solution:
/*
 * File extension is in extensions list (dots allowed).
 *
 * This problem is trivial because the so-called extension is simply the end
 * part of the name.
 */

#define _CRT_SECURE_NO_WARNINGS

#include
#include
#include
#include
#include

#ifdef _Bool
#include
#else
#define bool int
#define true  1
#define false 0
#endif

/*
 * The implemented algorithm is not the most efficient one: for N extensions
 * of length M it has the cost O(N * M).
 */
int checkFileExtension(char* fileName, char* fileExtensions)
{
    char* fileExtension = fileExtensions;

    if ( *fileName )
    {
        while ( *fileExtension )
        {
            int fileNameLength = strlen(fileName);
            int extensionLength = strlen(fileExtension);
            if ( fileNameLength >= extensionLength )
            {
                char* a = fileName + fileNameLength - extensionLength;
                char* b = fileExtension;
                while ( *a && toupper(*a++) == toupper(*b++) )
                    ;
                if ( !*a )
                    return true;
            }
            fileExtension += extensionLength + 1;
        }
    }
    return false;
}

void printExtensions(char* extensions)
{
    while( *extensions )
    {
        printf("%s\n", extensions);
        extensions += strlen(extensions) + 1;
    }
}

bool test(char* fileName, char* extension, bool expectedResult)
{
    bool result = checkFileExtension(fileName,extension);
    bool returnValue = result == expectedResult;
    printf("%20s  result: %-5s  expected: %-5s  test %s\n",
        fileName,
        result         ? "true"   : "false",
        expectedResult ? "true"   : "false",
        returnValue    ? "passed" : "failed" );
    return returnValue;
}

int main(void)
{
    static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0";

    setlocale(LC_ALL,"");

    printExtensions(extensions);
    printf("\n");

    if ( test("MyData.a##",         extensions,true )
    &&   test("MyData.tar.Gz",      extensions,true )
    &&   test("MyData.gzip",        extensions,false)
    &&   test("MyData.7z.backup",   extensions,false)
    &&   test("MyData...",          extensions,false)
    &&   test("MyData",             extensions,false)
    &&   test("MyData_v1.0.tar.bz2",extensions,true )
    &&   test("MyData_v1.0.bz2",    extensions,false)
    &&   test("filename",           extensions,false)
    )
        printf("\n%s\n", "All tests passed.");
    else
        printf("\n%s\n", "Last test failed.");

    printf("\n%s\n", "press enter");
    getchar();
    return 0;
}


File extension is in extensions list

Solution:
function fileExtensionInExtensionsList(filename) {
	let foundIt = false;
	let filenameLC = filename.toLowerCase();
	let extensions = ["zip", "rar", "7z", "gz", "archive", "A##" ,"tar.bz2"];
	extensions.forEach(extension =>  {
		if (filenameLC.endsWith("." + extension.toLowerCase())) { foundIt = true; }
	} );
	return foundIt;
}

// perform tests below

var fileNamesToTest = [
	"MyData.a##"
	,"MyData.tar.Gz"
	,"MyData.gzip"
	,"MyData.7z.backup"
	,"MyData..."
	,"MyData"
	,"MyData_v1.0.tar.bz2"
	,"MyData_v1.0.bz2"
];

fileNamesToTest.forEach(filename => {
	console.log(filename + " -> " + fileExtensionInExtensionsList(filename));
});


File extension is in extensions list

Solution:
'''Check for a specific set of file extensions'''

# extensionFound :: [Extension] -> FileName -> Maybe Extension
def extensionFound(xs):
    '''Nothing if no matching extension is found,
       or Just the extension (drawn from xs, and
       a suffix of the filename, immediately following
       a dot character).
    '''
    return lambda fn: find(fn.lower().endswith)(
        ['.' + x.lower() for x in xs]
    )

# TEST ----------------------------------------------------
# main :: IO ()
def main():
    '''Check filenames for a particular set of extensions.'''

    # checkExtension :: FileName -> Maybe Extension
    def checkExtension(fn):
        return extensionFound([
            'zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'
        ])(fn)

    print(
        fTable(__doc__ + ':\n')(str)(str)(
            compose(fromMaybe('n/a'))(checkExtension)
        )([
            'MyData.a##',
            'MyData.tar.Gz',
            'MyData.gzip',
            'MyData.7z.backup',
            'MyData...',
            'MyData',
            'MyData_v1.0.tar.bz2',
            'MyData_v1.0.bz2'
        ])
    )

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

# Just :: a -> Maybe a
def Just(x):
    '''Constructor for an inhabited Maybe (option type) value.'''
    return {'type': 'Maybe', 'Nothing': False, 'Just': x}

# Nothing :: Maybe a
def Nothing():
    '''Constructor for an empty Maybe (option type) value.'''
    return {'type': 'Maybe', 'Nothing': True}

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    '''Right to left function composition.'''
    return lambda f: lambda x: g(f(x))

# find :: (a -> Bool) -> [a] -> Maybe a
def find(p):
    '''Just the first element in the list that matches p,
       or Nothing if no elements match.
    '''
    def go(xs):
        for x in xs:
            if p(x):
                return Just(x)
        return Nothing()
    return lambda xs: go(xs)

# fromMaybe :: a -> Maybe a -> a
def fromMaybe(x):
    '''The default value x if mb is Nothing,
       or the value contained in mb.
    '''
    return lambda mb: x if (
        mb.get('Nothing')
    ) else mb.get('Just')

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

# fTable :: String -> (a -> String) ->
#                     (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
                     f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )

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


File size distribution

;Task:
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.

My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.

Don't forget that empty files may exist, to serve as a marker.

Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?

Solution:
#include
#include
#include

#define MAXORDER 25

int main(int argC, char* argV[])
{
	char str[MAXORDER],commandString[1000],*startPath;
	long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
	int i,j,len;
	double scale;
	FILE* fp;

	if(argC==1)
		printf("Usage : %s ",argV[0]);
	else{
		if(strchr(argV[1],' ')!=NULL){
		len = strlen(argV[1]);
		startPath = (char*)malloc((len+2)*sizeof(char));
		startPath[0] = '\"';
		startPath[len+1]='\"';
		strncpy(startPath+1,argV[1],len);
		startPath[len+2] = argV[1][len];
		sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
	}

	else if(strlen(argV[1])==1 && argV[1][0]=='.')
		strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");

	else
		sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);

	fp = popen(commandString,"r");

	while(fgets(str,100,fp)!=NULL){
			if(str[0]=='0')
				fileSizeLog[0]++;
			else
				fileSizeLog[strlen(str)]++;
	}

	if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
		for(i=0;imax)?max=fileSizeLog[i]:max;

				(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);

				for(i=0;i
Invocation and textual output :

C:\My Projects\threeJS>fileSize.exe "C:\My Projects" t

Size Order < 10^ 0 bytes : 1770
Size Order < 10^ 1 bytes : 1
Size Order < 10^ 2 bytes : 20
Size Order < 10^ 3 bytes : 219
Size Order < 10^ 4 bytes : 1793
Size Order < 10^ 5 bytes : 1832
Size Order < 10^ 6 bytes : 631
Size Order < 10^ 7 bytes : 124
Size Order < 10^ 8 bytes : 26
Size Order < 10^ 9 bytes : 0
Size Order < 10^10 bytes : 0
Size Order < 10^11 bytes : 0
Size Order < 10^12 bytes : 0
Size Order < 10^13 bytes : 0
Size Order < 10^14 bytes : 0
Size Order < 10^15 bytes : 0
Size Order < 10^16 bytes : 0
Size Order < 10^17 bytes : 0
Size Order < 10^18 bytes : 0
Size Order < 10^19 bytes : 0
Size Order < 10^20 bytes : 0
Size Order < 10^21 bytes : 0
Size Order < 10^22 bytes : 0
Size Order < 10^23 bytes : 0
Size Order < 10^24 bytes : 0

Invocation and graphical output :

C:\My Projects\threeJS>fileSize.exe "C:\My Projects" g

Size Order < 10^ 0 bytes |█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████1770
Size Order < 10^ 1 bytes |1
Size Order < 10^ 2 bytes |██20
Size Order < 10^ 3 bytes |█████████████████████████████219
Size Order < 10^ 4 bytes |████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████1793
Size Order < 10^ 5 bytes |██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████1832
Size Order < 10^ 6 bytes |██████████████████████████████████████████████████████████████████████████████████████631
Size Order < 10^ 7 bytes |████████████████124
Size Order < 10^ 8 bytes |███26
Size Order < 10^ 9 bytes |0
Size Order < 10^10 bytes |0
Size Order < 10^11 bytes |0
Size Order < 10^12 bytes |0
Size Order < 10^13 bytes |0
Size Order < 10^14 bytes |0
Size Order < 10^15 bytes |0
Size Order < 10^16 bytes |0
Size Order < 10^17 bytes |0
Size Order < 10^18 bytes |0
Size Order < 10^19 bytes |0
Size Order < 10^20 bytes |0
Size Order < 10^21 bytes |0
Size Order < 10^22 bytes |0
Size Order < 10^23 bytes |0
Size Order < 10^24 bytes |0

Note that it is possible to track files up to 10^24 (Yottabyte) in size with this implementation, but if you have a file that large, you shouldn't be needing such programs. :)

===POSIX===
This works on macOS 10.15. It should be OK for Linux as well.
#include
#include
#include
#include
#include

static const uintmax_t sizes[] = {
    0, 1000, 10000, 100000, 1000000, 10000000,
    100000000, 1000000000, 10000000000
};
static const size_t nsizes = sizeof(sizes)/sizeof(sizes[0]);
static uintmax_t count[nsizes + 1] = { 0 };
static uintmax_t files = 0;
static uintmax_t total_size = 0;

static int callback(const char* file, const struct stat* sp, int flag) {
    if (flag == FTW_F) {
        uintmax_t file_size = sp->st_size;
        ++files;
        total_size += file_size;
        size_t index = 0;
        for (; index < nsizes && sizes[index] < file_size; ++index);
        ++count[index];
    } else if (flag == FTW_DNR) {
        fprintf(stderr, "Cannot read directory %s.\n", file);
    }
    return 0;
}

int main(int argc, char** argv) {
    setlocale(LC_ALL, "");
    const char* directory = argc > 1 ? argv[1] : ".";
    if (ftw(directory, callback, 512) != 0) {
        perror(directory);
        return EXIT_FAILURE;
    }
    printf("File size distribution for '%s':\n", directory);
    for (size_t i = 0; i <= nsizes; ++i) {
        if (i == nsizes)
            printf("> %'lu", sizes[i - 1]);
        else
            printf("%'16lu", sizes[i]);
        printf(" bytes: %'lu\n", count[i]);
    }
    printf("Number of files: %'lu\n", files);
    printf("Total file size: %'lu\n", total_size);
    return EXIT_SUCCESS;
}


File size distribution

Solution:
import sys, os
from collections import Counter

def dodir(path):
    global h

    for name in os.listdir(path):
        p = os.path.join(path, name)

        if os.path.islink(p):
            pass
        elif os.path.isfile(p):
            h[os.stat(p).st_size] += 1
        elif os.path.isdir(p):
            dodir(p)
        else:
            pass

def main(arg):
    global h
    h = Counter()
    for dir in arg:
        dodir(dir)

    s = n = 0
    for k, v in sorted(h.items()):
        print("Size %d -> %d file(s)" % (k, v))
        n += v
        s += k * v
    print("Total %d bytes for %d files" % (s, n))

main(sys.argv[1:])