Composite numbers k with no single digit factors whose factors are all substrings of k

Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''.

;Task

* Find and show here, on this page, the first ten elements of the sequence.

;Stretch

* Find and show the next ten elements.

Solution:
from sympy import isprime, factorint

def contains_its_prime_factors_all_over_7(n):
    if n < 10 or isprime(n):
        return False
    strn = str(n)
    pfacs = factorint(n).keys()
    return all(f > 9 and str(f) in strn for f in pfacs)

found = 0
for n in range(1_000_000_000):
    if contains_its_prime_factors_all_over_7(n):
        found += 1
        print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '')
        if found == 20:
            break


Conjugate transpose

[[Category:Matrices]]

Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.

::: (M^H)_{ji} = \overline{M_{ij}}

This means that   row j, column i of the conjugate transpose equals the
complex conjugate of row i, column j of the original matrix.

In the next list, M must also be a square matrix.

* A Hermitian matrix equals its own conjugate transpose: M^H = M.
* A multiplication with its conjugate transpose: M^HM = MM^H.
* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.

;Task:
Given some matrix of complex numbers, find its conjugate transpose.

Also determine if the matrix is a:
::* Hermitian matrix,
::* normal matrix,  or
::* unitary matrix.

;See also:
* MathWorld entry: [http://mathworld.wolfram.com/ConjugateTranspose.html conjugate transpose]
* MathWorld entry: [http://mathworld.wolfram.com/HermitianMatrix.html Hermitian matrix]
* MathWorld entry: [http://mathworld.wolfram.com/NormalMatrix.html normal matrix]
* MathWorld entry: [http://mathworld.wolfram.com/UnitaryMatrix.html unitary matrix]

Solution:
/* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */

#include
#include
#include

typedef struct
{
  int rows, cols;
  complex **z;
} matrix;

matrix
transpose (matrix a)
{
  int i, j;
  matrix b;

  b.rows = a.cols;
  b.cols = a.rows;

  b.z = malloc (b.rows * sizeof (complex *));

  for (i = 0; i < b.rows; i++)
    {
      b.z[i] = malloc (b.cols * sizeof (complex));
      for (j = 0; j < b.cols; j++)
        {
          b.z[i][j] = conj (a.z[j][i]);
        }
    }

  return b;
}

int
isHermitian (matrix a)
{
  int i, j;
  matrix b = transpose (a);

  if (b.rows == a.rows && b.cols == a.cols)
    {
      for (i = 0; i < b.rows; i++)
        {
          for (j = 0; j < b.cols; j++)
            {
              if (b.z[i][j] != a.z[i][j])
                return 0;
            }
        }
    }

  else
    return 0;

  return 1;
}

matrix
multiply (matrix a, matrix b)
{
  matrix c;
  int i, j;

  if (a.cols == b.rows)
    {
      c.rows = a.rows;
      c.cols = b.cols;

      c.z = malloc (c.rows * (sizeof (complex *)));

      for (i = 0; i < c.rows; i++)
        {
          c.z[i] = malloc (c.cols * sizeof (complex));
          c.z[i][j] = 0 + 0 * I;
          for (j = 0; j < b.cols; j++)
            {
              c.z[i][j] += a.z[i][j] * b.z[j][i];
            }
        }

    }

  return c;
}

int
isNormal (matrix a)
{
  int i, j;
  matrix a_ah, ah_a;

  if (a.rows != a.cols)
    return 0;

  a_ah = multiply (a, transpose (a));
  ah_a = multiply (transpose (a), a);

  for (i = 0; i < a.rows; i++)
    {
      for (j = 0; j < a.cols; j++)
        {
          if (a_ah.z[i][j] != ah_a.z[i][j])
            return 0;
        }
    }

  return 1;
}

int
isUnitary (matrix a)
{
  matrix b;
  int i, j;
  if (isNormal (a) == 1)
    {
      b = multiply (a, transpose(a));

      for (i = 0; i < b.rows; i++)
        {
          for (j = 0; j < b.cols; j++)
            {
              if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))
                return 0;
            }
        }
      return 1;
    }
  return 0;
}

int
main ()
{
  complex z = 3 + 4 * I;
  matrix a, aT;
  int i, j;
  printf ("Enter rows and columns :");
  scanf ("%d%d", &a.rows, &a.cols);

  a.z = malloc (a.rows * sizeof (complex *));
  printf ("Randomly Generated Complex Matrix A is : ");
  for (i = 0; i < a.rows; i++)
    {
      printf ("\n");
      a.z[i] = malloc (a.cols * sizeof (complex));
      for (j = 0; j < a.cols; j++)
        {
          a.z[i][j] = rand () % 10 + rand () % 10 * I;
          printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j]));
        }
    }

  aT = transpose (a);

  printf ("\n\nTranspose of Complex Matrix A is : ");
  for (i = 0; i < aT.rows; i++)
    {
      printf ("\n");
      aT.z[i] = malloc (aT.cols * sizeof (complex));
      for (j = 0; j < aT.cols; j++)
        {
          aT.z[i][j] = rand () % 10 + rand () % 10 * I;
          printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j]));
        }
    }

  printf ("\n\nComplex Matrix A %s hermitian",
          isHermitian (a) == 1 ? "is" : "is not");
  printf ("\n\nComplex Matrix A %s unitary",
          isUnitary (a) == 1 ? "is" : "is not");
  printf ("\n\nComplex Matrix A %s normal",
          isNormal (a) == 1 ? "is" : "is not");

  return 0;
}


Conjugate transpose

Solution:
def conjugate_transpose(m):
    return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))

def mmul( ma, mb):
    return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)

def mi(size):
    'Complex Identity matrix'
    sz = range(size)
    m = [[0 + 0j for i in sz] for j in sz]
    for i in range(size):
        m[i][i] = 1 + 0j
    return tuple(tuple(row) for row in m)

def __allsame(vector):
    first, rest = vector[0], vector[1:]
    return all(i == first for i in rest)

def __allnearsame(vector, eps=1e-14):
    first, rest = vector[0], vector[1:]
    return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps
               for i in rest)

def isequal(matrices, eps=1e-14):
    'Check any number of matrices for equality within eps'
    x = [len(m) for m in matrices]
    if not __allsame(x): return False
    y = [len(m[0]) for m in matrices]
    if not __allsame(y): return False
    for s in range(x[0]):
        for t in range(y[0]):
            if not __allnearsame([m[s][t] for m in matrices], eps): return False
    return True

def ishermitian(m, ct):
    return isequal([m, ct])

def isnormal(m, ct):
    return isequal([mmul(m, ct), mmul(ct, m)])

def isunitary(m, ct):
    mct, ctm = mmul(m, ct), mmul(ct, m)
    mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])
    ident = mi(mctx)
    return isequal([mct, ctm, ident])

def printm(comment, m):
    print(comment)
    fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]
    width = max(max(len(f) for f in row) for row in fields)
    lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)
    print('\n'.join(lines))

if __name__ == '__main__':
    for matrix in [
            ((( 3.000+0.000j), (+2.000+1.000j)),
            (( 2.000-1.000j), (+1.000+0.000j))),

            ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)),
            (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)),
            (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),

            ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)),
            (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)),
            (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:
        printm('\nMatrix:', matrix)
        ct = conjugate_transpose(matrix)
        printm('Its conjugate transpose:', ct)
        print('Hermitian? %s.' % ishermitian(matrix, ct))
        print('Normal?    %s.' % isnormal(matrix, ct))
        print('Unitary?   %s.' % isunitary(matrix, ct))


Continued fraction

:a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}}

The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:

For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.

:\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}}

For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.

:e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}}

For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.

:\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}}

;See also:
:*   [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.

Solution:
/* calculate approximations for continued fractions */
#include

/* kind of function that returns a series of coefficients */
typedef double (*coeff_func)(unsigned n);

/* calculates the specified number of expansions of the continued fraction
 * described by the coefficient series f_a and f_b */
double calc(coeff_func f_a, coeff_func f_b, unsigned expansions)
{
	double a, b, r;
	a = b = r = 0.0;

	unsigned i;
	for (i = expansions; i > 0; i--) {
		a = f_a(i);
		b = f_b(i);
		r = b / (a + r);
	}
	a = f_a(0);

	return a + r;
}

/* series for sqrt(2) */
double sqrt2_a(unsigned n)
{
	return n ? 2.0 : 1.0;
}

double sqrt2_b(unsigned n)
{
	return 1.0;
}

/* series for the napier constant */
double napier_a(unsigned n)
{
	return n ? n : 2.0;
}

double napier_b(unsigned n)
{
	return n > 1.0 ? n - 1.0 : 1.0;
}

/* series for pi */
double pi_a(unsigned n)
{
	return n ? 6.0 : 3.0;
}

double pi_b(unsigned n)
{
	double c = 2.0 * n - 1.0;

	return c * c;
}

int main(void)
{
	double sqrt2, napier, pi;

	sqrt2  = calc(sqrt2_a,  sqrt2_b,  1000);
	napier = calc(napier_a, napier_b, 1000);
	pi     = calc(pi_a,     pi_b,     1000);

	printf("%12.10g\n%12.10g\n%12.10g\n", sqrt2, napier, pi);

	return 0;
}


Continued fraction

Solution:
from fractions import Fraction
import itertools
try: zip = itertools.izip
except: pass

# The Continued Fraction
def CF(a, b, t):
  terms = list(itertools.islice(zip(a, b), t))
  z = Fraction(1,1)
  for a, b in reversed(terms):
    z = a + b / z
  return z

# Approximates a fraction to a string
def pRes(x, d):
  q, x = divmod(x, 1)
  res = str(q)
  res += "."
  for i in range(d):
    x *= 10
    q, x = divmod(x, 1)
    res += str(q)
  return res

# Test the Continued Fraction for sqrt2
def sqrt2_a():
  yield 1
  for x in itertools.repeat(2):
    yield x

def sqrt2_b():
  for x in itertools.repeat(1):
    yield x

cf = CF(sqrt2_a(), sqrt2_b(), 950)
print(pRes(cf, 200))
#1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147

# Test the Continued Fraction for Napier's Constant
def Napier_a():
  yield 2
  for x in itertools.count(1):
    yield x

def Napier_b():
  yield 1
  for x in itertools.count(1):
    yield x

cf = CF(Napier_a(), Napier_b(), 950)
print(pRes(cf, 200))
#2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901

# Test the Continued Fraction for Pi
def Pi_a():
  yield 3
  for x in itertools.repeat(6):
    yield x

def Pi_b():
  for x in itertools.count(1,2):
    yield x*x

cf = CF(Pi_a(), Pi_b(), 950)
print(pRes(cf, 10))
#3.1415926532


Continued fraction/Arithmetic/Construct from rational number

The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming:
:N_1 is the numerator
:N_2 is the denominator

The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.

To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero.

Demonstrate the function by outputing the continued fraction for:
: 1/2
: 3
: 23/8
: 13/11
: 22/7
: -151/77
\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you:
: 14142,10000
: 141421,100000
: 1414214,1000000
: 14142136,10000000

Try :
: 31,10
: 314,100
: 3142,1000
: 31428,10000
: 314285,100000
: 3142857,1000000
: 31428571,10000000
: 314285714,100000000

Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.

Solution:
#include

typedef struct{
	int num,den;
	}fraction;

fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}};
fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};
fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};

int r2cf(int *numerator,int *denominator)
{
	int quotient=0,temp;

	if(denominator != 0)
	{
		quotient = *numerator / *denominator;

		temp = *numerator;

		*numerator = *denominator;

		*denominator = temp % *denominator;
	}

	return quotient;
}

int main()
{
	int i;

	printf("Running the examples :");

	for(i=0;i
And the run gives :

Running the examples :
For N = 1, D = 2 : 0  2
For N = 3, D = 1 : 3
For N = 23, D = 8 : 2  1  7
For N = 13, D = 11 : 1  5  2
For N = 22, D = 7 : 3  7
For N = -151, D = 77 : -1  -1  -24  -1  -2

Running for √2 :
For N = 14142, D = 10000 : 1  2  2  2  2  2  1  1  29
For N = 141421, D = 100000 : 1  2  2  2  2  2  2  3  1  1  3  1  7  2
For N = 1414214, D = 1000000 : 1  2  2  2  2  2  2  2  3  6  1  2  1  12
For N = 14142136, D = 10000000 : 1  2  2  2  2  2  2  2  2  2  6  1  2  4  1  1  2

Running for π :
For N = 31, D = 10 : 3  10
For N = 314, D = 100 : 3  7  7
For N = 3142, D = 1000 : 3  7  23  1  2
For N = 31428, D = 10000 : 3  7  357
For N = 314285, D = 100000 : 3  7  2857
For N = 3142857, D = 1000000 : 3  7  142857
For N = 31428571, D = 10000000 : 3  7  476190  3
For N = 314285714, D = 100000000 : 3  7  7142857


Solution:
def r2cf(n1,n2):
  while n2:
    n1, (t1, n2) = n2, divmod(n1, n2)
    yield t1

print(list(r2cf(1,2)))    # => [0, 2]
print(list(r2cf(3,1)))    # => [3]
print(list(r2cf(23,8)))    # => [2, 1, 7]
print(list(r2cf(13,11)))    # => [1, 5, 2]
print(list(r2cf(22,7)))    # => [3, 7]
print(list(r2cf(14142,10000)))    # => [1, 2, 2, 2, 2, 2, 1, 1, 29]
print(list(r2cf(141421,100000)))    # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]
print(list(r2cf(1414214,1000000)))    # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]
print(list(r2cf(14142136,10000000)))    # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]


Continued fraction/Arithmetic/G(matrix ng, continued fraction n)

This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:
: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix}
I may perform perform the following operations:
:Input the next term of N1
:Output a term of the continued fraction resulting from the operation.

I output a term if the integer parts of \frac{a}{b} and \frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \infty.

When I input a term t my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1  \\
  b + b_1 * t & b_1
\end{bmatrix}

When I output a term t my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b  \\
  a_1 - b_1 * t & a - b * t
\end{bmatrix}

When I need a term t but there are no more my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\
  b_1 & b_1
\end{bmatrix}

I am done when b1 and b are zero.

Demonstrate your solution by calculating:
:[1;5,2] + 1/2
:[3;7] + 1/2
:[3;7] divided by 4
Using a generator for \sqrt{2} (e.g., from [[Continued fraction]]) calculate \frac{1}{\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.

The first step in implementing [[Arithmetic-geometric mean]] is to calculate \frac{1 + \frac{1}{\sqrt{2}}}{2} do this now to cross the starting line and begin the race.

Solution:
/*------------------------------------------------------------------*/
/* For C with Boehm GC as garbage collector. */

#include
#include
#include
#include
#include
#include
#include                  /* Boehm GC. */

/*------------------------------------------------------------------*/

/* Let us choose an integer type. */
typedef long long int integer;

/* We need consistent definitions of division and remainder. Let us
   set those here. For convenience (because C provides it), we will
   use truncation towards zero. */
#define DIV(a, b) ((a) / (b))
#define REM(a, b) ((a) % (b))

/* Choose a memory allocator: Boehm GC. (Ideally one should check for
   NULL return values, but for this pedagogical example let us skip
   that.) */
#define MALLOC_INIT() GC_INIT ()
#define MALLOC GC_MALLOC
#define REALLOC GC_REALLOC
#define FREE GC_FREE            /* Or one could make this a no-op. */

/*------------------------------------------------------------------*/
/* Some operations on char-strings. (In practice, I would write an m4
   macro to create such repetitive C functions for me. Of course, it
   is also possible to use  or some such [generally unsafe]
   mechanism.) */

static char *
string_append1 (const char *s1)
{
  size_t n1 = strlen (s1);
  char *s = MALLOC (n1 + 1);
  s[n1] = '\0';
  memcpy (s, s1, n1);
  return s;
}

static char *
string_append2 (const char *s1, const char *s2)
{
  size_t n1 = strlen (s1);
  size_t n2 = strlen (s2);
  char *s = MALLOC (n1 + n2 + 1);
  s[n1 + n2] = '\0';
  memcpy (s, s1, n1);
  memcpy (s + n1, s2, n2);
  return s;
}

static char *
string_append3 (const char *s1, const char *s2, const char *s3)
{
  size_t n1 = strlen (s1);
  size_t n2 = strlen (s2);
  size_t n3 = strlen (s3);
  char *s = MALLOC (n1 + n2 + n3 + 1);
  s[n1 + n2 + n3] = '\0';
  memcpy (s, s1, n1);
  memcpy (s + n1, s2, n2);
  memcpy (s + n1 + n2, s3, n3);
  return s;
}

/*------------------------------------------------------------------*/
/* Continued fractions as processes for generating terms. The terms
   are memoized and are accessed by their zero-based index. */

typedef void cf_generator_func_t (void *env, bool *there_is_a_term,
                                  integer *term);

struct _cf_generator  /* For practical purposes, this is a closure. */
{
  cf_generator_func_t *func;
  void *env;
};

typedef struct _cf_generator *cf_generator_t;

struct _cf
{
  bool terminated;          /* No more terms? */
  size_t m;                 /* The number of terms computed so far. */
  size_t n;                 /* The size of memo storage. */
  integer *memo;            /* Memoized terms. */
  cf_generator_t gen;       /* A closure to generate terms. */
};

typedef struct _cf *cf_t;

cf_generator_t
cf_generator_make (cf_generator_func_t func, void *env)
{
  cf_generator_t gen = MALLOC (sizeof (struct _cf_generator));
  gen->func = func;
  gen->env = env;
  return gen;
}

cf_t
cf_make (cf_generator_t gen)
{
  const size_t start_size = 8;
  integer *memo = MALLOC (start_size * sizeof (integer));
  cf_t cf = MALLOC (sizeof (struct _cf));
  cf->terminated = false;
  cf->m = 0;
  cf->n = start_size;
  cf->memo = memo;
  cf->gen = gen;
  return cf;
}

static void
_cf_get_more_terms (cf_t cf, size_t needed)
{
  size_t term_count = cf->m;
  bool done = false;
  while (!done)
    {
      if (term_count == needed)
        {
          cf->m = needed;
          done = true;
        }
      else
        {
          bool there_is_a_term;
          integer term;
          cf->gen->func (cf->gen->env, &there_is_a_term, &term);
          if (there_is_a_term)
            {
              cf->memo[term_count] = term;
              term_count += 1;
            }
          else
            {
              cf->terminated = true;
              cf->m = term_count;
              done = true;
            }
        }
    }
}

static void
_cf_update (cf_t cf, size_t needed)
{
  if (cf->terminated || needed <= (cf->m))
    /* Do nothing. */ ;
  else if (needed <= (cf->n))
    _cf_get_more_terms (cf, needed);
  else
    {
      /* Provide twice the needed storage. */
      cf->n = 2 * needed;
      cf->memo = REALLOC (cf->memo, cf->n * sizeof (integer));
      _cf_get_more_terms (cf, needed);
    }
}

void
cf_get_at (cf_t cf, size_t i, bool *there_is_a_term,
           integer *term)
{
  _cf_update (cf, i + 1);
  *there_is_a_term = (i < (cf->m));
  if (*there_is_a_term)
    *term = cf->memo[i];
}

char *
cf2string_max_terms (cf_t cf, size_t max_terms)
{
  char *s = string_append1 ("[");
  const char *sep = "";
  size_t i = 0;
  bool done = false;
  while (!done)
    {
      if (i == max_terms)
        {
          s = string_append2 (s, ",...]");
          done = true;
        }
      else
        {
          bool there_is_a_term;
          integer term;
          cf_get_at (cf, i, &there_is_a_term, &term);
          if (there_is_a_term)
            {
              char buf1[1];
              const int numeral_len =
                snprintf (buf1, 1, "%jd", (intmax_t) term);
              char buf[numeral_len + 1];
              snprintf (buf, numeral_len + 1, "%jd", (intmax_t) term);
              s = string_append3 (s, sep, buf);
              sep = (sep[0] == '\0') ? ";" : ",";
              i += 1;
            }
          else
            {
              s = string_append2 (s, "]");
              done = true;
            }
        }
    }
  return s;
}

char *
cf2string (cf_t cf)
{
  const size_t default_max_terms = 20;
  return cf2string_max_terms (cf, default_max_terms);
}

/*------------------------------------------------------------------*/
/* Using a cf_t as a cf_generator_t. */

struct _cf_gen_env
{
  cf_t cf;
  size_t i;
};

static void
cf_gen_run (void *env, bool *there_is_a_term, integer *term)
{
  struct _cf_gen_env *state = env;
  cf_get_at (state->cf, state->i, there_is_a_term, term);
  state->i += 1;
}

cf_generator_t
cf_gen_make (cf_t cf)
{
  struct _cf_gen_env *state = MALLOC (sizeof (struct _cf_gen_env));
  state->cf = cf;
  state->i = 0;
  return cf_generator_make (cf_gen_run, state);
}

/*------------------------------------------------------------------*/
/* A homographic function. */

struct _hfunc
{
  integer a1;
  integer a;
  integer b1;
  integer b;
};

typedef struct _hfunc *hfunc_t;

struct _hfunc_gen_env
{
  struct _hfunc state;
  cf_generator_t gen;
};

hfunc_t
hfunc_make (integer a1, integer a, integer b1, integer b)
{
  hfunc_t f = MALLOC (sizeof (struct _hfunc));
  f->a1 = a1;
  f->a = a;
  f->b1 = b1;
  f->b = b;
  return f;
}

static void
_take_term_from_ngen (struct _hfunc *state,
                      cf_generator_t ngen)
{
  const integer a1 = state->a1;
  const integer b1 = state->b1;

  bool there_is_a_term;
  integer term;
  ngen->func (ngen->env, &there_is_a_term, &term);
  if (there_is_a_term)
    {
      const integer a = state->a;
      const integer b = state->b;

      state->a1 = a + (a1 * term);
      state->a = a1;
      state->b1 = b + (b1 * term);
      state->b = b1;
    }
  else
    {
      state->a = a1;
      state->b = b1;
    }
}

static void
_adjust_state_for_term_output (struct _hfunc *state,
                               integer term)
{
  const integer a1 = state->a1;
  const integer a = state->a;
  const integer b1 = state->b1;
  const integer b = state->b;

  state->a1 = b1;
  state->a = b;
  state->b1 = a1 - (b1 * term);
  state->b = a - (b * term);
}

static void
hfunc_gen_run (void *env, bool *there_is_a_term, integer *term)
{
  struct _hfunc *state = &(((struct _hfunc_gen_env *) env)->state);
  cf_generator_t ngen = ((struct _hfunc_gen_env *) env)->gen;

  bool done = false;
  while (!done)
    {
      const bool b1_iseqz = (state->b1 == 0);
      const bool b_iseqz = (state->b == 0);
      if (b1_iseqz && b_iseqz)
        {
          *there_is_a_term = false;
          done = true;
        }
      else if (!b1_iseqz && !b_iseqz)
        {
          const integer q1 = DIV (state->a1, state->b1);
          const integer q = DIV (state->a, state->b);
          if (q1 == q)
            {
              _adjust_state_for_term_output (state, q);
              *there_is_a_term = true;
              *term = q;
              done = true;
            }
          else
            _take_term_from_ngen (state, ngen);
        }
      else
        _take_term_from_ngen (state, ngen);
    }
}

/* Make a new generator that applies an hfunc_t to another
   generator. */
cf_generator_t
hfunc_gen_make (hfunc_t f, cf_generator_t gen)
{
  struct _hfunc_gen_env *env =
    MALLOC (sizeof (struct _hfunc_gen_env));
  env->state = *f;
  env->gen = gen;
  return cf_generator_make (hfunc_gen_run, env);
}

/* Make a new cf_t that applies an hfunc_t to another cf_t. */
cf_t
hfunc_apply (hfunc_t f, cf_t cf)
{
  cf_generator_t gen1 = cf_gen_make (cf);
  cf_generator_t gen2 = hfunc_gen_make (f, gen1);
  return cf_make (gen2);
}

/*------------------------------------------------------------------*/
/* Creation of a cf_t for a rational number. */

struct _r2cf_gen_env
{
  integer n;
  integer d;
};

static void
r2cf_gen_run (void *env, bool *there_is_a_term, integer *term)
{
  struct _r2cf_gen_env *state = env;
  *there_is_a_term = (state->d != 0);
  if (*there_is_a_term)
    {
      const integer q = DIV (state->n, state->d);
      const integer r = REM (state->n, state->d);
      state->n = state->d;
      state->d = r;
      *term = q;
    }
}

cf_generator_t
r2cf_gen_make (integer n, integer d)
{
  struct _r2cf_gen_env *state =
    MALLOC (sizeof (struct _r2cf_gen_env));
  state->n = n;
  state->d = d;
  return cf_generator_make (r2cf_gen_run, state);
}

cf_t
r2cf (integer n, integer d)
{
  return cf_make (r2cf_gen_make (n, d));
}

/*------------------------------------------------------------------*/
/* Creation of a cf_t for sqrt(2). */

struct _sqrt2_gen_env
{
  integer term;
};

static void
sqrt2_gen_run (void *env, bool *there_is_a_term, integer *term)
{
  struct _sqrt2_gen_env *state = env;
  *there_is_a_term = true;
  *term = state->term;
  state->term = 2;
}

cf_generator_t
sqrt2_gen_make (void)
{
  struct _sqrt2_gen_env *state =
    MALLOC (sizeof (struct _sqrt2_gen_env));
  state->term = 1;
  return cf_generator_make (sqrt2_gen_run, state);
}

cf_t
sqrt2_make (void)
{
  return cf_make (sqrt2_gen_make ());
}

/*------------------------------------------------------------------*/

int
main (void)
{
  MALLOC_INIT ();

  hfunc_t add_one_half = hfunc_make (2, 1, 0, 2);
  hfunc_t add_one = hfunc_make (1, 1, 0, 1);
  hfunc_t divide_by_two = hfunc_make (1, 0, 0, 2);
  hfunc_t divide_by_four = hfunc_make (1, 0, 0, 4);
  hfunc_t take_reciprocal = hfunc_make (0, 1, 1, 0);
  hfunc_t add_one_then_div_two = hfunc_make (1, 1, 0, 2);
  hfunc_t add_two_then_div_four = hfunc_make (1, 2, 0, 4);

  cf_t cf_13_11 = r2cf (13, 11);
  cf_t cf_22_7 = r2cf (22, 7);
  cf_t cf_sqrt2 = sqrt2_make ();

  cf_t cf_13_11_plus_1_2 = hfunc_apply (add_one_half, cf_13_11);
  cf_t cf_22_7_plus_1_2 = hfunc_apply (add_one_half, cf_22_7);
  cf_t cf_22_7_div_4 = hfunc_apply (divide_by_four, cf_22_7);

  /* The following two give the same result: */
  cf_t cf_sqrt2_div_2 = hfunc_apply (divide_by_two, cf_sqrt2);
  cf_t cf_1_div_sqrt2 = hfunc_apply (take_reciprocal, cf_sqrt2);
  assert (strcmp (cf2string (cf_sqrt2_div_2),
                  cf2string (cf_1_div_sqrt2)) == 0);

  /* The following three give the same result: */
  cf_t cf_2_plus_sqrt2_grouped_div_4 =
    hfunc_apply (add_two_then_div_four, cf_sqrt2);
  cf_t cf_half_of_1_plus_half_sqrt2 =
    hfunc_apply (add_one_then_div_two, cf_sqrt2_div_2);
  cf_t cf_half_of_1_plus_1_div_sqrt2 =
    hfunc_apply (divide_by_two,
                 hfunc_apply (add_one, cf_sqrt2_div_2));
  assert (strcmp (cf2string (cf_2_plus_sqrt2_grouped_div_4),
                  cf2string (cf_half_of_1_plus_half_sqrt2)) == 0);
  assert (strcmp (cf2string (cf_half_of_1_plus_half_sqrt2),
                  cf2string (cf_half_of_1_plus_1_div_sqrt2)) == 0);

  printf ("13/11 => %s\n", cf2string (cf_13_11));
  printf ("22/7 => %s\n", cf2string (cf_22_7));
  printf ("sqrt(2) => %s\n", cf2string (cf_sqrt2));
  printf ("13/11 + 1/2 => %s\n", cf2string (cf_13_11_plus_1_2));
  printf ("22/7 + 1/2 => %s\n", cf2string (cf_22_7_plus_1_2));
  printf ("(22/7)/4 => %s\n", cf2string (cf_22_7_div_4));
  printf ("sqrt(2)/2 => %s\n", cf2string (cf_sqrt2_div_2));
  printf ("1/sqrt(2) => %s\n", cf2string (cf_1_div_sqrt2));
  printf ("(2+sqrt(2))/4 => %s\n",
          cf2string (cf_2_plus_sqrt2_grouped_div_4));
  printf ("(1+sqrt(2)/2)/2 => %s\n",
          cf2string (cf_half_of_1_plus_half_sqrt2));
  printf ("(1+1/sqrt(2))/2 => %s\n",
          cf2string (cf_half_of_1_plus_1_div_sqrt2));

  return 0;
}

/*------------------------------------------------------------------*/


Solution:
class NG:
  def __init__(self, a1, a, b1, b):
    self.a1, self.a, self.b1, self.b = a1, a, b1, b

  def ingress(self, n):
    self.a, self.a1 = self.a1, self.a + self.a1 * n
    self.b, self.b1 = self.b1, self.b + self.b1 * n

  @property
  def needterm(self):
    return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1

  @property
  def egress(self):
    n = self.a // self.b
    self.a,  self.b  = self.b,  self.a  - self.b  * n
    self.a1, self.b1 = self.b1, self.a1 - self.b1 * n
    return n

  @property
  def egress_done(self):
    if self.needterm: self.a, self.b = self.a1, self.b1
    return self.egress

  @property
  def done(self):
    return self.b == 0 and self.b1 == 0


Convert decimal number to rational

The task is to write a program to transform a decimal number into a fraction in lowest terms.

It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...

Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518)  = 0.518518...

Acceptable output:

* 0.9054054 → 4527027 / 5000000
* 0.518518  → 259259 / 500000

Finite decimals are of course no problem:

* 0.75      → 3 / 4

Solution:
#include
#include
#include
#include

/* f : number to convert.
 * num, denom: returned parts of the rational.
 * md: max denominator value.  Note that machine floating point number
 *     has a finite resolution (10e-16 ish for 64 bit double), so specifying
 *     a "best match with minimal error" is often wrong, because one can
 *     always just retrieve the significand and return that divided by
 *     2**52, which is in a sense accurate, but generally not very useful:
 *     1.0/7.0 would be "2573485501354569/18014398509481984", for example.
 */
void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	/*  a: continued fraction coefficients. */
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	/* continued fraction and check denominator each step */
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}


Convert decimal number to rational

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

    const main = () =>
        showJSON(
            map( // Using a tolerance epsilon of 1/10000
                n => showRatio(approxRatio(0.0001)(n)),
                [0.9054054, 0.518518, 0.75]
            )
        );

    // Epsilon -> Real -> Ratio

    // approxRatio :: Real -> Real -> Ratio
    const approxRatio = eps => n => {
        const
            gcde = (e, x, y) => {
                const _gcd = (a, b) => (b < e ? a : _gcd(b, a % b));
                return _gcd(Math.abs(x), Math.abs(y));
            },
            c = gcde(Boolean(eps) ? eps : (1 / 10000), 1, n);
        return Ratio(
            Math.floor(n / c), // numerator
            Math.floor(1 / c) // denominator
        );
    };

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

    // Ratio :: Int -> Int -> Ratio
    const Ratio = (n, d) => ({
        type: 'Ratio',
        'n': n, // numerator
        'd': d // denominator
    });

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // showJSON :: a -> String
    const showJSON = x => JSON.stringify(x, null, 2);

    // showRatio :: Ratio -> String
    const showRatio = nd =>
        nd.n.toString() + '/' + nd.d.toString();

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


Convert decimal number to rational

Solution:
>>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))

0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))

0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>>


Convert decimal number to rational

Solution:
'''Approximate rationals from decimals'''

from math import (floor, gcd)
import sys

# approxRatio :: Float -> Float -> Ratio
def approxRatio(epsilon):
    '''The simplest rational approximation to
       n within the margin given by epsilon.
    '''
    def gcde(e, x, y):
        def _gcd(a, b):
            return a if b < e else _gcd(b, a % b)
        return _gcd(abs(x), abs(y))
    return lambda n: (lambda c=(
        gcde(epsilon if 0 < epsilon else (0.0001), 1, n)
    ): ratio(floor(n / c))(floor(1 / c)))()

# main :: IO ()
def main():
    '''Conversions at different levels of precision.'''

    xs = [0.9054054, 0.518518, 0.75]
    print(
        fTable(__doc__ + ' (epsilon of 1/10000):\n')(str)(
            lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))
        )(
            approxRatio(1 / 10000)
        )(xs)
    )
    print('\n')

    e = minBound(float)
    print(
        fTable(__doc__ + ' (epsilon of ' + repr(e) + '):\n')(str)(
            lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))
        )(
            approxRatio(e)
        )(xs)
    )

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

# fromRatio :: Ratio Int -> Float
def fromRatio(r):
    '''A floating point value derived from a
       a rational value.
    '''
    return r.get('numerator') / r.get('denominator')

# minBound :: Bounded Type -> a
def minBound(t):
    '''Minimum value for a bounded type.'''
    maxsize = sys.maxsize
    float_infomin = sys.float_info.min
    return {
        int: (-maxsize - 1),
        float: float_infomin,
        bool: False,
        str: chr(0)
    }[t]

# ratio :: Int -> Int -> Ratio Int
def ratio(n):
    '''Rational value constructed
       from a numerator and a denominator.
    '''
    def go(n, d):
        g = gcd(n, d)
        return {
            'type': 'Ratio',
            'numerator': n // g, 'denominator': d // g
        }
    return lambda d: go(n * signum(d), abs(d))

# showRatio :: Ratio -> String
def showRatio(r):
    '''String representation of the ratio r.'''
    d = r.get('denominator')
    return str(r.get('numerator')) + (
        ' / ' + str(d) if 1 != d else ''
    )

# signum :: Num -> Num
def signum(n):
    '''The sign of n.'''
    return -1 if 0 > n else (1 if 0 < n else 0)

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

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

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


Convert seconds to compound duration

[[Category:Date and time]]

;Task:
Write a function or program which:
*   takes a positive integer representing a duration in seconds as input (e.g., 100), and
*   returns a string which shows the same duration decomposed into:
:::*   weeks,
:::*   days,
:::*   hours,
:::*   minutes,   and
:::*   seconds.

This is detailed below (e.g., "2 hr, 59 sec").

Demonstrate that it passes the following three test-cases:

'''''Test Cases'''''

:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}

'''''Details'''''

The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}

However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").

Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)

Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).

Solution:
#include  /* requires c99 */
#include   /* requires c99 */
#include
#include

#define N_EL 5

uintmax_t sec_to_week(uintmax_t);
uintmax_t sec_to_day(uintmax_t);
uintmax_t sec_to_hour(uintmax_t);
uintmax_t sec_to_min(uintmax_t);

uintmax_t week_to_sec(uintmax_t);
uintmax_t day_to_sec(uintmax_t);
uintmax_t hour_to_sec(uintmax_t);
uintmax_t min_to_sec(uintmax_t);

char *format_sec(uintmax_t);
    /* the primary function */

int main(int argc, char *argv[])
{
    uintmax_t input;
    char *a;

    if(argc<2) {
        printf("usage: %s #seconds\n", argv[0]);
        return 1;
    }
    input = strtoumax(argv[1],(void *)0, 10 /*base 10*/);
    if(input<1) {
        printf("Bad input: %s\n", argv[1]);
        printf("usage: %s #seconds\n", argv[0]);
        return 1;
    }
    printf("Number entered: %" PRIuMAX "\n", input);
    a = format_sec(input);
    printf(a);
    free(a);

    return 0;
}

/* note: must free memory
 * after using this function */
char *format_sec(uintmax_t input)
{
    int i;
    bool first;
    uintmax_t weeks, days, hours, mins;
    /*seconds kept in input*/

    char *retval;
    FILE *stream;
    size_t size;
    uintmax_t *traverse[N_EL]={&weeks,&days,
            &hours,&mins,&input};
    char *labels[N_EL]={"wk","d","hr","min","sec"};

    weeks = sec_to_week(input);
    input = input - week_to_sec(weeks);

    days = sec_to_day(input);
    input = input - day_to_sec(days);

    hours = sec_to_hour(input);
    input = input - hour_to_sec(hours);

    mins = sec_to_min(input);
    input = input - min_to_sec(mins);
    /* input now has the remaining seconds */

    /* open stream */
    stream = open_memstream(&retval,&size);
    if(stream == 0) {
        fprintf(stderr,"Unable to allocate memory");
        return 0;
    }

    /* populate stream */
    first = true;
    for(i=0;i


Convert seconds to compound duration

Solution:
(function () {
    'use strict';

    // angloDuration :: Int -> String
    function angloDuration(intSeconds) {
        return zip(
                weekParts(intSeconds),
                ['wk', 'd', 'hr', 'min','sec']
            )
            .reduce(function (a, x) {
                return a.concat(x[0] ? (
                    [(x[0].toString() + ' ' + x[1])]
                ) : []);
            }, [])
            .join(', ');
    }

    // weekParts :: Int -> [Int]
    function weekParts(intSeconds) {

        return [undefined, 7, 24, 60, 60]
            .reduceRight(function (a, x) {
                var intRest = a.remaining,
                    intMod = isNaN(x) ? intRest : intRest % x;

                return {
                    remaining:(intRest - intMod) / (x || 1),
                    parts: [intMod].concat(a.parts)
                };
            }, {
                remaining: intSeconds,
                parts: []
            })
            .parts
    }

    // GENERIC ZIP

    // zip :: [a] -> [b] -> [(a,b)]
    function zip(xs, ys) {
        return xs.length === ys.length ? (
            xs.map(function (x, i) {
                return [x, ys[i]];
            })
        ) : undefined;
    }

    // TEST

    return [7259, 86400, 6000000]
        .map(function (intSeconds) {
            return intSeconds.toString() +
                '    ->    ' + angloDuration(intSeconds);
        })
        .join('\n');

})();


Convert seconds to compound duration

Solution:
'''Compound duration'''

from functools import reduce
from itertools import chain

# compoundDurationFromUnits :: [Num] -> [String] -> Num -> [(Num, String)]
def compoundDurationFromUnits(qs):
    '''A list of compound string representions of a number n of time units,
       in terms of the multiples given in qs, and the labels given in ks.
    '''
    return lambda ks: lambda n: list(
        chain.from_iterable(map(
            lambda v, k: [(v, k)] if 0 < v else [],
            mapAccumR(
                lambda a, x: divmod(a, x) if 0 < x else (1, a)
            )(n)(qs)[1],
            ks
        ))
    )

# --------------------------TEST---------------------------
# main :: IO ()
def main():
    '''Tests of various durations, with a
       particular set of units and labels.
    '''

    print(
        fTable('Compound durations from numbers of seconds:\n')(str)(
            quoted("'")
        )(
            lambda n: ', '.join([
                str(v) + ' ' + k for v, k in
                compoundDurationFromUnits([0, 7, 24, 60, 60])(
                    ['wk', 'd', 'hr', 'min', 'sec']
                )(n)
            ])
        )([7259, 86400, 6000000])
    )

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

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

# mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
def mapAccumR(f):
    '''A tuple of an accumulation and a list derived by a combined
       map and fold, with accumulation from right to left.
    '''
    def go(a, x):
        acc, y = f(a[0], x)
        return (acc, [y] + a[1])
    return lambda acc: lambda xs: (
        reduce(go, reversed(xs), (acc, []))
    )

# quoted :: Char -> String -> String
def quoted(c):
    '''A string flanked on both sides
       by a specified quote character.
    '''
    return lambda s: c + s + c

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


Copy stdin to stdout

Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.

Solution:
#include

int main(){
  char c;
  while ( (c=getchar()) != EOF ){
    putchar(c);
  }
  return 0;
}


Copy stdin to stdout

Solution:
process.stdin.resume();
process.stdin.pipe(process.stdout);


Copy stdin to stdout

Solution: python -c 'import sys; sys.stdout.write(sys.stdin.read())'


Count the coins

There are four types of common coins in   [https://en.wikipedia.org/wiki/United_States US]   currency:
:::#   quarters   (25 cents)
:::#   dimes   (10 cents)
:::#   nickels   (5 cents),   and
:::#   pennies   (1 cent)

There are six ways to make change for 15 cents:
:::#   A dime and a nickel
:::#   A dime and 5 pennies
:::#   3 nickels
:::#   2 nickels and 5 pennies
:::#   A nickel and 10 pennies
:::#   15 pennies

;Task:
How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents).

;Optional:
Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000?

(Note:   the answer is larger than   232).

;References:
* [https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52 an algorithm] from the book ''Structure and Interpretation of Computer Programs''.
* [https://algorithmist.com/wiki/Coin_change an article in the algorithmist].
* Change-making problem on Wikipedia.

Solution:
#include
#include
#include

// ad hoc 128 bit integer type; faster than using GMP because of low
// overhead
typedef struct { uint64_t x[2]; } i128;

// display in decimal
void show(i128 v) {
	uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32};
	int i, j = 0, len = 4;
	char buf[100];
	do {
		uint64_t c = 0;
		for (i = len; i--; ) {
			c = (c << 32) + x[i];
			x[i] = c / 10, c %= 10;
		}

		buf[j++] = c + '0';
		for (len = 4; !x[len - 1]; len--);
	} while (len);

	while (j--) putchar(buf[j]);
	putchar('\n');
}

i128 count(int sum, int *coins)
{
	int n, i, k;
	for (n = 0; coins[n]; n++);

	i128 **v = malloc(sizeof(int*) * n);
	int *idx = malloc(sizeof(int) * n);

	for (i = 0; i < n; i++) {
		idx[i] = coins[i];
		// each v[i] is a cyclic buffer
		v[i] = calloc(sizeof(i128), coins[i]);
	}

	v[0][coins[0] - 1] = (i128) {{1, 0}};

	for (k = 0; k <= sum; k++) {
		for (i = 0; i < n; i++)
			if (!idx[i]--) idx[i] = coins[i] - 1;

		i128 c = v[0][ idx[0] ];

		for (i = 1; i < n; i++) {
			i128 *p = v[i] + idx[i];

			// 128 bit addition
			p->x[0] += c.x[0];
			p->x[1] += c.x[1];
			if (p->x[0] < c.x[0]) // carry
				p->x[1] ++;
			c = *p;
		}
	}

	i128 r = v[n - 1][idx[n-1]];

	for (i = 0; i < n; i++) free(v[i]);
	free(v);
	free(idx);

	return r;
}

// simple recursive method; slow
int count2(int sum, int *coins)
{
	if (!*coins || sum < 0) return 0;
	if (!sum) return 1;
	return count2(sum - *coins, coins) + count2(sum, coins + 1);
}

int main(void)
{
	int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 };
	int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 };

	show(count(   100, us_coins + 2));
	show(count(  1000, us_coins));

	show(count(  1000 * 100, us_coins));
	show(count( 10000 * 100, us_coins));
	show(count(100000 * 100, us_coins));

	putchar('\n');

	show(count(     1 * 100, eu_coins));
	show(count(  1000 * 100, eu_coins));
	show(count( 10000 * 100, eu_coins));
	show(count(100000 * 100, eu_coins));

	return 0;
}


Count the coins

Solution:
function countcoins(t, o) {
    'use strict';
    var targetsLength = t + 1;
    var operandsLength = o.length;
    t = [1];

    for (var a = 0; a < operandsLength; a++) {
        for (var b = 1; b < targetsLength; b++) {

            // initialise undefined target
            t[b] = t[b] ? t[b] : 0;

            // accumulate target + operand ways
            t[b] += (b < o[a]) ? 0 : t[b - o[a]];
        }
    }

    return t[targetsLength - 1];
}


Count the coins

Solution:
try:
    import psyco
    psyco.full()
except ImportError:
    pass

def count_changes(amount_cents, coins):
    n = len(coins)
    # max([]) instead of max() for Psyco
    cycle = max([c+1 for c in coins if c <= amount_cents]) * n
    table = [0] * cycle
    for i in xrange(n):
        table[i] = 1

    pos = n
    for s in xrange(1, amount_cents + 1):
        for i in xrange(n):
            if i == 0 and pos >= cycle:
                pos = 0
            if coins[i] <= s:
                q = pos - coins[i] * n
                table[pos]= table[q] if (q >= 0) else table[q + cycle]
            if i:
                table[pos] += table[pos - 1]
            pos += 1
    return table[pos - 1]

def main():
    us_coins = [100, 50, 25, 10, 5, 1]
    eu_coins = [200, 100, 50, 20, 10, 5, 2, 1]

    for coins in (us_coins, eu_coins):
        print count_changes(     100, coins[2:])
        print count_changes(  100000, coins)
        print count_changes( 1000000, coins)
        print count_changes(10000000, coins), "\n"

main()


Create an HTML table

Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.

Solution:
#include
#include

int main()
{
	int i;
	printf(""
		"XYZ");
	for (i = 0; i < 4; i++) {
		printf("%d%d%d%d", i,
			rand() % 10000, rand() % 10000, rand() % 10000);
	}
	printf("");

	return 0;
}


Create an HTML table

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

    // HTML ---------------------------------------------

    // treeHTML :: tree
    //      {tag :: String, text :: String, kvs :: Dict}
    //      -> String
    const treeHTML = tree =>
        foldTree(
            (x, xs) => `<${x.tag + attribString(x.kvs)}>` + (
                'text' in x ? (
                    x.text
                ) : '\n'
            ) + concat(xs) + `\n`)(
            tree
        );

    // attribString :: Dict -> String
    const attribString = dct =>
        dct ? (
            ' ' + Object.keys(dct)
            .reduce(
                (a, k) => a + k + '="' + dct[k] + '" ', ''
            ).trim()
        ) : '';

    // TEST ---------------------------------------------
    const main = () => {
        const
            tableStyle = {
                style: "width:25%; border:2px solid silver;"
            },
            trStyle = {
                style: "border:1px solid silver;text-align:right;"
            },
            strCaption = 'Table generated by JS';

        const
            n = 3,
            colNames = take(n)(enumFrom('A')),
            dataRows = map(
                x => Tuple(x)(map(randomRInt(100)(9999))(
                    colNames
                )))(take(n)(enumFrom(1)));

        const
            // TABLE AS TREE STRUCTURE  -----------------
            tableTree = Node({
                    tag: 'table',
                    kvs: tableStyle
                },
                append([
                    Node({
                        tag: 'caption',
                        text: 'Table source generated by JS'
                    }),
                    // HEADER ROW -----------------------
                    Node({
                            tag: 'tr',
                        },
                        map(k => Node({
                            tag: 'th',
                            kvs: {
                                style: "text-align:right;"
                            },
                            text: k
                        }))(cons('')(colNames))
                    )
                    // DATA ROWS ------------------------
                ])(map(tpl => Node({
                    tag: 'tr',
                    kvs: trStyle
                }, cons(
                    Node({
                        tag: 'th',
                        text: fst(tpl)
                    }))(
                    map(v => Node({
                        tag: 'td',
                        text: v.toString()
                    }))(snd(tpl))
                )))(dataRows))
            );

        // Return a value and/or apply console.log to it.
        // (JS embeddings vary in their IO channels)
        const strHTML = treeHTML(tableTree);
        return (
            console.log(strHTML)
            //strHTML
        );
    };

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

    // Node :: a -> [Tree a] -> Tree a
    const Node = (v, xs) => ({
        type: 'Node',
        root: v,
        nest: xs || []
    });

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

    // append (++) :: [a] -> [a] -> [a]
    // append (++) :: String -> String -> String
    const append = xs => ys => xs.concat(ys);

    // chr :: Int -> Char
    const chr = String.fromCodePoint;

    // concat :: [[a]] -> [a]
    // concat :: [String] -> String
    const concat = xs =>
        0 < xs.length ? (() => {
            const unit = 'string' !== typeof xs[0] ? (
                []
            ) : '';
            return unit.concat.apply(unit, xs);
        })() : [];

    // cons :: a -> [a] -> [a]
    const cons = x => xs => [x].concat(xs);

    // enumFrom :: a -> [a]
    function* enumFrom(x) {
        let v = x;
        while (true) {
            yield v;
            v = succ(v);
        }
    }

    // enumFromToChar :: Char -> Char -> [Char]
    const enumFromToChar = m => n => {
        const [intM, intN] = [m, n].map(
            x => x.charCodeAt(0)
        );
        return Array.from({
            length: Math.floor(intN - intM) + 1
        }, (_, i) => String.fromCodePoint(intM + i));
    };

    // foldTree :: (a -> [b] -> b) -> Tree a -> b
    const foldTree = f => tree => {
        const go = node =>
            f(node.root, node.nest.map(go));
        return go(tree);
    };

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // isChar :: a -> Bool
    const isChar = x =>
        ('string' === typeof x) && (1 === x.length);

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

    // ord :: Char -> Int
    const ord = c => c.codePointAt(0);

    // randomRInt :: Int -> Int -> () -> Int
    const randomRInt = low => high => () =>
        low + Math.floor(
            (Math.random() * ((high - low) + 1))
        );

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // succ :: Enum a => a -> a
    const succ = x =>
        isChar(x) ? (
            chr(1 + ord(x))
        ) : isNaN(x) ? (
            undefined
        ) : 1 + x;

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

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


Create an HTML table

Solution:
import random

def rand9999():
    return random.randint(1000, 9999)

def tag(attr='', **kwargs):
    for tag, txt in kwargs.items():
        return '<{tag}{attr}>{txt}'.format(**locals())

if __name__ == '__main__':
    header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
    rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i)
                                    + ''.join(tag(td=rand9999())
                                              for j in range(3)))
                     for i in range(1, 6))
    table = tag(table='\n' + header + rows + '\n')
    print(table)


Cullen and Woodall numbers

A Cullen number is a number of the form '''n × 2n + 1''' where '''n''' is a natural number.

A Woodall number is very similar. It is a number of the form '''n × 2n - 1''' where '''n''' is a natural number.

So for each '''n''' the associated Cullen number and Woodall number differ by 2.

''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''

'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.

It is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.

;Task

* Write procedures to find Cullen numbers and Woodall numbers.

* Use those procedures to find and show here, on this page the first 20 of each.

;Stretch

* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.

* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.

;See also

* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1

* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1

* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime

* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime

Solution:
print("working...")
print("First 20 Cullen numbers:")

for n in range(1,21):
    num = n*pow(2,n)+1
    print(str(num),end= " ")

print()
print("First 20 Woodall numbers:")

for n in range(1,21):
    num = n*pow(2,n)-1
    print(str(num),end=" ")

print()
print("done...")


Currency

;Task:
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.

;Note:
The '''IEEE 754''' binary floating point representations of numbers like   '''2.86'''   and   '''.0765'''   are not exact.

For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.

Use the values:
::* 4000000000000000 hamburgers at $5.50 each       (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.

(That number of hamburgers is a 4 with 15 zeros after it.    The number is contrived to exclude naïve task solutions using 64 bit floating point types.)

Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax

The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.

The output must show dollars and cents with a decimal point.

The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16

Dollar signs and thousands separators are optional.

Solution:
#include
#include

int main()
{
	mpf_t burgerUnitPrice, milkshakePrice, burgerTotalPrice, totalPrice, tax, burgerNum, milkshakeNum;

	mpf_inits(burgerUnitPrice, milkshakePrice, burgerTotalPrice, totalPrice, tax,burgerNum, milkshakeNum,NULL);

	mpf_set_d(burgerUnitPrice,5.50);
	mpf_set_d(milkshakePrice,2 * 2.86);
	mpf_set_d(burgerNum,4000000000000000);
	mpf_set_d(milkshakeNum,2);

	mpf_mul(burgerTotalPrice,burgerNum,burgerUnitPrice);
	mpf_add(totalPrice,burgerTotalPrice,milkshakePrice);

	mpf_set_str(tax,"0.0765",10);
	mpf_mul(tax,totalPrice,tax);

	gmp_printf("\nTotal price before tax : $ %.*Ff", 2, totalPrice);
	gmp_printf("\nTotal tax : $ %.*Ff", 2, tax);

	mpf_add(totalPrice,totalPrice,tax);

	gmp_printf("\nTotal price after tax : $ %.*Ff", 2, totalPrice);

	return 0;
}


Currency

Solution:
const money = require('money-math')

let hamburgers = 4000000000000000
let hamburgerPrice = 5.50

let shakes = 2
let shakePrice = 2.86

let tax = 7.65

let hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice))
let shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice))

let subTotal = money.add(hamburgerTotal, shakeTotal)

let taxTotal = money.percent(subTotal, tax)

let total = money.add(subTotal, taxTotal)

console.log('Hamburger Total:', hamburgerTotal)
console.log('Shake Total:', shakeTotal)
console.log('Sub Total:', subTotal)
console.log('Tax:', taxTotal)
console.log('Total:', total)


Currency

Solution:
from decimal import Decimal as D
from collections import namedtuple

Item = namedtuple('Item', 'price, quant')

items = dict( hamburger=Item(D('5.50'), D('4000000000000000')),
              milkshake=Item(D('2.86'), D('2')) )
tax_rate = D('0.0765')

fmt = "%-10s %8s %18s %22s"
print(fmt % tuple('Item Price Quantity Extension'.upper().split()))

total_before_tax = 0
for item, (price, quant) in sorted(items.items()):
    ext = price * quant
    print(fmt % (item, price, quant, ext))
    total_before_tax += ext
print(fmt % ('', '', '', '--------------------'))
print(fmt % ('', '', 'subtotal', total_before_tax))

tax = (tax_rate * total_before_tax).quantize(D('0.00'))
print(fmt % ('', '', 'Tax', tax))

total = total_before_tax + tax
print(fmt % ('', '', '', '--------------------'))
print(fmt % ('', '', 'Total', total))


Currying

;Task:
Create a simple demonstrative example of Currying in a specific language.

Add any historic details as to how the feature made its way into the language.

[[Category:Functions and subroutines]]

Solution:
#include
#include

long int factorial(int n){
	if(n>1)
		return n*factorial(n-1);
	return 1;
}

long int sumOfFactorials(int num,...){
	va_list vaList;
	long int sum = 0;

	va_start(vaList,num);

	while(num--)
		sum += factorial(va_arg(vaList,int));

	va_end(vaList);

	return sum;
}

int main()
{
	printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5));
	printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5));
	printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3));

	return 0;
}


Currying

Solution:
(function () {

    // curry :: ((a, b) -> c) -> a -> b -> c
    function curry(f) {
        return function (a) {
            return function (b) {
                return f(a, b);
            };
        };
    }

    // TESTS

    // product :: Num -> Num -> Num
    function product(a, b) {
        return a * b;
    }

    // return typeof curry(product);
    // --> function

    // return typeof curry(product)(7)
    // --> function

    //return typeof curry(product)(7)(9)
    // --> number

    return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        .map(curry(product)(7))

    // [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

})();


Currying

Solution:
# AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS

# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
    return lambda a: lambda b: f(a, b)

# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
    return lambda x, y: f(x)(y)

# EXAMPLES --------------------------------------

# A plain uncurried function with 2 arguments,

# justifyLeft :: Int -> String -> String
def justifyLeft(n, s):
    return (s + (n * ' '))[:n]

# and a similar, but manually curried, function.

# justifyRight :: Int -> String -> String
def justifyRight(n):
    return lambda s: (
        ((n * ' ') + s)[-n:]
    )

# CURRYING and UNCURRYING at run-time:

def main():
    for s in [
        'Manually curried using a lambda:',
        '\n'.join(map(
            justifyRight(5),
            ['1', '9', '10', '99', '100', '1000']
        )),

        '\nAutomatically uncurried:',
        uncurry(justifyRight)(5, '10000'),

        '\nAutomatically curried',
        '\n'.join(map(
            curry(justifyLeft)(10),
            ['1', '9', '10', '99', '100', '1000']
        ))
    ]:
        print (s)

main()


Curzon numbers

A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by  '''2 × n + 1'''.

'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by  '''k × n + 1'''.

''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.''

Generalized Curzon numbers only exist for even base integers.

;Task

* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.

;Stretch

* Find and show the '''one thousandth'''.

;See also

;* [https://www.numbersaplenty.com/set/Curzon_number Numbers Aplenty - Curzon numbers]
;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)

''and even though it is not specifically mentioned that they are Curzon numbers:''

;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)

Solution:
#include
#include
#include
#include

uint64_t modPow(uint64_t base, uint64_t exp, uint64_t mod) {
    if (mod == 1) return 0;
    uint64_t result = 1;
    base %= mod;
    for (; exp > 0; exp >>= 1) {
        if ((exp & 1) == 1) result = (result * base) % mod;
        base = (base * base) % mod;
    }
    return result;
}

bool isCurzon(uint64_t n, uint64_t k) {
    const uint64_t r = k * n;
    return modPow(k, n, r+1) == r;
}

int main() {
    uint64_t k, n, count;
    setlocale(LC_NUMERIC, "");
    for (k = 2; k <= 10; k += 2) {
        printf("Curzon numbers with base %ld:\n", k);
        for (n = 1, count = 0; count < 50; ++n) {
            if (isCurzon(n, k)) {
                printf("%4ld ", n);
                if (++count % 10 == 0) printf("\n");
            }
        }
        for (;;) {
            if (isCurzon(n, k)) ++count;
            if (count == 1000) break;
            ++n;
        }
        printf("1,000th Curzon number with base %ld: %'ld\n\n", k, n);
    }
    return 0;
}


Curzon numbers

Solution:
def is_Curzon(n, k):
    r = k * n
    return pow(k, n, r + 1) == r

for k in [2, 4, 6, 8, 10]:
    n, curzons = 1, []
    while len(curzons) < 1000:
        if is_Curzon(n, k):
            curzons.append(n)
        n += 1
    print(f'Curzon numbers with k = {k}:')
    for i, c in enumerate(curzons[:50]):
        print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '')
    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\n')


Cut a rectangle

A given rectangle is made from ''m'' × ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.

[[file:rect-cut.svg]]

Write a program that calculates the number of different ways to cut an ''m'' × ''n'' rectangle.  Optionally, show each of the cuts.

Possibly related task: [[Maze generation]] for depth-first search.

Solution:
#include
#include

typedef unsigned char byte;
int w = 0, h = 0, verbose = 0;
unsigned long count = 0;

byte **hor, **ver, **vis;
byte **c = 0;

enum { U = 1, D = 2, L = 4, R = 8 };

byte ** alloc2(int w, int h)
{
	int i;
	byte **x = calloc(1, sizeof(byte*) * h + h * w);
	x[0] = (byte *)&x[h];
	for (i = 1; i < h; i++)
		x[i] = x[i - 1] + w;
	return x;
}

void show()
{
	int i, j, v, last_v;
	printf("%ld\n", count);
#if 0
	for (i = 0; i <= h; i++) {
		for (j = 0; j <= w; j++)
			printf("%d ", hor[i][j]);
		puts("");
	}
	puts("");

	for (i = 0; i <= h; i++) {
		for (j = 0; j <= w; j++)
			printf("%d ", ver[i][j]);
		puts("");
	}
	puts("");
#endif
	for (i = 0; i < h; i++) {
		if (!i) v = last_v = 0;
		else last_v = v = hor[i][0] ? !last_v : last_v;

		for (j = 0; j < w; v = ver[i][++j] ? !v : v)
			printf(v ? "\033[31m[]" : "\033[33m{}");
		puts("\033[m");
	}
	putchar('\n');
}

void walk(int y, int x)
{
	if (x < 0 || y < 0 || x > w || y > h) return;

	if (!x || !y || x == w || y == h) {
		++count;
		if (verbose) show();
		return;
	}

	if (vis[y][x]) return;
	vis[y][x]++; vis[h - y][w - x]++;

	if (x && !hor[y][x - 1]) {
		hor[y][x - 1] = hor[h - y][w - x] = 1;
		walk(y, x - 1);
		hor[y][x - 1] = hor[h - y][w - x] = 0;
	}
	if (x < w && !hor[y][x]) {
		hor[y][x] = hor[h - y][w - x - 1] = 1;
		walk(y, x + 1);
		hor[y][x] = hor[h - y][w - x - 1] = 0;
	}

	if (y && !ver[y - 1][x]) {
		ver[y - 1][x] = ver[h - y][w - x] = 1;
		walk(y - 1, x);
		ver[y - 1][x] = ver[h - y][w - x] = 0;
	}

	if (y < h && !ver[y][x]) {
		ver[y][x] = ver[h - y - 1][w - x] = 1;
		walk(y + 1, x);
		ver[y][x] = ver[h - y - 1][w - x] = 0;
	}

	vis[y][x]--; vis[h - y][w - x]--;
}

void cut(void)
{
	if (1 & (h * w)) return;

	hor = alloc2(w + 1, h + 1);
	ver = alloc2(w + 1, h + 1);
	vis = alloc2(w + 1, h + 1);

	if (h & 1) {
		ver[h/2][w/2] = 1;
		walk(h / 2, w / 2);
	} else if (w & 1) {
		hor[h/2][w/2] = 1;
		walk(h / 2, w / 2);
	} else {
		vis[h/2][w/2] = 1;

		hor[h/2][w/2-1] = hor[h/2][w/2] = 1;
		walk(h / 2, w / 2 - 1);
		hor[h/2][w/2-1] = hor[h/2][w/2] = 0;

		ver[h/2 - 1][w/2] = ver[h/2][w/2] = 1;
		walk(h / 2 - 1, w/2);
	}
}

void cwalk(int y, int x, int d)
{
	if (!y || y == h || !x || x == w) {
		++count;
		return;
	}
	vis[y][x] = vis[h-y][w-x] = 1;

	if (x && !vis[y][x-1])
		cwalk(y, x - 1, d|1);
	if ((d&1) && x < w && !vis[y][x+1])
		cwalk(y, x + 1, d|1);
	if (y && !vis[y-1][x])
		cwalk(y - 1, x, d|2);
	if ((d&2) && y < h && !vis[y + 1][x])
		cwalk(y + 1, x, d|2);

	vis[y][x] = vis[h-y][w-x] = 0;
}

void count_only(void)
{
	int t;
	long res;
	if (h * w & 1) return;
	if (h & 1) t = h, h = w, w = t;

	vis = alloc2(w + 1, h + 1);
	vis[h/2][w/2] = 1;

	if (w & 1) vis[h/2][w/2 + 1] = 1;
	if (w > 1) {
		cwalk(h/2, w/2 - 1, 1);
		res = 2 * count - 1;
		count = 0;
		if (w != h)
			cwalk(h/2+1, w/2, (w & 1) ? 3 : 2);

		res += 2 * count - !(w & 1);
	} else {
		res = 1;
	}
	if (w == h) res = 2 * res + 2;
	count = res;
}

int main(int c, char **v)
{
	int i;

	for (i = 1; i < c; i++) {
		if (v[i][0] == '-' && v[i][1] == 'v' && !v[i][2]) {
			verbose = 1;
		} else if (!w) {
			w = atoi(v[i]);
			if (w <= 0) goto bail;
		} else if (!h) {
			h = atoi(v[i]);
			if (h <= 0) goto bail;
		} else
			goto bail;
	}
	if (!w) goto bail;
	if (!h) h = w;

	if (verbose) cut();
	else count_only();

	printf("Total: %ld\n", count);
	return 0;

bail:	fprintf(stderr, "bad args\n");
	return 1;
}


Cut a rectangle

Solution:
def cut_it(h, w):
    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
    if h % 2: h, w = w, h
    if h % 2: return 0
    if w == 1: return 1
    count = 0

    next = [w + 1, -w - 1, -1, 1]
    blen = (h + 1) * (w + 1) - 1
    grid = [False] * (blen + 1)

    def walk(y, x, count):
        if not y or y == h or not x or x == w:
            return count + 1

        t = y * (w + 1) + x
        grid[t] = grid[blen - t] = True

        if not grid[t + next[0]]:
            count = walk(y + dirs[0][0], x + dirs[0][1], count)
        if not grid[t + next[1]]:
            count = walk(y + dirs[1][0], x + dirs[1][1], count)
        if not grid[t + next[2]]:
            count = walk(y + dirs[2][0], x + dirs[2][1], count)
        if not grid[t + next[3]]:
            count = walk(y + dirs[3][0], x + dirs[3][1], count)

        grid[t] = grid[blen - t] = False
        return count

    t = h // 2 * (w + 1) + w // 2
    if w % 2:
        grid[t] = grid[t + 1] = True
        count = walk(h // 2, w // 2 - 1, count)
        res = count
        count = 0
        count = walk(h // 2 - 1, w // 2, count)
        return res + count * 2
    else:
        grid[t] = True
        count = walk(h // 2, w // 2 - 1, count)
        if h == w:
            return count * 2
        count = walk(h // 2 - 1, w // 2, count)
        return count

def main():
    for w in xrange(1, 10):
        for h in xrange(1, w + 1):
            if not((w * h) % 2):
                print "%d x %d: %d" % (w, h, cut_it(w, h))

main()


Cyclotomic polynomial

The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.

;Task:
*   Find and print the first 30 cyclotomic polynomials.
*   Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.

;See also
*   Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
*   The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.

Solution:
from itertools import count, chain
from collections import deque

def primes(_cache=[2, 3]):
    yield from _cache
    for n in count(_cache[-1]+2, 2):
        if isprime(n):
            _cache.append(n)
            yield n

def isprime(n):
    for p in primes():
        if n%p == 0:
            return False
        if p*p > n:
            return True

def factors(n):
    for p in primes():
    # prime factoring is such a non-issue for small numbers that, for
    # this example, we might even just say
    # for p in count(2):
        if p*p > n:
            if n > 1:
                yield(n, 1, 1)
            break

        if n%p == 0:
            cnt = 0
            while True:
                n, cnt = n//p, cnt+1
                if n%p != 0: break
            yield p, cnt, n
# ^^ not the most sophisticated prime number routines, because no need

# Returns (list1, list2) representing the division between
# two polinomials. A list p of integers means the product
#   (x^p[0] - 1) * (x^p[1] - 1) * ...
def cyclotomic(n):
    def poly_div(num, den):
        return (num[0] + den[1], num[1] + den[0])

    def elevate(poly, n): # replace poly p(x) with p(x**n)
        powerup = lambda p, n: [a*n for a in p]
        return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n))

    if n == 0:
        return ([], [])
    if n == 1:
        return ([1], [])

    p, m, r = next(factors(n))
    poly = cyclotomic(r)
    return elevate(poly_div(elevate(poly, p), poly), p**(m-1))

def to_text(poly):
    def getx(c, e):
        if e == 0:
            return '1'
        elif e == 1:
            return 'x'
        return 'x' + (''.join('⁰¹²³⁴⁵⁶⁷⁸⁹'[i] for i in map(int, str(e))))

    parts = []
    for (c,e) in (poly):
        if c < 0:
            coef = ' - ' if c == -1 else f' - {-c} '
        else:
            coef = (parts and ' + ' or '') if c == 1 else f' + {c}'
        parts.append(coef + getx(c,e))
    return ''.join(parts)

def terms(poly):
    # convert above representation of division to (coef, power) pairs

    def merge(a, b):
        # a, b should be deques. They may change during the course.
        while a or b:
            l = a[0] if a else (0, -1) # sentinel value
            r = b[0] if b else (0, -1)
            if l[1] > r[1]:
                a.popleft()
            elif l[1] < r[1]:
                b.popleft()
                l = r
            else:
                a.popleft()
                b.popleft()
                l = (l[0] + r[0], l[1])
            yield l

    def mul(poly, p): # p means polynomial x^p - 1
        poly = list(poly)
        return merge(deque((c, e+p) for c,e in poly),
                     deque((-c, e) for c,e in poly))

    def div(poly, p): # p means polynomial x^p - 1
        q = deque()
        for c,e in merge(deque(poly), q):
            if c:
                q.append((c, e - p))
                yield (c, e - p)
            if e == p: break

    p = [(1, 0)]  # 1*x^0, i.e. 1

    for x in poly[0]: # numerator
        p = mul(p, x)
    for x in sorted(poly[1], reverse=True): # denominator
        p = div(p, x)
    return p

for n in chain(range(11), [2]):
    print(f'{n}: {to_text(terms(cyclotomic(n)))}')

want = 1
for n in count():
    c = [c for c,_ in terms(cyclotomic(n))]
    while want in c or -want in c:
        print(f'C[{want}]: {n}')
        want += 1


Damm algorithm

The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.

The algorithm is named after H. Michael Damm.

;Task:
Verify the checksum, stored as last digit of an input.

Solution:
#include
#include
#include

bool damm(unsigned char *input, size_t length) {
    static const unsigned char table[10][10] = {
        {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
        {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
        {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
        {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
        {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
        {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
        {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
        {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
        {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
        {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
    };

    unsigned char interim = 0;
    for (size_t i = 0; i < length; i++) {
        interim = table[interim][input[i]];
    }
    return interim == 0;
}

int main() {
    unsigned char input[4] = {5, 7, 2, 4};
    puts(damm(input, 4) ? "Checksum correct" : "Checksum incorrect");
    return 0;
}


Damm algorithm

Solution:
const table = [
    [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
    [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
    [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
    [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
    [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
    [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
    [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
    [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
    [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
    [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
 ];

const lookup = (p, c) => table[p][parseInt(c, 10)]
const damm = input => [...input].reduce(lookup, 0) === 0;

// ----------------------------------------------------------[ Tests ]----
const test = () => ["5724", "5727", "112946", "112949"].forEach(e =>
    console.log(`${e} => ${damm(e) ? 'Pass' : 'Fail'}`)
);
test();


Damm algorithm

Solution:
def damm(num: int) -> bool:
    row = 0
    for digit in str(num):
        row = _matrix[row][int(digit)]
    return row == 0

_matrix = (
    (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),
    (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
    (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),
    (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),
    (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),
    (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),
    (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),
    (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),
    (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),
    (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
)

if __name__ == '__main__':
    for test in [5724, 5727, 112946]:
        print(f'{test}\t Validates as: {damm(test)}')


De Bruijn sequences

The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn.

A note on Dutch capitalization:   Nicolaas' last name is   '''de Bruijn''',   the   '''de'''   isn't normally capitalized
unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.

In combinatorial mathematics,   a   '''de Bruijn sequence'''   of order    ''n''    on
a    size-''k''    alphabet (computer science)    ''A''    is a cyclic sequence in which every
possible    length-''n''    string (computer science, formal theory)   on    ''A''    occurs
exactly once as a contiguous substring.

Such a sequence is denoted by    ''B''(''k'', ''n'')    and has
length   ''k''''n'',   which is also the number of distinct substrings of
length   ''n''   on   ''A'';
de Bruijn sequences are therefore optimally short.

There are:
                          (k!)k(n-1)   ÷   kn
distinct de Bruijn sequences    ''B''(''k'', ''n'').

;Task:
For this Rosetta Code task,   a   '''de Bruijn'''   sequence is to be generated that can be used to shorten a brute-force attack on
a   PIN-like   code lock that does not have an "enter"
key and accepts the last    ''n''    digits entered.

Note:   automated teller machines (ATMs)   used to work like
this,   but their software has been updated to not allow a brute-force attack.

;Example:
A   digital door lock   with a 4-digit code would
have ''B'' (10, 4) solutions,   with a length of   '''10,000'''   (digits).

Therefore, only at most     '''10,000 + 3'''     (as the solutions are cyclic or ''wrap-around'')   presses are needed to
open the lock.

Trying all 4-digit codes separately would require   '''4 × 10,000'''   or   '''40,000'''   presses.

;Task requirements:
:*   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
:::*   Show the length of the generated de Bruijn sequence.
:::*   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the ''discussion'' page).
:::*   Show the first and last   '''130'''   digits of the de Bruijn sequence.
:*   Verify that all four-digit (decimal)   '''1,000'''   PIN codes are contained within the de Bruijn sequence.
:::*   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).
:*   Reverse the de Bruijn sequence.
:*   Again, perform the (above) verification test.
:*   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
:::*   Perform the verification test (again).   There should be four PIN codes missing.

(The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list
any and all missing PIN codes.)

Show all output here, on this page.

;References:
:*   Wikipedia           entry:   de Bruijn sequence.
:*   MathWorld           entry:   [http://mathworld.wolfram.com/deBruijnSequence.html de Bruijn sequence].
:*   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.

Solution:
# from https://en.wikipedia.org/wiki/De_Bruijn_sequence

def de_bruijn(k, n):
    """
    de Bruijn sequence for alphabet k
    and subsequences of length n.
    """
    try:
        # let's see if k can be cast to an integer;
        # if so, make our alphabet a list
        _ = int(k)
        alphabet = list(map(str, range(k)))

    except (ValueError, TypeError):
        alphabet = k
        k = len(k)

    a = [0] * k * n
    sequence = []

    def db(t, p):
        if t > n:
            if n % p == 0:
                sequence.extend(a[1:p + 1])
        else:
            a[t] = a[t - p]
            db(t + 1, p)
            for j in range(a[t - p] + 1, k):
                a[t] = j
                db(t + 1, t)
    db(1, 1)
    return "".join(alphabet[i] for i in sequence)

def validate(db):
    """

    Check that all 10,000 combinations of 0-9 are present in
    De Bruijn string db.

    Validating the reversed deBruijn sequence:
      No errors found

    Validating the overlaid deBruijn sequence:
      4 errors found:
        PIN number 1459 missing
        PIN number 4591 missing
        PIN number 5814 missing
        PIN number 8145 missing

    """

    dbwithwrap = db+db[0:3]

    digits = '0123456789'

    errorstrings = []

    for d1 in digits:
        for d2 in digits:
            for d3 in digits:
                for d4 in digits:
                    teststring = d1+d2+d3+d4
                    if teststring not in dbwithwrap:
                        errorstrings.append(teststring)

    if len(errorstrings) > 0:
        print("  "+str(len(errorstrings))+" errors found:")
        for e in errorstrings:
            print("  PIN number "+e+"  missing")
    else:
        print("  No errors found")

db = de_bruijn(10, 4)

print(" ")
print("The length of the de Bruijn sequence is ", str(len(db)))
print(" ")
print("The first 130 digits of the de Bruijn sequence are: "+db[0:130])
print(" ")
print("The last 130 digits of the de Bruijn sequence are: "+db[-130:])
print(" ")
print("Validating the deBruijn sequence:")
validate(db)
dbreversed = db[::-1]
print(" ")
print("Validating the reversed deBruijn sequence:")
validate(dbreversed)
dboverlaid = db[0:4443]+'.'+db[4444:]
print(" ")
print("Validating the overlaid deBruijn sequence:")
validate(dboverlaid)


Deceptive numbers

Repunits are numbers that consist entirely of repetitions of the digit one (unity).  The notation '''Rn''' symbolizes the repunit made up of '''n''' ones.

Every prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''.

;E.G.

The repunit '''R6''' is evenly divisible by '''7'''.

111111 / 7 = 15873

The repunit '''R42''' is evenly divisible by '''43'''.

111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677

And so on.

There are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''.

The repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13).

111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221

;Task

* Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1'''

;See also

;* [https://www.numbersaplenty.com/set/deceptive_number Numbers Aplenty - Deceptive numbers]
;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}

Solution:
#include

unsigned modpow(unsigned b, unsigned e, unsigned m)
{
    unsigned p;
    for (p = 1; e; e >>= 1) {
        if (e & 1)
            p = p * b % m;
        b = b * b % m;
    }
    return p;
}

int is_deceptive(unsigned n)
{
    unsigned x;
    if (n & 1 && n % 3 && n % 5) {
        for (x = 7; x * x <= n; x += 6) {
            if (!(n % x && n % (x + 4)))
                return modpow(10, n - 1, n) == 1;
        }
    }
    return 0;
}

int main(void)
{
    unsigned c, i = 49;
    for (c = 0; c != 50; ++i) {
        if (is_deceptive(i)) {
            printf(" %u", i);
            ++c;
        }
    }
    return 0;
}


Deceptive numbers

Solution:
from itertools import count, islice
from math import isqrt

def is_deceptive(n):
    if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:
        for d in range(7, isqrt(n) + 1, 6):
            if not (n % d and n % (d + 4)): return True
    return False

print(*islice(filter(is_deceptive, count()), 100))


Deepcopy

;Task:
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.

The task should show:

* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.

* Any limitations of the method.

* That the structure and its copy are different.

* Suitable links to external documentation for common libraries.

Solution:
#include
#include

typedef struct elem{
	int data;
	struct elem* next;
}cell;

typedef cell* list;

void addToList(list *a,int num){
	list temp, holder;

	if(*a==NULL){
		*a = (list)malloc(sizeof(cell));
		(*a)->data = num;
		(*a)->next = NULL;
	}
	else{
		temp = *a;

		while(temp->next!=NULL)
			temp = temp->next;

		holder = (list)malloc(sizeof(cell));
		holder->data = num;
		holder->next = NULL;

		temp->next = holder;
	}
}

list copyList(list a){
	list b, tempA, tempB, temp;

	if(a!=NULL){
		b = (list)malloc(sizeof(cell));
		b->data = a->data;
		b->next = NULL;

		tempA = a->next;
		tempB = b;

		while(tempA!=NULL){
			temp = (list)malloc(sizeof(cell));
			temp->data = tempA->data;
			temp->next = NULL;

			tempB->next = temp;
			tempB = temp;

			tempA = tempA->next;
		}
	}

	return b;
}

void printList(list a){
	list temp = a;

	while(temp!=NULL){
		printf("%d,",temp->data);
		temp = temp->next;
	}
	printf("\b");
}

int main()
{
	list a,b;
	int i;

	for(i=1;i<=5;i++)
		addToList(&a,i);

	printf("List a is : ");

	printList(a);

	b = copyList(a);

	free(a);

	printf("\nList a destroyed, List b is : ");

	printList(b);

	return 0;
}


Deepcopy

Solution:
var deepcopy = function(o){
  return JSON.parse(JSON.stringify(src));
};

var src = {foo:0,bar:[0,1]};
print(JSON.stringify(src));
var dst = deepcopy(src);
print(JSON.stringify(src));


Deming's funnel

W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings.  In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern.  He applied a sequence of "rules" to try to improve performance.  In each case the experiment begins with the funnel positioned directly over the target.

* '''Rule 1''': The funnel remains directly above the target.
* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop.  E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment.  E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
* '''Rule 4''': The funnel is moved directly over the last place a marble landed.

Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys.  '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule.

Note that rules 2, 3, and 4 give successively worse results.  Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.

'''Stretch goal 1''': Generate fresh pseudorandom data.  The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.

'''Stretch goal 2''': Show scatter plots of all four results.

;Further information:
* Further [http://blog.newsystemsthinking.com/w-edwards-deming-and-the-funnel-experiment/ explanation and interpretation]
* [https://www.youtube.com/watch?v=2VogtYRc9dA Video demonstration] of the funnel experiment at the Mayo Clinic.

Solution:
import math

dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,
       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201,
       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,
       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,
       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,
       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,
       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799,
       0.087]

dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,
       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188,
       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,
       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038,
       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445,
       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044,
       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901,
       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]

def funnel(dxs, rule):
    x, rxs = 0, []
    for dx in dxs:
        rxs.append(x + dx)
        x = rule(x, dx)
    return rxs

def mean(xs): return sum(xs) / len(xs)

def stddev(xs):
    m = mean(xs)
    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))

def experiment(label, rule):
    rxs, rys = funnel(dxs, rule), funnel(dys, rule)
    print label
    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))
    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))
    print

experiment('Rule 1:', lambda z, dz: 0)
experiment('Rule 2:', lambda z, dz: -dz)
experiment('Rule 3:', lambda z, dz: -(z+dz))
experiment('Rule 4:', lambda z, dz: z+dz)


Department numbers

There is a highly organized city that has decided to assign a number to each of their departments:
::*   police department
::*   sanitation department
::*   fire department

Each department can have a number between   '''1'''   and   '''7'''   (inclusive).

The three department numbers are to be unique (different from each other) and must add up to   '''12'''.

The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.

;Task:
Write a computer program which outputs all valid combinations.

Possible output   (for the 1st and 14th solutions):

  --police--  --sanitation--  --fire--
      2             3            7
      6             5            1

Solution:
#include

int main()
{
	int police,sanitation,fire;

	printf("Police     Sanitation         Fire\n");
	printf("----------------------------------");

	for(police=2;police<=6;police+=2){
		for(sanitation=1;sanitation<=7;sanitation++){
			for(fire=1;fire<=7;fire++){
				if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){
					printf("\n%d\t\t%d\t\t%d",police,sanitation,fire);
				}
			}
		}
	}

	return 0;
}


Department numbers

Solution:
from itertools import permutations

def solve():
    c, p, f, s = "\\,Police,Fire,Sanitation".split(',')
    print(f"{c:>3}  {p:^6} {f:^4} {s:^10}")
    c = 1
    for p, f, s in permutations(range(1, 8), r=3):
        if p + s + f == 12 and p % 2 == 0:
            print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
            c += 1

if __name__ == '__main__':
    solve()


Descending primes

Generate and show all primes with strictly descending decimal digits.

;See also
;* OEIS:A052014 - Primes with distinct digits in descending order

;Related:
*[[Ascending primes]]

Solution:
#include

int ispr(unsigned int n) {
    if ((n & 1) == 0 || n < 2) return n == 2;
    for (unsigned int j = 3; j * j <= n; j += 2)
      if (n % j == 0) return 0; return 1; }

int main() {
  unsigned int c = 0, nc, pc = 9, i, a, b, l,
    ps[128], nxt[128];
  for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;
  while (1) {
    nc = 0;
    for (i = 0; i < pc; i++) {
        if (ispr(a = ps[i]))
          printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
        for (b = a * 10, l = a % 10 + b++; b < l; b++)
          nxt[nc++] = b;
      }
      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
      else break;
    }
    printf("\n%d descending primes found", c);
}


Descending primes

Solution:
from sympy import isprime

def descending(xs=range(10)):
    for x in xs:
        yield x
        yield from descending(x*10 + d for d in range(x%10))

for i, p in enumerate(sorted(filter(isprime, descending()))):
    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')

print()


Detect division by zero

[[Category:Simple]]
;Task:
Write a function to detect a   ''divide by zero error''   without checking if the denominator is zero.

Solution:
#include 	/* INT_MIN */
#include 	/* siglongjmp(), sigsetjmp() */
#include 	/* perror(), printf() */
#include 	/* exit() */
#include 	/* sigaction(), sigemptyset() */

static sigjmp_buf fpe_env;

/*
 * This SIGFPE handler jumps to fpe_env.
 *
 * A SIGFPE handler must not return, because the program might retry
 * the division, which might cause an infinite loop. The only safe
 * options are to _exit() the program or to siglongjmp() out.
 */
static void
fpe_handler(int signal, siginfo_t *w, void *a)
{
	siglongjmp(fpe_env, w->si_code);
	/* NOTREACHED */
}

/*
 * Try to do x / y, but catch attempts to divide by zero.
 */
void
try_division(int x, int y)
{
	struct sigaction act, old;
	int code;
	/*
	 * The result must be volatile, else C compiler might delay
	 * division until after sigaction() restores old handler.
	 */
	volatile int result;

	/*
	 * Save fpe_env so that fpe_handler() can jump back here.
	 * sigsetjmp() returns zero.
	 */
	code = sigsetjmp(fpe_env, 1);
	if (code == 0) {
		/* Install fpe_handler() to trap SIGFPE. */
		act.sa_sigaction = fpe_handler;
		sigemptyset(&act.sa_mask);
		act.sa_flags = SA_SIGINFO;
		if (sigaction(SIGFPE, &act, &old) < 0) {
			perror("sigaction");
			exit(1);
		}

		/* Do division. */
		result = x / y;

		/*
		 * Restore old hander, so that SIGFPE cannot jump out
		 * of a call to printf(), which might cause trouble.
		 */
		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}

		printf("%d / %d is %d\n", x, y, result);
	} else {
		/*
		 * We caught SIGFPE. Our fpe_handler() jumped to our
		 * sigsetjmp() and passes a nonzero code.
		 *
		 * But first, restore old handler.
		 */
		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}

		/* FPE_FLTDIV should never happen with integers. */
		switch (code) {
		case FPE_INTDIV: /* integer division by zero */
		case FPE_FLTDIV: /* float division by zero */
			printf("%d / %d: caught division by zero!\n", x, y);
			break;
		default:
			printf("%d / %d: caught mysterious error!\n", x, y);
			break;
		}
	}
}

/* Try some division. */
int
main()
{
	try_division(-44, 0);
	try_division(-44, 5);
	try_division(0, 5);
	try_division(0, 0);
	try_division(INT_MIN, -1);
	return 0;
}


Detect division by zero

Solution:
function divByZero(dividend,divisor)
{
	var quotient=dividend/divisor;
        if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity
        return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively
}
alert(divByZero(0,0));


Detect division by zero

Solution:
def div_check(x, y):
  try:
    x / y
  except ZeroDivisionError:
    return True
  else:
    return False