Eertree

An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.

The data structure has commonalities to both ''tries'' and ''suffix trees''.
  See links below.

;Task:
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.

;See also:
*   Wikipedia entry:   trie.
*   Wikipedia entry:   suffix tree
*   Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.

Solution:
using System;
using System.Collections.Generic;

namespace Eertree {
    class Node {
        public Node(int length) {
            this.Length = length;
            // empty or
            this.Edges = new Dictionary<char, int>();
        }

        public Node(int length, Dictionary<char, int> edges, int suffix) {
            this.Length = length;
            this.Edges = edges;
            this.Suffix = suffix;
        }

        public int Length { get; set; }
        public Dictionary<char, int> Edges { get; set; }
        public int Suffix { get; set; }
    }

    class Program {
        const int EVEN_ROOT = 0;
        const int ODD_ROOT = 1;

        static List<Node> Eertree(string s) {
            List<Node> tree = new List<Node> {
                //new Node(0, null, ODD_ROOT), or
                new Node(0, new Dictionary<char, int>(), ODD_ROOT),
                //new Node(-1, null, ODD_ROOT) or
                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)
            };
            int suffix = ODD_ROOT;
            int n, k;
            for (int i = 0; i < s.Length; i++) {
                char c = s[i];
                for (n = suffix; ; n = tree[n].Suffix) {
                    k = tree[n].Length;
                    int b = i - k - 1;
                    if (b >= 0 && s[b] == c) {
                        break;
                    }
                }
                if (tree[n].Edges.ContainsKey(c)) {
                    suffix = tree[n].Edges[c];
                    continue;
                }
                suffix = tree.Count;
                tree.Add(new Node(k + 2));
                tree[n].Edges[c] = suffix;
                if (tree[suffix].Length == 1) {
                    tree[suffix].Suffix = 0;
                    continue;
                }
                while (true) {
                    n = tree[n].Suffix;
                    int b = i - tree[n].Length - 1;
                    if (b >= 0 && s[b] == c) {
                        break;
                    }
                }
                tree[suffix].Suffix = tree[n].Edges[c];
            }
            return tree;
        }

        static List<string> SubPalindromes(List<Node> tree) {
            List<string> s = new List<string>();
            SubPalindromes_children(0, "", tree, s);
            foreach (var c in tree[1].Edges.Keys) {
                int m = tree[1].Edges[c];
                string ct = c.ToString();
                s.Add(ct);
                SubPalindromes_children(m, ct, tree, s);
            }
            return s;
        }

        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {
            foreach (var c in tree[n].Edges.Keys) {
                int m = tree[n].Edges[c];
                string p1 = c + p + c;
                s.Add(p1);
                SubPalindromes_children(m, p1, tree, s);
            }
        }

        static void Main(string[] args) {
            List<Node> tree = Eertree("eertree");
            List<string> result = SubPalindromes(tree);
            string listStr = string.Join(", ", result);
            Console.WriteLine("[{0}]", listStr);
        }
    }
}


Egyptian division

Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of [[Ethiopian multiplication]]

'''Algorithm:'''

Given two numbers where the '''dividend''' is to be divided by the '''divisor''':

# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
# Continue with successive i'th rows of 2^i and 2^i * divisor.
# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''
# Consider each row of the table, in the ''reverse'' order of its construction.
# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).

'''Example: 580 / 34'''

''' Table creation: '''

::: {| class="wikitable"
! powers_of_2
! doublings
|-
| 1
| 34
|-
| 2
| 68
|-
| 4
| 136
|-
| 8
| 272
|-
| 16
| 544
|}

''' Initialization of sums: '''

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| 16
| 544
|

|

|-
|
|
| 0
| 0
|}

''' Considering table rows, bottom-up: '''

When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
| 16
| 544
|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
| 16
| 544
|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
| 16
| 544
|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
| 16
| 544
|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| '''1'''
| '''34'''
| 17
| 578
|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

;Answer:
So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.

;Task:
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.

* Functions should be clear interpretations of the algorithm.
* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.

;Related tasks:
:*   Egyptian fractions

;References:
:*   Egyptian Number System

Solution:
using System;
using System.Collections;

namespace Egyptian_division
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.Clear();
			Console.WriteLine();
			Console.WriteLine(" Egyptian division ");
			Console.WriteLine();
			Console.Write(" Enter value of dividend : ");
			int dividend = int.Parse(Console.ReadLine());

			Console.Write(" Enter value of divisor : ");
			int divisor = int.Parse(Console.ReadLine());

			Divide(dividend, divisor);

			Console.WriteLine();
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);

		}

		static void Divide(int dividend, int divisor)
		{
			//
			// Local variable declaration and initialization
			//
			int result   = 0;
			int reminder = 0;

			int powers_of_two = 0;
			int doublings 	  = 0;

			int answer 	= 0;
			int accumulator = 0;

			int two = 2;
			int pow = 0;
			int row = 0;

			//
			// Tables declaration
			//
			ArrayList table_powers_of_two = new ArrayList();
			ArrayList table_doublings     = new ArrayList();

			//
			// Fill and Show table values
			//
			Console.WriteLine("                           ");
			Console.WriteLine(" powers_of_2     doublings ");
			Console.WriteLine("                           ");

			// Set initial values
			powers_of_two = 1;
			doublings = divisor;
			while( doublings <= dividend )
			{
				// Set table value
				table_powers_of_two.Add( powers_of_two );
				table_doublings.Add( doublings );

				// Show new table row
				Console.WriteLine("{0,8}{1,16}",powers_of_two, doublings);

				pow++;

				powers_of_two = (int)Math.Pow( two, pow );
				doublings = powers_of_two * divisor;
			}
			Console.WriteLine("                           ");

			//
			// Calculate division and Show table values
			//
			row = pow - 1;
			Console.WriteLine("                                                 ");
			Console.WriteLine(" powers_of_2     doublings   answer   accumulator");
			Console.WriteLine("                                                 ");
			Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row);

			pow--;
			while( pow >= 0 && accumulator < dividend )
			{
				// Get values from tables
				doublings = int.Parse(table_doublings[pow].ToString());
				powers_of_two = int.Parse(table_powers_of_two[pow].ToString());

				if(accumulator + int.Parse(table_doublings[pow].ToString()) <= dividend )
				{
					// Set new values
					accumulator += doublings;
					answer += powers_of_two;

					// Show accumulated row values in different collor
					Console.ForegroundColor = ConsoleColor.Green;
					Console.Write("{0,8}{1,16}",powers_of_two, doublings);
					Console.ForegroundColor = ConsoleColor.Green;
					Console.WriteLine("{0,10}{1,12}", answer, accumulator);
					Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2);
				}
				else
				{
					// Show not accumulated row walues
					Console.ForegroundColor = ConsoleColor.DarkGray;
					Console.Write("{0,8}{1,16}",powers_of_two, doublings);
					Console.ForegroundColor = ConsoleColor.Gray;
					Console.WriteLine("{0,10}{1,12}", answer, accumulator);
					Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2);
				}

				pow--;
			}

			Console.WriteLine();
			Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row + 2);
			Console.ResetColor();

			// Set result and reminder
			result = answer;
			if( accumulator < dividend )
			{
				reminder = dividend - accumulator;

				Console.WriteLine(" So " + dividend +
				                  " divided by " + divisor +
				                  " using the Egyptian method is \n " + result +
				                  " remainder (" + dividend + " - " + accumulator +
				                  ") or " + reminder);
				Console.WriteLine();
			}
			else
			{
				reminder = 0;

				Console.WriteLine(" So " + dividend +
				                  " divided by " + divisor +
				                  " using the Egyptian method is \n " + result +
				                  " remainder " + reminder);
				Console.WriteLine();
			}
		}
	}
}


Elementary cellular automaton

An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors.  Those three values can be encoded with three bits.

The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order.  Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.

;Task:
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state.  You can demonstrate your solution with any automaton of your choice.

The space state should ''wrap'':  this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.

This task is basically a generalization of [[one-dimensional cellular automata]].

;See also
* Cellular automata (natureofcode.com)

Solution:
using System;
using System.Collections;
namespace ElementaryCellularAutomaton
{
    class Automata
    {
        BitArray cells, ncells;
        const int MAX_CELLS = 19;

        public void run()
        {
            cells = new BitArray(MAX_CELLS);
            ncells = new BitArray(MAX_CELLS);
            while (true)
            {
                Console.Clear();
                Console.WriteLine("What Rule do you want to visualize");
                doRule(int.Parse(Console.ReadLine()));
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }
        }

        private byte getCells(int index)
        {
            byte b;
            int i1 = index - 1,
                i2 = index,
                i3 = index + 1;

            if (i1 < 0) i1 = MAX_CELLS - 1;
            if (i3 >= MAX_CELLS) i3 -= MAX_CELLS;

            b = Convert.ToByte(
                4 * Convert.ToByte(cells.Get(i1)) +
                2 * Convert.ToByte(cells.Get(i2)) +
                Convert.ToByte(cells.Get(i3)));
            return b;
        }

        private string getBase2(int i)
        {
            string s = Convert.ToString(i, 2);
            while (s.Length < 8)
            { s = "0" + s; }
            return s;
        }

        private void doRule(int rule)
        {
            Console.Clear();
            string rl = getBase2(rule);
            cells.SetAll(false);
            ncells.SetAll(false);
            cells.Set(MAX_CELLS / 2, true);

            Console.WriteLine("Rule: " + rule + "\n----------\n");

            for (int gen = 0; gen < 51; gen++)
            {
                Console.Write("{0, 4}", gen + ": ");

                foreach (bool b in cells)
                    Console.Write(b ? "#" : ".");

                Console.WriteLine("");

                int i = 0;
                while (true)
                {
                    byte b = getCells(i);
                    ncells[i] = '1' == rl[7 - b] ? true : false;
                    if (++i == MAX_CELLS) break;
                }

                i = 0;
                foreach (bool b in ncells)
                    cells[i++] = b;
            }
            Console.WriteLine("");
        }

    };
    class Program
    {
        static void Main(string[] args)
        {
            Automata t = new Automata();
            t.run();
        }
    }
}


Empty directory

Starting with a path to some directory, determine whether the directory is empty.

An empty directory contains no files nor subdirectories.
With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.

Solution:
using System;
using System.IO;

class Program
{
    static void Main( string[] args )
    {
        foreach ( string dir in args )
        {
            Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" );
        }
    }

    private static bool IsDirectoryEmpty( string dir )
    {
        return ( Directory.GetFiles( dir ).Length == 0 &&
            Directory.GetDirectories( dir ).Length == 0 );
    }
}


Empty string

Languages may have features for dealing specifically with empty strings
(those containing no characters).

;Task:
::*   Demonstrate how to assign an empty string to a variable.
::*   Demonstrate how to check that a string is empty.
::*   Demonstrate how to check that a string is not empty.

Solution:
using System;
using System.Collections.Generic;

static class Program
{
    // In short:
    public static void Foo()
    {
        string s;

        // Assign empty string:
        s = "";
        // or
        s = string.Empty;

        // Check for empty string only (false if s is null):
        if (s != null && s.Length == 0) { }

        // Check for null or empty (more idiomatic in .NET):
        if (string.IsNullOrEmpty(s)) { }
    }

    public static void Main()
    {
        // Equality is somewhat convoluted in .NET.
        // The methods above are the author's recommendation for each case.

        // s is initialized to null. It is a variable of the System.String type that is a null reference and is not
        // the empty string.
        string s = null;

        // Alias Console.WriteLine(bool) with a shorter name to make the demonstration code less verbose.
        Action<bool> P = Console.WriteLine;

        // Assign the empty string literal to s.
        s = "";

        // ' Assign String.Empty to s.
        s = string.Empty;

        // The empty string literal is the same object reference as String.Empty because of string interning, meaning the
        // behavior of the two is identical.
        // From this point on, "" will be used instead of String.Empty for brevity.

        //#== operator (object)
        // The == operator tests for reference equality when overload resolution fails to find an operator defined by
        // either operand type. However, which strings are interned is a CLR implementation detail and may be unreliable
        // when comparing non-empty strings. The equivalent in VB.NET would be s Is "".
        // Note that there is no such operator as Object.op_Equality(Object, Object): the use of the == operator for
        // types of type Object is a C# language feature.
        P((object)s == "");

        //#Object.ReferenceEquals(Object, Object)
        // The previous line is semantically to the following, though it does not involve a method call.
        P(object.ReferenceEquals(s, ""));

        //#String.op_Equality(String, String)
        // The equality operator of System.String is implemented as a call to String.Equals(String). Operators cannot be
        // called with method syntax in C#.
        P(s == "");

        //#String.Equals(String, String)
        // Call the static method defined on the String type, which first calls Object.ReferenceEquals and then, after
        // verifying that both are strings of the same length, compares the strings character-by-character.
        P(string.Equals(s, ""));

        //#Object.Equals(Object, Object)
        // First checks for reference equality and whether one or both of the arguments is null. It then invokes the
        // instance Equals method of the left parameter.
        P(object.Equals(s, ""));

        //#String.Equals(String)
        // The method is called with the string literal as the receiver because a NullReferenceException is thrown if s
        // is null.
        P("".Equals(s));

        //#String.Length
        // Check the Length property. The ?. (null-conditional) operator is used to avoid NullReferenceException. The Equals
        // call above can also be done this way. Null propagation makes the equality operator return false if one operand
        // is a Nullable<T> and does not have a value, making this result in false when s is null.
        P(s?.Length == 0);

        //#String.Length
        // A more traditional version of the null-conditional using a guard clause.
        // Both the null-conditional and this are noticeably (~4 times) faster than "".Equals(s). In general, it appears that
        // for empty strings, using the length is faster than using an equality comparison.
        P(s != null && s.Length == 0);

        //#String.IsNullOrEmpty(String)
        // Note that all of the other methods give false for null.
        // A static method of System.String that returns true if the string is null or its length is zero.
        P(string.IsNullOrEmpty(s));

        //#System.Collections.Generic.EqualityComparer(Of String).Default.Equals(String, String)
        // The EqualityComparer(Of T) class provides default implementations when an IEqualityComparer(Of T) is required.
        // The implementation for String calls String.Equals(String).
        P(EqualityComparer<string>.Default.Equals(s, ""));

        Console.WriteLine();

        // Each of the means described above, except testing for a non-empty string.
        P((object)s != "");
        P(!object.ReferenceEquals(s, ""));
        P(s != "");
        P(!string.Equals(s, ""));
        P(!object.Equals(s, ""));
        P(!"".Equals(s));
        P(s?.Length != 0); // Still false when s is null!
        P(s == null || s.Length != 0);
        P(!string.IsNullOrEmpty(s));
        P(!EqualityComparer<string>.Default.Equals(s, ""));
    }
}


Equilibrium index

An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.

For example, in a sequence   A:

:::::   A_0 = -7
:::::   A_1 =  1
:::::   A_2 =  5
:::::   A_3 =  2
:::::   A_4 = -4
:::::   A_5 =  3
:::::   A_6 =  0

3   is an equilibrium index, because:

:::::   A_0 + A_1 + A_2 = A_4 + A_5 + A_6

6   is also an equilibrium index, because:

:::::   A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0

(sum of zero elements is zero)

7   is not an equilibrium index, because it is not a valid index of sequence A.

;Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).

Assume that the sequence may be very long.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence)
    {
        var left = 0;
        var right = sequence.Sum();
        var index = 0;
        foreach (var element in sequence)
        {
            right -= element;
            if (left == right)
            {
                yield return index;
            }
            left += element;
            index++;
        }
    }

    static void Main()
    {
        foreach (var index in EquilibriumIndices(new[] { -7, 1, 5, 2, -4, 3, 0 }))
        {
            Console.WriteLine(index);
        }
    }
}


Euler's identity

{{Wikipedia|Euler's_identity}}

In mathematics, ''Euler's identity'' is the equality:

                ei\pi + 1 = 0

where

    e is Euler's number, the base of natural logarithms,
    ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and
    \pi is pi, the ratio of the circumference of a circle to its diameter.

Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:

    The number 0.
    The number 1.
    The number \pi (\pi = 3.14159+),
    The number e (e = 2.71828+), which occurs widely in mathematical analysis.
    The number ''i'', the imaginary unit of the complex numbers.

;Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.

Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.

If that is the case, or there is some other limitation, show
that ei\pi + 1 is ''approximately'' equal to zero and
show the amount of error in the calculation.

If your language is capable of symbolic calculations, show
that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.

Solution:
using System;
using System.Numerics;

public class Program
{
    static void Main() {
        Complex e = Math.E;
        Complex i = Complex.ImaginaryOne;
        Complex π = Math.PI;
        Console.WriteLine(Complex.Pow(e, i * π) + 1);
    }
}


Euler's sum of powers conjecture

There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.

This conjecture is called Euler's sum of powers conjecture and can be stated as such:

:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.

In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.

The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.

Related tasks are:
* [[Pythagorean quadruples]].
* [[Pythagorean triples]].

Solution:
using System;

namespace EulerSumOfPowers {
    class Program {
        const int MAX_NUMBER = 250;

        static void Main(string[] args) {
            bool found = false;
            long[] fifth = new long[MAX_NUMBER];

            for (int i = 1; i <= MAX_NUMBER; i++) {
                long i2 = i * i;
                fifth[i - 1] = i2 * i2 * i;
            }

            for (int a = 0; a < MAX_NUMBER && !found; a++) {
                for (int b = a; b < MAX_NUMBER && !found; b++) {
                    for (int c = b; c < MAX_NUMBER && !found; c++) {
                        for (int d = c; d < MAX_NUMBER && !found; d++) {
                            long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d];
                            int e = Array.BinarySearch(fifth, sum);
                            found = e >= 0;
                            if (found) {
                                Console.WriteLine("{0}^5 + {1}^5 + {2}^5 + {3}^5 = {4}^5", a + 1, b + 1, c + 1, d + 1, e + 1);
                            }
                        }
                    }
                }
            }
        }
    }
}


Euler's sum of powers conjecture

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Euler_cs
{
    class Program
    {
        struct Pair
        {
            public int a, b;
            public Pair(int x, int y)
            {
                a = x; b = y;
            }
        }

        static int min = 1, max = 250;
        static ulong[] p5;
        static SortedDictionary<ulong, Pair>[] sum2 =
                   new SortedDictionary<ulong, Pair>[30];

        static string Fmt(Pair p)
        {
            return string.Format("{0}^5 + {1}^5", p.a, p.b);
        }

        public static void InitM()
        {
            for (int i = 0; i <= 29; i++)
                sum2[i] = new SortedDictionary<ulong, Pair>();
            p5 = new ulong[max + 1];
            p5[min] = Convert.ToUInt64(min) * Convert.ToUInt64(min);
            p5[min] *= p5[min] * Convert.ToUInt64(min);
            for (int i = min; i <= max - 1; i++)
            {
                for (int j = i + 1; j <= max; j++)
                {
                    p5[j] = Convert.ToUInt64(j) * Convert.ToUInt64(j);
                    p5[j] *= p5[j] * Convert.ToUInt64(j);
                    if (j == max) continue;
                    ulong x = p5[i] + p5[j];
                    sum2[x % 30].Add(x, new Pair(i, j));
                }
            }
        }

        static List<string> CalcM(int m)
        {
            List<string> res = new List<string>();
            for (int i = max; i >= min; i--)
            {
                ulong p = p5[i]; int pm = i % 30, mp = (pm - m + 30) % 30;
                foreach (var s in sum2[m].Keys)
                {
                    if (p <= s) break;
                    ulong t = p - s;
                    if (sum2[mp].Keys.Contains(t) && sum2[mp][t].a > sum2[m][s].b)
                        res.Add(string.Format("  {1} + {2} = {0}^5",
                            i, Fmt(sum2[m][s]), Fmt(sum2[mp][t])));
                }
            }
            return res;
        }

        static int Snip(string s)
        {
            int p = s.IndexOf("=") + 1;
            return Convert.ToInt32(s.Substring(p, s.IndexOf("^", p) - p));
        }

        static int CompareRes(string x, string y)
        {
            int res = Snip(x).CompareTo(Snip(y));
            if (res == 0) res = x.CompareTo(y);
            return res;
        }

        static int Validify(int def, string s)
        {
            int res = def, t = 0; int.TryParse(s, out t);
            if (t >= 1 && t < Math.Pow((double)(ulong.MaxValue >> 1), 0.2))
                res = t;
            return res;
        }

        static void Switch(ref int a, ref int b)
        {
            int t = a; a = b; b = t;
        }

        static void Main(string[] args)
        {
            if (args.Count() > 1)
            {
                min = Validify(min, args[0]);
                max = Validify(max, args[1]);
                if (max < min) Switch(ref max, ref min);
            }
            else if (args.Count() == 1)
                max = Validify(max, args[0]);
            Console.WriteLine("Mod 30 shortcut with threading, checking from {0} to {1}...", min, max);
            List<string> res = new List<string>();
            DateTime st = DateTime.Now;
            List<Task<List<string>>> taskList = new List<Task<List<string>>>();
            InitM();
            for (int j = 0; j <= 29; j++)
            {
                var jj = j;
                taskList.Add(Task.Run(() => CalcM(jj)));
            }
            Task.WhenAll(taskList);
            foreach (var item in taskList.Select(t => t.Result))
                res.AddRange(item);
            res.Sort(CompareRes);
            foreach (var item in res)
                Console.WriteLine(item);
            Console.WriteLine("  Computation time to check entire space was {0} seconds",
                (DateTime.Now - st).TotalSeconds);
            if (System.Diagnostics.Debugger.IsAttached)
                Console.ReadKey();
        }
    }
}


Even or odd

Test whether an integer is even or odd.

There is more than one way to solve this task:

* Use the even and odd predicates, if the language provides them.
* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.
* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.
* Use modular congruences:
** ''i''  0 (mod 2) iff ''i'' is even.
** ''i''  1 (mod 2) iff ''i'' is odd.

Solution:
namespace RosettaCode
{
    using System;

    public static class EvenOrOdd
    {
        public static bool IsEvenBitwise(this int number)
        {
            return (number & 1) == 0;
        }

        public static bool IsOddBitwise(this int number)
        {
            return (number & 1) != 0;
        }

        public static bool IsEvenRemainder(this int number)
        {
            int remainder;
            Math.DivRem(number, 2, out remainder);
            return remainder == 0;
        }

        public static bool IsOddRemainder(this int number)
        {
            int remainder;
            Math.DivRem(number, 2, out remainder);
            return remainder != 0;
        }

        public static bool IsEvenModulo(this int number)
        {
            return (number % 2) == 0;
        }

        public static bool IsOddModulo(this int number)
        {
            return (number % 2) != 0;
        }
    }
    public class Program
    {
        public static void Main()
        {
            int num = 26;               //Set this to any integer.
            if (num.IsEvenBitwise())    //Replace this with any even function.
            {
                Console.Write("Even");
            }
            else
            {
                Console.Write("Odd");
            }
            //Prints "Even".
            if (num.IsOddBitwise())    //Replace this with any odd function.
            {
                Console.Write("Odd");
            }
            else
            {
                Console.Write("Even");
            }
            //Prints "Even".
        }
    }
}


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:
using System;
using System.Collections.Generic;
using System.Linq;

static class Program {
    static Random Rng = new Random((int)DateTime.Now.Ticks);

    static char NextCharacter(this Random self) {
        const string AllowedChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        return AllowedChars[self.Next() % AllowedChars.Length];
    }

    static string NextString(this Random self, int length) {
        return String.Join("", Enumerable.Repeat(' ', length)
            .Select(c => Rng.NextCharacter()));
    }

    static int Fitness(string target, string current) {
        return target.Zip(current, (a, b) => a == b ? 1 : 0).Sum();
    }

    static string Mutate(string current, double rate) {
        return String.Join("", from c in current
               select Rng.NextDouble() <= rate ? Rng.NextCharacter() : c);
    }

    static void Main(string[] args) {
        const string target = "METHINKS IT IS LIKE A WEASEL";
        const int C = 100;
        const double P = 0.05;

        // Start with a random string the same length as the target.
        string parent = Rng.NextString(target.Length);

        Console.WriteLine("START:       {0,20} fitness: {1}",
            parent, Fitness(target, parent));
        int i = 0;

        while (parent != target) {
            // Create C mutated strings + the current parent.
            var candidates = Enumerable.Range(0, C + 1)
                .Select(n => n > 0 ? Mutate(parent, P) : parent);

            // select the fittest
            parent = candidates.OrderByDescending(c => Fitness(target, c)).First();

            ++i;
            Console.WriteLine("     #{0,6} {1,20} fitness: {2}",
                i, parent, Fitness(target, parent));
        }

        Console.WriteLine("END: #{0,6} {1,20}", i, parent);
    }
}


Execute HQ9+

Implement a   ''' [[HQ9+]] '''   interpreter or compiler.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void RunCode(string code)
    {
        int accumulator = 0;
        var opcodes = new Dictionary<char, Action>
        {
            {'H', () => Console.WriteLine("Hello, World!"))},
            {'Q', () => Console.WriteLine(code) },
            {'9', () => Console.WriteLine(Enumerable.Range(1,100).Reverse().Select(n => string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around\n{1} bottles of beer on the wall\n", n, n-1)).Aggregate((a,b) => a + "\n" + b))},
            {'+', () => accumulator++ }
        }

        foreach(var c in code)
            opcodes[c]();
    }
}


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:   exponentiation

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

Solution:
using System;

namespace exponents
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * Like C, C# does not have an exponent operator.
             * Exponentiation is done via Math.Pow, which
             * only takes two arguments
             */
            Console.WriteLine(Math.Pow(Math.Pow(5, 3), 2));
            Console.WriteLine(Math.Pow(5, Math.Pow(3, 2)));
            Console.Read();
        }

    }
}


Extend your language

{{Control Structures}}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:
using System;
using System.Reflection;

namespace Extend_your_language
{

	class Program
	{

		public static void Main(string[] args)
		{
			Console.WriteLine();
			Console.WriteLine("Hello World!");
			Console.WriteLine();

			int x = 0;
			int y = 0;

			for(x=0;x<2;x++)
			{
				for(y=0;y<2;y++)
				{

					CONDITIONS( (x==0) , (y==0) ).
						IF2  ("METHOD1").
						ELSE1("METHOD2").
						ELSE2("METHOD3").
						ELSE ("METHOD4");

				}
			}

			Console.WriteLine();
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}

		public static void METHOD1()
		{
			Console.WriteLine("METHOD 1 executed - both are true");
		}

		public static void METHOD2()
		{
			Console.WriteLine("METHOD 2 executed - first is true");
		}

		public static void METHOD3()
		{
			Console.WriteLine("METHOD 3 executed - second is true");
		}

		public static void METHOD4()
		{
			Console.WriteLine("METHOD 4 executed - both are false");
		}

		static int CONDITIONS(bool condition1, bool condition2)
		{
			int c = 0;
			if(condition1 && condition2)
				c = 0;
			else if(condition1)
				c = 1;
			else if(condition2)
				c = 2;
			else
				c = 3;

			return c;
		}
	}

	public static class ExtensionMethods
	{

		public static int IF2(this int value, string method)
		{
			if(value == 0)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}

			return value;
		}

		public static int ELSE1(this int value, string method)
		{
			if(value == 1)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}

			return value;
		}

		public static int ELSE2(this int value, string method)
		{
			if(value == 2)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}

			return value;
		}

		public static void ELSE(this int value, string method)
		{
			if(value == 3)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}
		}

	}
}


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:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Program
{
    public class FastaEntry
    {
        public string Name { get; set; }
        public StringBuilder Sequence { get; set; }
    }

    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
    {
        FastaEntry f = null;
        string line;
        while ((line = fastaFile.ReadLine()) != null)
        {
            // ignore comment lines
            if (line.StartsWith(";"))
                continue;

            if (line.StartsWith(">"))
            {
                if (f != null)
                    yield return f;
                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
            }
            else if (f != null)
                f.Sequence.Append(line);
        }
        yield return f;
    }

    static void Main(string[] args)
    {
        try
        {
            using (var fastaFile = new StreamReader("fasta.txt"))
            {
                foreach (FastaEntry f in ParseFasta(fastaFile))
                    Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e);
        }
        Console.ReadLine();
    }
}


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 x 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          Farey sequence
*   Wikipedia   entry   Farey sequence

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

public static class FareySequence
{
    public static void Main() {
        for (int i = 1; i <= 11; i++) {
            Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}")));
        }
        for (int i = 100; i <= 1000; i+=100) {
            Console.WriteLine($"F{i} has {Generate(i).Count()} terms.");
        }
    }

    public static IEnumerable<(int num, int den)> Generate(int i) {
        var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n));
        var seq = new SortedSet<(int n, int d)>(comparer);
        for (int d = 1; d <= i; d++) {
            for (int n = 0; n <= d; n++) {
                seq.Add((n, d));
            }
        }
        return seq;
    }
}


Fast Fourier transform

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. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.

Solution:
using System;
using System.Numerics;
using System.Linq;
using System.Diagnostics;

// Fast Fourier Transform in C#
public class Program {

    /* Performs a Bit Reversal Algorithm on a postive integer
     * for given number of bits
     * e.g. 011 with 3 bits is reversed to 110 */
    public static int BitReverse(int n, int bits) {
       int reversedN = n;
       int count = bits - 1;

       n >>= 1;
       while (n > 0) {
            reversedN = (reversedN << 1) | (n & 1);
            count--;
            n >>= 1;
        }

        return ((reversedN << count) & ((1 << bits) - 1));
    }

    /* Uses Cooley-Tukey iterative in-place algorithm with radix-2 DIT case
     * assumes no of points provided are a power of 2 */
    public static void FFT(Complex[] buffer) {
#if false
        int bits = (int)Math.Log(buffer.Length, 2);
        for (int j = 1; j < buffer.Length / 2; j++) {

            int swapPos = BitReverse(j, bits);
            var temp = buffer[j];
            buffer[j] = buffer[swapPos];
            buffer[swapPos] = temp;
        }
// Said Zandian
// The above section of the code is incorrect and does not work correctly and has two bugs.
// BUG 1
// The bug is that when you reach and index that was swapped previously it does swap it again
// Ex. binary value n = 0010 and Bits = 4 as input to BitReverse routine and  returns 4. The code section above //     swaps it. Cells 2 and 4 are swapped. just fine.
//     now binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 2. The code Section
//     swap it. Cells 4 and 2 are swapped.     WROOOOONG
//
// Bug 2
// The code works on the half section of the cells. In the case of Bits = 4 it means that we are having 16 cells
// The code works on half the cells        for (int j = 1; j < buffer.Length / 2; j++) buffer.Length returns 16
// and divide by 2 makes 8, so j goes from 1 to 7. This covers almost everything but what happened to 1011 value
// which must be swap with 1101. and this is the second bug.
//
// use the following corrected section of the code. I have seen this bug in other languages that uses bit
// reversal routine.

#else
            for (int j = 1; j < buffer.Length; j++)
            {
                int swapPos = BitReverse(j, bits);
                if (swapPos <= j)
                {
                    continue;
                }
                var temp = buffer[j];
                buffer[j] = buffer[swapPos];
                buffer[swapPos] = temp;
            }

// First the full length is used and 1011 value is swapped with 1101. Second if new swapPos is less than j
// then it means that swap was happen when j was the swapPos.

#endif

        for (int N = 2; N <= buffer.Length; N <<= 1) {
            for (int i = 0; i < buffer.Length; i += N) {
                for (int k = 0; k < N / 2; k++) {

                    int evenIndex = i + k;
                    int oddIndex = i + k + (N / 2);
                    var even = buffer[evenIndex];
                    var odd = buffer[oddIndex];

                    double term = -2 * Math.PI * k / (double)N;
                    Complex exp = new Complex(Math.Cos(term), Math.Sin(term)) * odd;

                    buffer[evenIndex] = even + exp;
                    buffer[oddIndex] = even - exp;

                }
            }
        }
    }

    public static void Main(string[] args) {
        Complex[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};

        FFT(input);

        Console.WriteLine("Results:");
        foreach (Complex c in input) {
            Console.WriteLine(c);
        }
    }
}


Feigenbaum constant calculation

Calculate the Feigenbaum constant.

;See:
:*   Details in the Wikipedia article:   Feigenbaum constant.

Solution:
using System;

namespace FeigenbaumConstant {
    class Program {
        static void Main(string[] args) {
            var maxIt = 13;
            var maxItJ = 10;
            var a1 = 1.0;
            var a2 = 0.0;
            var d1 = 3.2;
            Console.WriteLine(" i       d");
            for (int i = 2; i <= maxIt; i++) {
                var a = a1 + (a1 - a2) / d1;
                for (int j = 1; j <= maxItJ; j++) {
                    var x = 0.0;
                    var y = 0.0;
                    for (int k = 1; k <= 1<<i; k++) {
                        y = 1.0 - 2.0 * y * x;
                        x = a - x * x;
                    }
                    a -= x / y;
                }
                var d = (a1 - a2) / (a - a1);
                Console.WriteLine("{0,2:d}    {1:f8}", 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]]
*   Wolfram Mathworld
*   [[Hofstadter Q sequence]]
*   [[Leonardo numbers]]

;Also see:
*   Lucas Numbers - Numberphile (Video)
*   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
*   Wikipedia, Lucas number
*   MathWorld, Fibonacci Number
*   Some identities for r-Fibonacci numbers
*   OEIS Fibonacci numbers
*   OEIS Lucas numbers

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fibonacci
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10));
            PrintNumberSequence("Lucas", GetLucasNumbers(10));
            PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10));
            PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10));
            Console.ReadKey();
        }

        private static IList<ulong> GetLucasNumbers(int length)
        {
            IList<ulong> seedSequence = new List<ulong>() { 2, 1 };
            return GetFibLikeSequence(seedSequence, length);
        }

        private static IList<ulong> GetNnacciNumbers(int seedLength, int length)
        {
            return GetFibLikeSequence(GetNacciSeed(seedLength), length);
        }

        private static IList<ulong> GetNacciSeed(int seedLength)
        {
            IList<ulong> seedSquence = new List<ulong>() { 1 };

            for (uint i = 0; i < seedLength - 1; i++)
            {
                seedSquence.Add((ulong)Math.Pow(2, i));
            }

            return seedSquence;
        }

        private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
        {
            IList<ulong> sequence = new List<ulong>();

            int count = seedSequence.Count();

            if (length <= count)
            {
                sequence = seedSequence.Take((int)length).ToList();
            }
            else
            {
                sequence = seedSequence;

                for (int i = count; i < length; i++)
                {
                    ulong num = 0;

                    for (int j = 0; j < count; j++)
                    {
                        num += sequence[sequence.Count - 1 - j];
                    }

                    sequence.Add(num);
                }
            }

            return sequence;
        }

        private static void PrintNumberSequence(string Title, IList<ulong> numbersequence)
        {
            StringBuilder output = new StringBuilder(Title).Append("   ");

            foreach (long item in numbersequence)
            {
                output.AppendFormat("{0}, ", item);
            }

            Console.WriteLine(output.ToString());
        }
    }
}


Fibonacci word

The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence    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:
using SYS = System;
using SCG = System.Collections.Generic;

//
// Basically a port of the C++ solution as posted
// 2017-11-12.
//
namespace FibonacciWord
{
  class Program
  {
    static void Main( string[] args )
    {
      PrintHeading();
      string firstString = "1";
      int n = 1;
      PrintLine( n, firstString );
      string secondString = "0";
      ++n;
      PrintLine( n, secondString );
      while ( n < 37 )
      {
        string resultString = firstString + secondString;
        firstString = secondString;
        secondString = resultString;
        ++n;
        PrintLine( n, resultString );
      }
    }

    private static void PrintLine( int n, string result )
    {
      SYS.Console.Write( "{0,-5}", n );
      SYS.Console.Write( "{0,12}", result.Length );
      SYS.Console.WriteLine( "  {0,-16}", GetEntropy( result ) );
    }

    private static double GetEntropy( string result )
    {
      SCG.Dictionary<char, int> frequencies = new SCG.Dictionary<char, int>();
      foreach ( char c in result )
      {
        if ( frequencies.ContainsKey( c ) )
        {
          ++frequencies[c];
        }
        else
        {
          frequencies[c] = 1;
        }
      }

      int length = result.Length;
      double entropy = 0;
      foreach ( var keyValue in frequencies )
      {
        double freq = (double)keyValue.Value / length;
        entropy += freq * SYS.Math.Log( freq, 2 );
      }

      return -entropy;
    }

    private static void PrintHeading()
    {
      SYS.Console.Write( "{0,-5}", "N" );
      SYS.Console.Write( "{0,12}", "Length" );
      SYS.Console.WriteLine( "  {0,-16}", "Entropy" );
    }
  }
}


Find limit of recursion

{{selection|Short Circuit|Console Program Basics}}

;Task:
Find the limit of recursion.

Solution:
using System;
class RecursionLimit
{
  static void Main(string[] args)
  {
    Recur(0);
  }

  private static void Recur(int i)
  {
    Console.WriteLine(i);
    Recur(i + 1);
  }
}


Find palindromic numbers in both binary and ternary bases

*   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   ''both'':
:::*   base 2
:::*   base 3
*   Display   '''0'''   (zero) as the first number found, even though some other definitions ignore it.
*   Optionally, show the decimal number found in its binary and ternary form.
*   Show all output here.

It's permissible to assume the first two numbers and simply list them.

;See also
*   Sequence A60792,   numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;

public class FindPalindromicNumbers
{
    static void Main(string[] args)
    {
        var query =
            PalindromicTernaries()
            .Where(IsPalindromicBinary)
            .Take(6);
        foreach (var x in query) {
            Console.WriteLine("Decimal: " + x);
            Console.WriteLine("Ternary: " + ToTernary(x));
            Console.WriteLine("Binary: " + Convert.ToString(x, 2));
            Console.WriteLine();
        }
    }

    public static IEnumerable<long> PalindromicTernaries() {
        yield return 0;
        yield return 1;
        yield return 13;
        yield return 23;

        var f = new List<long> {0};
        long fMiddle = 9;
        while (true) {
            for (long edge = 1; edge < 3; edge++) {
                int i;
                do {
                    //construct the result
                    long result = fMiddle;
                    long fLeft = fMiddle * 3;
                    long fRight = fMiddle / 3;
                    for (int j = f.Count - 1; j >= 0; j--) {
                        result += (fLeft + fRight) * f[j];
                        fLeft *= 3;
                        fRight /= 3;
                    }
                    result += (fLeft + fRight) * edge;
                    yield return result;

                    //next permutation
                    for (i = f.Count - 1; i >= 0; i--) {
                        if (f[i] == 2) {
                            f[i] = 0;
                        } else {
                            f[i]++;
                            break;
                        }
                    }
                } while (i >= 0);
            }
            f.Add(0);
            fMiddle *= 3;
        }
    }

    public static bool IsPalindromicBinary(long number) {
        long n = number;
        long reverse = 0;
        while (n != 0) {
            reverse <<= 1;
            if ((n & 1) == 1) reverse++;
            n >>= 1;
        }
        return reverse == number;
    }

    public static string ToTernary(long n)
    {
        if (n == 0) return "0";
        string result = "";
        while (n > 0) {        {
            result = (n % 3) + result;
            n /= 3;
        }
        return result;
    }

}


Find the intersection of a line with a plane

Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.

;Task:
Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].

Solution:
using System;

namespace FindIntersection {
    class Vector3D {
        private double x, y, z;

        public Vector3D(double x, double y, double z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public static Vector3D operator +(Vector3D lhs, Vector3D rhs) {
            return new Vector3D(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z);
        }

        public static Vector3D operator -(Vector3D lhs, Vector3D rhs) {
            return new Vector3D(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
        }

        public static Vector3D operator *(Vector3D lhs, double rhs) {
            return new Vector3D(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs);
        }

        public double Dot(Vector3D rhs) {
            return x * rhs.x + y * rhs.y + z * rhs.z;
        }

        public override string ToString() {
            return string.Format("({0:F}, {1:F}, {2:F})", x, y, z);
        }
    }

    class Program {
        static Vector3D IntersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) {
            var diff = rayPoint - planePoint;
            var prod1 = diff.Dot(planeNormal);
            var prod2 = rayVector.Dot(planeNormal);
            var prod3 = prod1 / prod2;
            return rayPoint - rayVector * prod3;
        }

        static void Main(string[] args) {
            var rv = new Vector3D(0.0, -1.0, -1.0);
            var rp = new Vector3D(0.0, 0.0, 10.0);
            var pn = new Vector3D(0.0, 0.0, 1.0);
            var pp = new Vector3D(0.0, 0.0, 5.0);
            var ip = IntersectPoint(rv, rp, pn, pp);
            Console.WriteLine("The ray intersects the plane at {0}", ip);
        }
    }
}


Find the intersection of two lines

Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]

;Task:
Find the point of intersection of two lines in 2D.

The 1st     line passes though    (4,0)    and    (6,10) .
The 2nd line passes though    (0,3)    and    (10,7) .

Solution:
using System;
using System.Drawing;
public class Program
{
    static PointF FindIntersection(PointF s1, PointF e1, PointF s2, PointF e2) {
        float a1 = e1.Y - s1.Y;
        float b1 = s1.X - e1.X;
        float c1 = a1 * s1.X + b1 * s1.Y;

        float a2 = e2.Y - s2.Y;
        float b2 = s2.X - e2.X;
        float c2 = a2 * s2.X + b2 * s2.Y;

        float delta = a1 * b2 - a2 * b1;
        //If lines are parallel, the result will be (NaN, NaN).
        return delta == 0 ? new PointF(float.NaN, float.NaN)
            : new PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta);
    }

    static void Main() {
        Func<float, float, PointF> p = (x, y) => new PointF(x, y);
        Console.WriteLine(FindIntersection(p(4f, 0f), p(6f, 10f), p(0f, 3f), p(10f, 7f)));
        Console.WriteLine(FindIntersection(p(0f, 0f), p(1f, 1f), p(1f, 2f), p(4f, 5f)));
    }
}


Find the last Sunday of each month

Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29

;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]

Solution:
using System;

namespace LastSundayOfEachMonth
{
    class Program
    {
        static void Main()
        {
            Console.Write("Year to calculate: ");

            string strYear = Console.ReadLine();
            int year = Convert.ToInt32(strYear);

            DateTime date;
            for (int i = 1; i <= 12; i++)
            {
                date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar);
                /* Modification by Albert Zakhia on 2021-16-02
                   The below code is very slow due to the loop, we will go twice as fast
                while (date.DayOfWeek != DayOfWeek.Sunday)
                {
                    date = date.AddDays(-1);
                }
                */
                // The updated code
                int daysOffset = date.DayOfWeek - dayOfWeek; // take the offset to subtract directly instead of looping
                if (daysOffset < 0) daysOffset += 7; // if the code is negative, we need to normalize them
                date = date.AddDays(-daysOffset ); // now just add the days offset
                Console.WriteLine(date.ToString("yyyy-MM-dd"));
            }
        }
    }
}


Find the missing permutation

ABCD
                    CABD
                    ACDB
                    DACB
                    BCDA
                    ACBD
                    ADCB
                    CDAB
                    DABC
                    BCAD
                    CADB
                    CDBA
                    CBAD
                    ABDC
                    ADBC
                    BDCA
                    DCBA
                    BACD
                    BADC
                    BDAC
                    CBDA
                    DBCA
                    DCAB

Listed above are   all-but-one   of the permutations of the symbols   '''A''',   '''B''',   '''C''',   and   '''D''',   ''except''   for one permutation that's   ''not''   listed.

;Task:
Find that missing permutation.

;Methods:
* Obvious method:
         enumerate all permutations of   '''A''',  '''B''',  '''C''',  and  '''D''',
         and then look for the missing permutation.

* alternate method:
         Hint:  if all permutations were shown above,  how many
         times would  '''A'''  appear in each position?
         What is the  ''parity''  of this number?

* another alternate method:
         Hint:  if you add up the letter values of each column,
         does a missing letter   '''A''',  '''B''',  '''C''',  and  '''D'''   from each
         column cause the total value for each column to be unique?

;Related task:
*   [[Permutations]])

Solution:
using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var input = new [] {"ABCD","CABD","ACDB","DACB","BCDA",
            "ACBD","ADCB","CDAB","DABC","BCAD","CADB",
            "CDBA","CBAD","ABDC","ADBC","BDCA","DCBA",
            "BACD","BADC","BDAC","CBDA","DBCA","DCAB"};

        int[] values = {0,0,0,0};
        foreach (string s in input)
            for (int i = 0; i < 4; i++)
                values[i] ^= s[i];
        Console.WriteLine(string.Join("", values.Select(i => (char)i)));
    }
}


First-class functions/Use numbers analogously

In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.

This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.

Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
   x  = 2.0
   xi = 0.5
   y  = 4.0
   yi = 0.25
   z  = x + y
   zi = 1.0 / ( x + y )

Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
  new_function = multiplier(n1,n2)
  # where new_function(m) returns the result of n1 * n2 * m

Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.

To paraphrase the task description: Do what was done before, but with numbers rather than functions

Solution:
using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        double x, xi, y, yi, z, zi;
        x = 2.0;
        xi = 0.5;
        y = 4.0;
        yi = 0.25;
        z = x + y;
        zi = 1.0 / (x + y);

        var numlist = new[] { x, y, z };
        var numlisti = new[] { xi, yi, zi };
        var multiplied = numlist.Zip(numlisti, (n1, n2) =>
                       {
                           Func<double, double> multiplier = m => n1 * n2 * m;
                           return multiplier;
                       });

        foreach (var multiplier in multiplied)
            Console.WriteLine(multiplier(0.5));
    }
}


First perfect square in base n with n unique digits

Find the first perfect square in a given base '''N''' that has at least '''N''' digits and
exactly '''N''' ''significant unique'' digits when expressed in base '''N'''.

E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').

You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.

;Task

* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.

* (optional) Do the same for bases '''13''' through '''16'''.

* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)

;See also:

;* OEIS A260182: smallest square that is pandigital in base n.

;Related task

;* [[Casting out nines]]

Solution:
using System;
using System.Collections.Generic;
using System.Numerics;

static class Program
{
    static byte Base, bmo, blim, ic; static DateTime st0; static BigInteger bllim, threshold;
    static HashSet<byte> hs = new HashSet<byte>(), o = new HashSet<byte>();
    static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|";
    static List<BigInteger> limits;
    static string ms;

    // convert BigInteger to string using current base
    static string toStr(BigInteger b) {
        string res = ""; BigInteger re; while (b > 0) {
            b = BigInteger.DivRem(b, Base, out re); res = chars[(byte)re] + res;
        } return res;
    }

    // check for a portion of digits, bailing if uneven
    static bool allInQS(BigInteger b) {
        BigInteger re; int c = ic; hs.Clear(); hs.UnionWith(o); while (b > bllim) {
            b = BigInteger.DivRem(b, Base, out re);
            hs.Add((byte)re); c += 1; if (c > hs.Count) return false;
        } return true;
    }

    // check for a portion of digits, all the way to the end
    static bool allInS(BigInteger b) {
        BigInteger re; hs.Clear(); hs.UnionWith(o); while (b > bllim) {
            b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re);
        } return hs.Count == Base;
    }

    // check for all digits, bailing if uneven
    static bool allInQ(BigInteger b) {
        BigInteger re; int c = 0; hs.Clear(); while (b > 0) {
            b = BigInteger.DivRem(b, Base, out re);
            hs.Add((byte)re); c += 1; if (c > hs.Count) return false;
        } return true;
    }

    // check for all digits, all the way to the end
    static bool allIn(BigInteger b) {
        BigInteger re; hs.Clear(); while (b > 0) {
            b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re);
        } return hs.Count == Base;
    }

    // parse a string into a BigInteger, using current base
    static BigInteger to10(string s) {
        BigInteger res = 0; foreach (char i in s) res = res * Base + chars.IndexOf(i);
        return res;
    }

    // returns the minimum value string, optionally inserting extra digit
    static string fixup(int n) {
        string res = chars.Substring(0, Base); if (n > 0) res = res.Insert(n, n.ToString());
        return "10" + res.Substring(2);
    }

    // checks the square against the threshold, advances various limits when needed
    static void check(BigInteger sq) {
        if (sq > threshold) {
            o.Remove((byte)chars.IndexOf(ms[blim])); blim -= 1; ic -= 1;
            threshold = limits[bmo - blim - 1]; bllim = to10(ms.Substring(0, blim + 1));
        }
    }

    // performs all the caclulations for the current base
    static void doOne() {
        limits = new List<BigInteger>();
        bmo = (byte)(Base - 1); byte dr = 0; if ((Base & 1) == 1) dr = (byte)(Base >> 1);
        o.Clear(); blim = 0;
        byte id = 0; int inc = 1; long i = 0; DateTime st = DateTime.Now; if (Base == 2) st0 = st;
        byte[] sdr = new byte[bmo]; byte rc = 0; for (i = 0; i < bmo; i++) {
            sdr[i] = (byte)((i * i) % bmo); rc += sdr[i] == dr ? (byte)1 : (byte)0;
            sdr[i] += sdr[i] == 0 ? bmo : (byte)0;
        } i = 0; if (dr > 0) {
            id = Base;
            for (i = 1; i <= dr; i++) if (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr;
            i = 0;
        } ms = fixup(id);
        BigInteger sq = to10(ms); BigInteger rt = new BigInteger(Math.Sqrt((double)sq) + 1);
        sq = rt * rt; if (Base > 9) {
            for (int j = 1; j < Base; j++)
                limits.Add(to10(ms.Substring(0, j) + new string(chars[bmo], Base - j + (rc > 0 ? 0 : 1))));
            limits.Reverse(); while (sq < limits[0]) { rt++; sq = rt * rt; }
        }
        BigInteger dn = (rt << 1) + 1; BigInteger d = 1; if (Base > 3 && rc > 0) {
            while (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } // alligns sq to dr
            inc = bmo / rc;
            if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; }
            dn += dn + d;
        }
        d <<= 1; if (Base > 9) {
            blim = 0; while (sq < limits[bmo - blim - 1]) blim++; ic = (byte)(blim + 1);
            threshold = limits[bmo - blim - 1];
            if (blim > 0) for (byte j = 0; j <= blim; j++) o.Add((byte)chars.IndexOf(ms[j]));
            if (blim > 0) bllim = to10(ms.Substring(0, blim + 1)); else bllim = 0;
            if (Base > 5 && rc > 0)
                do { if (allInQS(sq)) break; sq += dn; dn += d; i += 1; check(sq); } while (true);
            else
                do { if (allInS(sq)) break; sq += dn; dn += d; i += 1; check(sq); } while (true);
        } else {
            if (Base > 5 && rc > 0)
                do { if (allInQ(sq)) break; sq += dn; dn += d; i += 1; } while (true);
            else
                do { if (allIn(sq)) break; sq += dn; dn += d; i += 1; } while (true);
        } rt += i * inc;
        Console.WriteLine("{0,3}  {1,2}  {2,2} {3,20} -> {4,-40} {5,10} {6,9:0.0000}s  {7,9:0.0000}s",
            Base, inc, (id > 0 ? chars.Substring(id, 1) : " "), toStr(rt), toStr(sq), i,
            (DateTime.Now - st).TotalSeconds, (DateTime.Now - st0).TotalSeconds);
    }

    static void Main(string[] args) {
        Console.WriteLine("base inc id                 root    square" +
            "                                   test count    time        total");
        for (Base = 2; Base <= 28; Base++) doOne();
        Console.WriteLine("Elasped time was {0,8:0.00} minutes", (DateTime.Now - st0).TotalMinutes);
    }
}


First power of 2 that has leading decimal digits of 12

Solution:
// a mini chrestomathy solution

using System;

class Program {

    // translated from java example
    static long js(int l, int n) {
        long res = 0, f = 1;
        double lf = Math.Log10(2);
        for (int i = l; i > 10; i /= 10) f *= 10;
        while (n > 0)
            if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--;
        return res;
    }

    // translated from go integer example (a.k.a. go translation of pascal alternative example)
    static long gi(int ld, int n) {
        string Ls = ld.ToString();
        long res = 0, count = 0, f = 1;
        for (int i = 1; i <= 18 - Ls.Length; i++) f *= 10;
        const long ten18 = (long)1e18; long probe = 1;
        do {
            probe <<= 1; res++; if (probe >= ten18)
                do {
                    if (probe >= ten18) probe /= 10;
                    if (probe / f == ld)
                        if (++count >= n) { count--; break; }
                    probe <<= 1; res++;
                } while (true);
            string ps = probe.ToString();
            if (ps.Substring(0, Math.Min(Ls.Length, ps.Length)) == Ls)
                if (++count >= n) break;
        } while (true);
        return res;
    }

    // translated from pascal alternative example
    static long pa(int ld, int n) {
        double L_float64 = Math.Pow(2, 64);
        ulong Log10_2_64 = (ulong)(L_float64 * Math.Log10(2));
        double Log10Num; ulong LmtUpper, LmtLower, Frac64;
        long res = 0, dgts = 1, cnt;
        for (int i = ld; i >= 10; i /= 10) dgts *= 10;
        Log10Num = Math.Log10((ld + 1.0) / dgts);
        // '316' was a limit
        if (Log10Num >= 0.5) {
            LmtUpper = (ld + 1.0) / dgts < 10.0 ? (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2) : 0;
            Log10Num = Math.Log10((double)ld / dgts);
            LmtLower = (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2);
        } else {
            LmtUpper = (ulong)(Log10Num * L_float64);
            LmtLower = (ulong)(Math.Log10((double)ld / dgts) * L_float64);
        }
        cnt = 0; Frac64 = 0; if (LmtUpper != 0)
            do {
                res++; Frac64 += Log10_2_64;
                if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper))
                    if (++cnt >= n) break;
            } while (true);
        else // '999..'
            do {
                res++; Frac64 += Log10_2_64;
                if (Frac64 >= LmtLower) if (++cnt >= n) break;
            } while (true);
        return res;
    }

    static int[] values = new int[] { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 };

    static void doOne(string name, Func<int, int, long> fun) {
        Console.WriteLine("{0} version:", name);
        var start = DateTime.Now;
        for (int i = 0; i < values.Length; i += 2)
            Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", values[i], values[i + 1], fun(values[i], values[i + 1]));
        Console.WriteLine("Took {0} seconds\n", DateTime.Now - start);
    }

    static void Main() {
        doOne("java simple", js);
        doOne("go integer", gi);
        doOne("pascal alternative", pa);
    }
}


Fivenum

Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory.

For example, the   '''R'''   programming language implements Tukey's five-number summary as the '''fivenum''' function.

;Task:
Given an array of numbers, compute the five-number summary.

;Note:
While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data.

Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fivenum {
    public static class Helper {
        public static string AsString<T>(this ICollection<T> c, string format = "{0}") {
            StringBuilder sb = new StringBuilder("[");
            int count = 0;
            foreach (var t in c) {
                if (count++ > 0) {
                    sb.Append(", ");
                }
                sb.AppendFormat(format, t);
            }
            return sb.Append("]").ToString();
        }
    }

    class Program {
        static double Median(double[] x, int start, int endInclusive) {
            int size = endInclusive - start + 1;
            if (size <= 0) throw new ArgumentException("Array slice cannot be empty");
            int m = start + size / 2;
            return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0;
        }

        static double[] Fivenum(double[] x) {
            foreach (var d in x) {
                if (Double.IsNaN(d)) {
                    throw new ArgumentException("Unable to deal with arrays containing NaN");
                }
            }
            double[] result = new double[5];
            Array.Sort(x);
            result[0] = x.First();
            result[2] = Median(x, 0, x.Length - 1);
            result[4] = x.Last();
            int m = x.Length / 2;
            int lowerEnd = (x.Length % 2 == 1) ? m : m - 1;
            result[1] = Median(x, 0, lowerEnd);
            result[3] = Median(x, m, x.Length - 1);
            return result;
        }

        static void Main(string[] args) {
            double[][] x1 = new double[][]{
                new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},
                new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0},
                new double[]{
                     0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
                    -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
                    -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
                     0.75775634,  0.32566578
                },
            };
            foreach(var x in x1) {
                var result = Fivenum(x);
                Console.WriteLine(result.AsString("{0:F8}"));
            }
        }
    }
}


Flatten a list

Write a function to flatten the nesting in an arbitrary list of values.

Your program should work on the equivalent of this list:
   [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
    [1, 2, 3, 4, 5, 6, 7, 8]

;Related task:
*   [[Tree traversal]]

Solution:
public static class Ex {
		public static List<object> Flatten(this List<object> list) {

			var result = new List<object>();
			foreach (var item in list) {
				if (item is List<object>) {
					result.AddRange(Flatten(item as List<object>));
				} else {
					result.Add(item);
				}
			}
			return result;
		}
		public static string Join<T>(this List<T> list, string glue) {
			return string.Join(glue, list.Select(i => i.ToString()).ToArray());
		}
	}

	class Program {

		static void Main(string[] args) {
			var list = new List<object>{new List<object>{1}, 2, new List<object>{new List<object>{3,4}, 5}, new List<object>{new List<object>{new List<object>{}}}, new List<object>{new List<object>{new List<object>{6}}}, 7, 8, new List<object>{}};

			Console.WriteLine("[" + list.Flatten().Join(", ") + "]");
			Console.ReadLine();
		}
	}


Floyd's triangle

Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where
* the first row is   '''1'''     (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.

The first few lines of a Floyd triangle looks like this:

 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

;Task:
:# Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.

Solution:
using System;
using System.Text;

public class FloydsTriangle
{
    internal static void Main(string[] args)
    {
        int count;
        if (args.Length >= 1 && int.TryParse(args[0], out count) && count > 0)
        {
            Console.WriteLine(MakeTriangle(count));
        }
        else
        {
            Console.WriteLine(MakeTriangle(5));
            Console.WriteLine();
            Console.WriteLine(MakeTriangle(14));
        }
    }

    public static string MakeTriangle(int rows)
    {
        int maxValue = (rows * (rows + 1)) / 2;
        int digit = 0;
        StringBuilder output = new StringBuilder();

        for (int row = 1; row <= rows; row++)
        {
            for (int column = 0; column < row; column++)
            {
                int colMaxDigit = (maxValue - rows) + column + 1;
                if (column > 0)
                {
                    output.Append(' ');
                }

                digit++;
                output.Append(digit.ToString().PadLeft(colMaxDigit.ToString().Length));
            }

            output.AppendLine();
        }

        return output.ToString();
    }
}


Four bit adder

"''Simulate''" a four-bit adder.

This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;

Finally a half adder can be made using an   ''xor''   gate and an   ''and''   gate.

The   ''xor''   gate can be made using two   ''not''s,   two   ''and''s   and one   ''or''.

'''Not''',   '''or'''   and   '''and''',   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.

If there is not a ''bit type'' in your language, to be sure that the   ''not''   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   ''nand''   (''and''   then   ''not'')   with the constant   '''1'''   on one input.

Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   ''connecting'' the other "constructive blocks",   in turn made of "simpler" and "smaller" ones.

{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
!   (A half adder)
!          (A full adder)
!                (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}

Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".

It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.

To test the implementation, show the sum of two four-bit numbers (in binary).

Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RosettaCodeTasks.FourBitAdder
{
	public struct BitAdderOutput
	{
		public bool S { get; set; }
		public bool C { get; set; }
		public override string ToString ( )
		{
			return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" );
		}
	}
	public struct Nibble
	{
		public bool _1 { get; set; }
		public bool _2 { get; set; }
		public bool _3 { get; set; }
		public bool _4 { get; set; }
		public override string ToString ( )
		{
			return ( _4 ? "1" : "0" )
				+ ( _3 ? "1" : "0" )
				+ ( _2 ? "1" : "0" )
				+ ( _1 ? "1" : "0" );
		}
	}
	public struct FourBitAdderOutput
	{
		public Nibble N { get; set; }
		public bool C { get; set; }
		public override string ToString ( )
		{
			return N.ToString ( ) + "c" + ( C ? "1" : "0" );
		}
	}

	public static class LogicGates
	{
		// Basic Gates
		public static bool Not ( bool A ) { return !A; }
		public static bool And ( bool A, bool B ) { return A && B; }
		public static bool Or ( bool A, bool B ) { return A || B; }

		// Composite Gates
		public static bool Xor ( bool A, bool B ) {	return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }
	}

	public static class ConstructiveBlocks
	{
		public static BitAdderOutput HalfAdder ( bool A, bool B )
		{
			return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };
		}

		public static BitAdderOutput FullAdder ( bool A, bool B, bool CI )
		{
			BitAdderOutput HA1 = HalfAdder ( CI, A );
			BitAdderOutput HA2 = HalfAdder ( HA1.S, B );

			return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };
		}

		public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )
		{

			BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );
			BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );
			BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );
			BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );

			return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };
		}

		public static void Test ( )
		{
			Console.WriteLine ( "Four Bit Adder" );

			for ( int i = 0; i < 256; i++ )
			{
				Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
				Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
				if ( (i & 1) == 1)
				{
					A._1 = true;
				}
				if ( ( i & 2 ) == 2 )
				{
					A._2 = true;
				}
				if ( ( i & 4 ) == 4 )
				{
					A._3 = true;
				}
				if ( ( i & 8 ) == 8 )
				{
					A._4 = true;
				}
				if ( ( i & 16 ) == 16 )
				{
					B._1 = true;
				}
				if ( ( i & 32 ) == 32)
				{
					B._2 = true;
				}
				if ( ( i & 64 ) == 64 )
				{
					B._3 = true;
				}
				if ( ( i & 128 ) == 128 )
				{
					B._4 = true;
				}

				Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );

			}

			Console.WriteLine ( );
		}

	}
}


Function prototype

Some languages provide the facility to declare functions and subroutines through the use of function prototyping.

;Task:
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:

* An explanation of any placement restrictions for prototype declarations
* A prototype declaration for a function that does not require arguments
* A prototype declaration for a function that requires two arguments
* A prototype declaration for a function that utilizes varargs
* A prototype declaration for a function that utilizes optional arguments
* A prototype declaration for a function that utilizes named parameters
* Example of prototype declarations for subroutines or procedures (if these differ from functions)
* An explanation and example of any special forms of prototyping not covered by the above

Languages that do not provide function prototyping facilities should be omitted from this task.

Solution:
using System;
public delegate int IntFunction(int a, int b);

public class Program
{
    public static int Add(int x, int y) {
        return x + y;
    }

    public static int Multiply(int x, int y) {
        return x * y;
    }

    public static void Main() {
        IntFunction func = Add;
        Console.WriteLine(func(2, 3)); //prints 5
        func = Multiply;
        Console.WriteLine(func(2, 3)); //prints 6
        func += Add;
        Console.WriteLine(func(2, 3)); //prints 5. Both functions are called, but only the last result is kept.
    }
}


Fusc sequence

Definitions:
The   '''fusc'''   integer sequence is defined as:
::*   fusc(0) = 0
::*   fusc(1) = 1
::*   for '''n'''>1,   the   '''n'''th   term is defined as:
::::*   if   '''n'''   is       even;     fusc(n) = fusc(n/2)
::::*   if   '''n'''   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2)

Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above).

;An observation:
:::::*   fusc(A) = fusc(B)

where   '''A'''   is some non-negative integer expressed in binary,   and
where   '''B'''   is the binary value of   '''A'''   reversed.

Fusc numbers are also known as:
::*   fusc function   (named by Dijkstra, 1982)
::*   Stern's Diatomic series   (although it starts with unity, not zero)
::*   Stern-Brocot sequence   (although it starts with unity, not zero)

;Task:
::*   show the first   '''61'''   fusc numbers (starting at zero) in a horizontal format.
::*   show the fusc number (and its index) whose length is greater than any previous fusc number length.
::::*   (the length is the number of decimal digits when the fusc number is expressed in base ten.)
::*   show all numbers with commas   (if appropriate).
::*   show all output here.

;Related task:
::*   RosettaCode Stern-Brocot sequence

;Also see:
::*   the MathWorld entry:   Stern's Diatomic Series.
::*   the OEIS      entry:   A2487.

Solution:
using System;
using System.Collections.Generic;

static class program
{
    static int n = 61;
    static List<int> l = new List<int>() { 0, 1 };

    static int fusc(int n)
    {
        if (n < l.Count) return l[n];
        int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
        l.Add(f); return f;
    }

    static void Main(string[] args)
    {
        bool lst = true; int w = -1, c = 0, t;
        string fs = "{0,11:n0}  {1,-9:n0}", res = "";
        Console.WriteLine("First {0} numbers in the fusc sequence:", n);
        for (int i = 0; i < int.MaxValue; i++)
        {
            int f = fusc(i); if (lst)
            {
                if (i < 61) Console.Write("{0} ", f);
                else
                {
                    lst = false;
                    Console.WriteLine();
                    Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
                    Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
                }
            }
            if ((t = f.ToString().Length) > w)
            {
                w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
                if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
            }
        }
        l.Clear();
    }
}