task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Euphoria
Euphoria
integer idM, idF   function F(integer n) if n = 0 then return 1 else return n - call_func(idM,{F(n-1)}) end if end function   idF = routine_id("F")   function M(integer n) if n = 0 then return 0 else return n - call_func(idF,{M(n-1)}) end if end function   idM = r...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Sidef
Sidef
func multisplit(sep, str, keep_sep=false) { sep = sep.map{.escape}.join('|'); var re = Regex.new(keep_sep ? "(#{sep})" : sep); str.split(re, -1); }   [false, true].each { |bool| say multisplit(%w(== != =), 'a!===b=!=c', keep_sep: bool); }
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Swift
Swift
extension String { func multiSplit(on seps: [String]) -> ([Substring], [(String, (start: String.Index, end: String.Index))]) { var matches = [Substring]() var matched = [(String, (String.Index, String.Index))]() var i = startIndex var lastMatch = startIndex   main: while i != endIndex { for ...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Factor
Factor
1000 [ { 1 } clone ] replicate
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#FreeBASIC
FreeBASIC
dim as foo array(1 to n)
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Forth
Forth
include FMS-SI.f include FMS-SILib.f     \ create a list of VAR objects the right way \ each: returns a unique object reference o{ 0 0 0 } dup p: o{ 0 0 0 } dup each: drop . 10774016 dup each: drop . 10786896 dup each: drop . 10786912     \ create a list of VAR objects the wrong way \ each: returns the same obje...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Ada
Ada
with Ada.Text_IO;   procedure Move_To_Front is   subtype Lower_Case is Character range 'a' .. 'z'; subtype Index is Integer range 0 .. 25; type Table is array (Index) of Lower_Case; Alphabet: constant Table := "abcdefghijklmnopqrstuvwxyz"; type Number_String is array(Positive range <>) of Natural;   ...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#ALGOL_W
ALGOL W
integer array a ( 1 :: 5, 1 :: 4, 1 :: 3, 1 :: 2 );
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#C
C
/*Single dimensional array of integers*/ int a[10];   /*2-dimensional array, also called matrix of floating point numbers. This matrix has 3 rows and 2 columns.*/   float b[3][2];   /*3-dimensional array ( Cube ? Cuboid ? Lattice ?) of characters*/   char c[4][5][6];   /*4-dimensional array (Hypercube ?) of doubles*/  ...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#C
C
#include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_multifit.h>   double w[] = { 52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46 }; double h[] = { 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#ALGOL_W
ALGOL W
begin  % returns the multifactorial of n with the specified degree % integer procedure multifactorial ( integer value n, degree ) ; begin integer mf, v; mf := v := n; while begin v := v - degree; v > 1 end do mf :...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 FUNCTION multiFactorial (n, degree) 110 IF n < 2 THEN 120 LET multiFactorial = 1 130 EXIT FUNCTION 140 END IF 150 LET result = n 160 FOR i = n - degree TO 2 STEP -degree 170 LET result = result * i 180 NEXT i 190 LET multiFactorial = result 200 END FUNCTION 210 220 FOR degree =...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#ActionScript
ActionScript
  package {   import flash.display.Sprite; import flash.events.Event; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat;   public class MousePosition extends Sprite {   private var _textField:TextField = new TextField();   public func...
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Nim
Nim
import math, sequtils, strutils   const MaxDepth = 6 Max = 36^MaxDepth - 1 # Max value for MaxDepth digits in base 36. Digits = "0123456789abcdefghijklmnopqrstuvwxyz"   # Sieve of Erathostenes. var composite: array[1..(Max div 2), bool] # Only odd numbers. for i in 1..composite.high: let n = 2 * i + 1 let...
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Pascal
Pascal
program MAXBaseStringIsPrimeInBase; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils; const CharOfBase= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; MINBASE = 2; MAXBASE = 62;//36;//62; MAXDIGITCOUNT = 5;//6; type tdigits = pa...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Draco
Draco
byte SIZE = 8; word count;   proc solve([*] int hist; int col) void: int i, j, n; n := dim(hist, 1); if col = n then count := count + 1; writeln(); writeln("No. ", count); writeln("-----"); for i from 0 upto n-1 do for j from 0 upto n-1 do ...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Maple
Maple
numtheory:-order( a, n )
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MultiplicativeOrder[37, 1000] MultiplicativeOrder[10^100 + 1, 7919] (*10^3th prime number Prime[1000]*) MultiplicativeOrder[10^1000 + 1, 15485863] (*10^6th prime number*) MultiplicativeOrder[10^10000 - 1, 22801763489] (*10^9th prime number*) MultiplicativeOrder[13, 1 + 10^80] MultiplicativeOrder[11,...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Prolog
Prolog
  iroot(_, 0, 0) :- !. iroot(M, N, R) :- M > 1, (N > 0 -> irootpos(M, N, R) ; N /\ 1 =:= 1, NegN is -N, irootpos(M, NegN, R0), R is -R0).   irootpos(N, A, R) :- X0 is 1 << (msb(A) div N), % initial guess is 2^(log2(A) / N) newton(N, A, X0, X1), iroot_loop(A, X1, N, A, R)...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#jq
jq
  # ordinalize an integer input, positive or negative def ordinalize: (if . < 0 then -(.) else . end) as $num | ($num % 100) as $small | (if 11 <= $small and $small <= 13 then "th" else ( $num % 10) | (if . == 1 then "st" elif . == 2 then "nd" elif . == 3 then "rd" else ...
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#zkl
zkl
(26).toString(16) //--> "1a" "1a".toInt(16) //-->26
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Sidef
Sidef
func is_narcissistic(n) { n.digits »**» n.len -> sum == n }   var count = 0 for i in ^Inf { if (is_narcissistic(i)) { say "#{++count}\t#{i}" break if (count == 25) } }
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Swift
Swift
extension BinaryInteger { @inlinable public var isNarcissistic: Bool { let digits = String(self).map({ Int(String($0))! }) let m = digits.count   guard m != 1 else { return true }   return digits.map({ $0.power(m) }).reduce(0, +) == self }   @inlinable public func power(_ n: Self) ->...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#JavaScript
JavaScript
for (let i of [...Array(5000).keys()] .filter(n => n == n.toString().split('') .reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0))) console.log(i);
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#F.23
F#
let rec f n = match n with | 0 -> 1 | _ -> n - (m (f (n-1))) and m n = match n with | 0 -> 0 | _ -> n - (f (m (n-1)))
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Tcl
Tcl
proc simplemultisplit {text sep} { set map {}; foreach s $sep {lappend map $s "\uffff"} return [split [string map $map $text] "\uffff"] } puts [simplemultisplit "a!===b=!=c" {"==" "!=" "="}]
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#TXR
TXR
@(next :args) @(coll :gap 0)@(choose :shortest tok)@\ @tok@{sep /==/}@\ @(or)@\ @tok@{sep /!=/}@\ @(or)@\ @tok@{sep /=/}@\ @(end)@(end)@tail @(output) @(rep)"@tok" {@sep} @(end)"@tail" @(end)
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Fortran
Fortran
  program multiple ! Define a simple type type T integer :: a = 3 end type T   ! Define a type containing a pointer type S integer, pointer :: a end type S   type(T), allocatable :: T_array(:) type(S), allocatable :: S_same(:) integer :: i integer, target :: v integer, ...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Go
Go
func nxm(n, m int) [][]int { d2 := make([][]int, n) for i := range d2 { d2[i] = make([]int, m) } return d2 }
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#ALGOL_68
ALGOL 68
BEGIN # find some Motzkin numbers # PR read "primes.incl.a68" PR # returns a table of the Motzkin numbers 0 .. n # OP MOTZKIN = ( INT n )[]LONG LONG INT: BEGIN [ 0 : n ]LONG LONG INT m; IF n >= 0 THEN m[ 0 ] := 1; IF n >= 1 THEN ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Aime
Aime
decode(list l) { integer c, e; data al, s;   al = "abcdefghijklmnopqrstuvwxyz"; for (, e in l) { s.append(c = al[e]); al.delete(e).insert(0, c); }   s; }   encode(data s) { integer c, e; data al; list l;   al = "abcdefghijklmnopqrstuvwxyz"; for (, c in s) { ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#ALGOL_68
ALGOL 68
# move the character at text pos to the front of text # # note text pos is based from 0 # PROC move to front = ( STRING text, INT text pos )STRING: IF text pos < 1 THEN # the character is already at the front (or not in the string) ...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#C.23
C#
var array = new int[,] { //Dimensions are inferred { 1, 2, 3 }, { 4, 5, 6} } //Accessing a single element: array[0, 0] = 999;   //To create a 4-dimensional array with all zeroes: var array = new int[5, 4, 3, 2];
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#C.2B.2B
C++
#include <iostream> #include <vector>   // convienince for printing the contents of a collection template<typename T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) { auto it = c.cbegin(); auto end = c.cend();   out << '['; if (it != end) { out << *it; it = std::nex...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#C.2B.2B
C++
#include <array> #include <iostream>   void require(bool condition, const std::string &message) { if (condition) { return; } throw std::runtime_error(message); }   template<typename T, size_t N> std::ostream &operator<<(std::ostream &os, const std::array<T, N> &a) { auto it = a.cbegin(); aut...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Arturo
Arturo
multifact: function [n deg][ if? n =< deg -> n else -> n * multifact n-deg deg ]   loop 1..5 'i [ prints ["Degree" i ":"] loop 1..10 'j [ prints [multifact j i " "] ] print "" ]
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Ada
Ada
with GLib; use GLib; with Gtk.Button; use Gtk.Button; with Gtk.Label; use Gtk.Label; with Gtk.Window; use Gtk.Window; with Gtk.Widget; use Gtk.Widget; with Gtk.Table; use Gtk.Table;   with Gtk.Handlers; with Gtk.Main;   procedure Tell_Mouse is Window : Gtk_Window; Grid  : Gtk_Table; Button : Gtk...
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::AllUtils <firstidx max>; use ntheory qw/fromdigits todigitstring primes/;   my(%prime_base, %max_bases, $l);   my $chars = 5; my $upto = fromdigits( '1' . 'Z' x $chars, 36); my @primes = @{primes( $upto )};   for my $base (2..36) { my $n = todigitstring($bas...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#EasyLang
EasyLang
subr show_sol print "Solution " & n_sol print "" for i range n write " " for j range n if j = x[i] write "Q " else write ". " . . print "" . print "" . subr test ok = 1 for i range y if x[y] = x[i] or abs (x[i] - x[y]) = abs (y - i) ok = 0 ....
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Maxima
Maxima
zn_order(37, 1000); /* 100 */   zn_order(10^100 + 1, 7919); /* 3959 */   zn_order(10^1000 + 1, 15485863); /* 15485862 */   zn_order(10^10000 - 1, 22801763489); /* 22801763488 */   zn_order(13, 1 + 10^80); /* 109609547199756140150989321269669269476675495992554276140800 */   zn_order(11, 1 + 10^100); /* 25834961127247525...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Nim
Nim
import strformat import bignum   type PExp = tuple[prime: Int; exp: uint]   let one = newInt(1) two = newInt(2) ten = newInt(10)     func sqrt(n: Int): Int = var s = n while true: result = s s = (n div result + result) shr 1 if s >= result: break     proc factor(n: Int): seq[PExp] = var n = n ...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#PureBasic
PureBasic
#Def_p=0.001   Procedure.d Nth_root(n.i, A.d, p.d=#Def_p) Protected Dim x.d(1) x(0)=A: x(1)=A/n While Abs(x(1)-x(0))>p x(0)=x(1) x(1)=((n-1.0)*x(1)+A/Pow(x(1),n-1.0))/n Wend ProcedureReturn x(1) EndProcedure   ;////////////////////////////// Debug "125'th root of 5642 is" Debug Pow(5642,1/125) Debug ...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Julia
Julia
using Printf
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Tcl
Tcl
proc isNarcissistic {n} { set m [string length $n] for {set t 0; set N $n} {$N} {set N [expr {$N / 10}]} { incr t [expr {($N%10) ** $m}] } return [expr {$n == $t}] }   proc firstNarcissists {target} { for {set n 0; set count 0} {$count < $target} {incr n} { if {[isNarcissistic $n]} { incr cou...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#jq
jq
def sigma( stream ): reduce stream as $x (0; . + $x ) ;   def ismunchausen: def digits: tostring | split("")[] | tonumber; . == sigma(digits | pow(.;.));   # Munchausen numbers from 1 to 5000 inclusive: range(1;5001) | select(ismunchausen)
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Factor
Factor
DEFER: F : M ( n -- n' ) dup 0 = [ dup 1 - M F - ] unless ; : F ( n -- n' ) dup 0 = [ drop 1 ] [ dup 1 - F M - ] if ;
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#UNIX_Shell
UNIX Shell
multisplit() { local str=$1 shift local regex=$( IFS='|'; echo "$*" ) local sep while [[ $str =~ $regex ]]; do sep=${BASH_REMATCH[0]} words+=( "${str%%${sep}*}" ) seps+=( "$sep" ) str=${str#*$sep} done words+=( "$str" ) }   words=() seps=()   original="a!===...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Groovy
Groovy
def createFoos1 = { n -> (0..<n).collect { new Foo() } }
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Haskell
Haskell
replicateM n makeTheDistinctThing
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Icon_and_Unicon
Icon and Unicon
  items_wrong := list (10, []) # prints '0' for size of each item every item := !items_wrong do write (*item) # after trying to add an item to one of the lists push (items_wrong[1], 2) # now prints '1' for size of each item every item := !items_wrong do write (*item)  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#AWK
AWK
  # syntax: GAWK --bignum -f MOTZKIN_NUMBERS.AWK BEGIN { print(" n Motzkin[n] prime") limit = 41 m[0] = m[1] = 1 for (i=2; i<=limit; i++) { m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2) } for (i=0; i<=limit; i++) { printf("%2d %18d %3d\n",i,m[i],is_prime(m[i])) } ...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#BASIC256
BASIC256
dim M(42) M[0] = 1 : M[1] = 1 print rjust("1",18) : print rjust("1",18)   for n = 2 to 41 M[n] = M[n-1] for i = 0 to n-2 M[n] += M[i]*M[n-2-i] next i print rjust(string(M[n]),18); chr(9); if isPrime(M[n]) then print "is a prime" else print next n end   function isPrime(v) if v <= 1 then return False for i = 2 ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#AutoHotkey
AutoHotkey
MTF_Encode(string){ str := "abcdefghijklmnopqrstuvwxyz" loop, parse, string code .= (A_Index>1 ? ",":"") . InStr(str, A_LoopField) - 1 , str := A_LoopField . StrReplace(str, A_LoopField) return code }   MTF_Decode(code){ str := "abcdefghijklmnopqrstuvwxyz" loop, parse, code, `, string .= (letter := SubStr(str,...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#D
D
import std.stdio;   /* * Using just what is built-in, D only supports single dimension arrays. Like other languages, arrays can be built up as jagged arrays. * Arrays can either be created with a fixed size, or dynamically with support for resizing. */ void nativeExample() { int[3] staticArray; // Statically all...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#C.23
C#
using System; using MathNet.Numerics.LinearRegression; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double;   class Program { static void Main(string[] args) { var col = DenseVector.OfArray(new double[] { 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.7...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#AutoHotkey
AutoHotkey
Loop, 5 { Output .= "Degree " (i := A_Index) ": " Loop, 10 Output .= MultiFact(A_Index, i) (A_Index = 10 ? "`n" : ", ") } MsgBox, % Output   MultiFact(n, d) { Result := n while 1 < n -= d Result *= n return, Result }
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#AmigaBASIC
AmigaBASIC
MOUSE ON   WHILE 1 m=MOUSE(0) PRINT MOUSE(1),MOUSE(2) WEND
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#AppleScript
AppleScript
use framework "AppKit"   tell application id "com.apple.SystemEvents" to tell ¬ (the first process where it is frontmost) to ¬ set {x, y} to the front window's position   tell the current application set H to NSHeight(its NSScreen's mainScreen's frame) tell [] & its NSEvent's mouseLocation set item 1 to (item 1) ...
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Phix
Phix
with javascript_semantics constant maxbase=36 -- or 62 function evalpoly(integer x, sequence p) integer result = 0 for y=1 to length(p) do result = result*x + p[y] end for return result end function function stringify(sequence digits) string res = repeat('0',length(digits)) for i=1 to...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#EchoLisp
EchoLisp
  ;; square num is i + j*N (define-syntax-rule (sq i j) (+ i (* j N)))   ;; compute diag number for each square (define (do-diag1 i0 j0 dnum into: dnum1 N) ;; ++i and ++j diags (for [(i (in-range i0 N)) (j (in-range j0 N))] ;;(writeln i j 'diag1 dnum) (vector-set! dnum1 (sq i j) dnum)))   (define (do-diag2 i0 ...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#PARI.2FGP
PARI/GP
znorder(Mod(a,n))
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Perl
Perl
use ntheory qw/znorder/; say znorder(54, 100001); use bigint; say znorder(11, 1 + 10**100);
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Python
Python
from decimal import Decimal, getcontext   def nthroot (n, A, precision): getcontext().prec = precision   n = Decimal(n) x_0 = A / n #step 1: make a while guess. x_1 = 1 #need it to exist before step 2 while True: #step 2: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Kotlin
Kotlin
fun Int.ordinalAbbrev() = if (this % 100 / 10 == 1) "th" else when (this % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" }   fun IntRange.ordinalAbbrev() = map { "$it" + it.ordinalAbbrev() }.joinToString(" ")   fun main(args: Array<String>) { listOf((0..25), (250..265), (1000..1025)).forEach { pr...
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#UNIX_Shell
UNIX Shell
function narcissistic { integer n=$1 len=${#n} sum=0 i for ((i=0; i<len; i++)); do (( sum += pow(${n:i:1}, len) )) done (( sum == n )) }   nums=() for ((n=0; ${#nums[@]} < 25; n++)); do narcissistic $n && nums+=($n) done echo "${nums[*]}" echo "elapsed: $SECONDS"
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Julia
Julia
println([n for n = 1:5000 if sum(d^d for d in digits(n)) == n])
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#FALSE
FALSE
[$[$1-f;!m;!-1-]?1+]f: [$[$1-m;!f;!- ]? ]m: [0[$20\>][\$@$@!." "1+]#%%]t: f; t;!" "m; t;!
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#VBScript
VBScript
  Function multisplit(s,sep) arr_sep = Split(sep,"|") For i = 0 To UBound(arr_sep) arr_s = Split(s,arr_sep(i)) s = Join(arr_s,",") Next multisplit = s End Function   Function multisplit_extra(s,sep) Set dict_sep = CreateObject("Scripting.Dictionary") arr_sep = Split(sep,"|") For i = 0 To UBound(arr_sep) di...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Wren
Wren
import "/pattern" for Pattern import "/fmt" for Fmt   var input = "a!===b=!=c" var p = Pattern.new("[/=/=|!/=|/=]") var separators = p.findAll(input) System.print("The separators matched and their starting/ending indices are:") for (sep in separators) { System.print("  %(Fmt.s(-4, Fmt.q(sep.text))) between %(sep.sp...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#J
J
i.
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Java
Java
Foo[] foos = new Foo[n]; // all elements initialized to null for (int i = 0; i < foos.length; i++) foos[i] = new Foo();   // incorrect version: Foo[] foos_WRONG = new Foo[n]; Arrays.fill(foos, new Foo()); // new Foo() only evaluated once
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#JavaScript
JavaScript
var a = new Array(n); for (var i = 0; i < n; i++) a[i] = new Foo();
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Burlesque
Burlesque
41rz{{2./}c!rz2?*{nr}c!\/2?/{JJ2.*J#Rnr#r\/+.nr.-}m[?*++it+.}m[Jp^#R{~]}5E!{fCL[1==}f[#r
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#C
C
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) retu...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Bracmat
Bracmat
( encode = string symboltable .  !arg:(?string.?symboltable) & vap $ ( ( = A Z i .  !symboltable:?A [?i !arg ?Z & !arg !A !Z:?symboltable & !i ) . !string ) ) & ( decode = indices symboltable ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#C
C
#include<stdio.h> #include<stdlib.h> #include<string.h>   #define MAX_SIZE 100   int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); //returns pointer to location of char c in string str shift=q-p; // no of characters...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#EchoLisp
EchoLisp
(require 'math) ;; dot-product   ;; dims = vector #(d1 d2 .....) ;; allocates a new m-array (define (make-m-array dims (init 0)) ;; allocate 2 + d1*d2*d3... consecutive cells (define msize (apply * (vector->list dims))) (define m-array (make-vector (+ 2 msize) init))   ;; compute displacements vector once for all ...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Common_Lisp
Common Lisp
  ;; Solve a linear system AX=B where A is symmetric and positive definite, so it can be Cholesky decomposed. (defun linsys (A B) (let* ((n (car (array-dimensions A))) (m (cadr (array-dimensions B))) (y (make-array n :element-type 'long-float :initial-element 0.0L0)) (X (make-array ...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#AWK
AWK
  # syntax: GAWK -f MULTIFACTORIAL.AWK # converted from Go BEGIN { for (k=1; k<=5; k++) { printf("degree %d:",k) for (n=1; n<=10; n++) { printf(" %d",multi_factorial(n,k)) } printf("\n") } exit(0) } function multi_factorial(n,k, r) { r = 1 for (; n>1; n-=k) { r...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#AutoHotkey
AutoHotkey
#i:: ; (Optional) Assigns a hotkey to display window info, Windows+i MouseGetPos, x, y ; Gets x/y pos relative to active window WinGetActiveTitle, WinTitle ; Gets active window title Traytip, Mouse position, x: %x%`ny: %y%`rWindow: %WinTitle%, 4 ; Displays the info as a Traytip for 4 seconds return
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#BBC_BASIC
BBC BASIC
MOUSE xmouse%, ymouse%, buttons% PRINT xmouse%, ymouse%
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   my %prime-base;   my $chars = 4; # for demonstration purposes. Change to 5 for the whole shmegegge.   my $threshold = ('1' ~ 'Z' x $chars).parse-base(36);   my @primes = $sieve.primes($threshold);   %prime-base.push: $_ for (2..36).map: -> $base { $threshold...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Eiffel
Eiffel
  class QUEENS   create make   feature {NONE} counter: INTEGER   place_queens(board: ARRAY[INTEGER]; level: INTEGER) local i, j: INTEGER safe: BOOLEAN do if level > board.count then counter := counter + 1 else from i := 1 until i > board.count loop safe := True ...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Phix
Phix
with javascript_semantics include mpfr.e procedure multi_order(mpz res, a, sequence p_and_k) mpz {pk,t,x,q,pz} = mpz_inits(5) mpz_set_si(res,1) if length(p_and_k)=1 then string {ps} = p_and_k mpz_set_str(pk,ps) mpz_sub_ui(t,pk,1) else atom {p, k} = p_and_k mpz_s...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#R
R
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) # 7131.5 nthroot(7, 0.5) # 49
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Racket
Racket
#lang racket   (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance))   (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root))   (define (loop current) (define next-guess (improve current)) ...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Lambdatalk
Lambdatalk
  {def fnOrdinalForm {lambda {:n} {if {and {<= 11 {% :n 100}} {>= 13 {% :n 100}}} then :nth else :n{A.get {% :n 10} th st nd rd th th th th th th}}}} -> fnOrdinalForm   {S.map fnOrdinalForm {S.serie 0 25}} -> 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st ...
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#VBA
VBA
Private Function narcissistic(n As Long) As Boolean Dim d As String: d = CStr(n) Dim l As Integer: l = Len(d) Dim sumn As Long: sumn = 0 For i = 1 To l sumn = sumn + (Mid(d, i, 1) - "0") ^ l Next i narcissistic = sumn = n End Function   Public Sub main() Dim s(24) As String Dim n...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Kotlin
Kotlin
// version 1.0.6   val powers = IntArray(10)   fun isMunchausen(n: Int): Boolean { if (n < 0) return false var sum = 0L var nn = n while (nn > 0) { sum += powers[nn % 10] if (sum > n.toLong()) return false nn /= 10 } return sum == n.toLong() }   fun main(args: Array<Str...
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Fantom
Fantom
  class Main { static Int f (Int n) { if (n <= 0) // ensure n > 0 return 1 else return n - m(f(n-1)) }   static Int m (Int n) { if (n <= 0) // ensure n > 0 return 0 else return n - f(m(n-1)) }   public static Void main () { 50.times |Int n| { echo (f(n)) } }...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Yabasic
Yabasic
t$ = "a!===b=!=c" s$ = "==,!=,="   dim n$(1)   n = token(s$, n$(), ",") dim p(n)   do l = len(t$) j = 0 for i = 1 to n p(i) = instr(t$, n$(i)) if p(i) and p(i) < l then l = p(i) : j = i end if next if not j print t$ : break print left$(t$, l - 1), " with separator ", n$(j) t$...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#zkl
zkl
fcn multisplit(text, sep){ lastmatch := i := 0; matches := List(); while(i < text.len()){ foreach j,s in ([0..].zip(sep)){ if(i == text.find(s,i)){ if(i > lastmatch) matches.append(text[lastmatch,i-lastmatch]); matches.append(T(j,i)); # Replace the string containing the matched separator...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#jq
jq
  def Array(atype; n): if atype == "number" then [ range(0;n) ] elif atype == "object" then [ range(0;n)| {"value": . } ] elif atype == "array" then [ range(0;n)| [.] ] elif atype == "string" then [ range(0;n)| tostring ] elif atype == "boolean" then if n == 0 then [] elif n == 1 then [false] elif n==2...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Julia
Julia
  foo() = rand() # repeated calls change the result with each call repeat([foo()], outer=5) # but this only calls foo() once, clones that first value  
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Kotlin
Kotlin
// version 1.1.2   class Foo { val id: Int   init { id = ++numCreated // creates a distict id for each object }   companion object { private var numCreated = 0 } }   fun main(args: Array<String>) { val n = 3 // say   /* correct approach - creates references to distinct object...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#C.23
C#
using System; using BI = System.Numerics.BigInteger;   class Program {   // has multiple factors (other than 1 and x) static bool hmf(BI x) { if (x < 4) return x == 1; if ((x & 1) == 0 || x % 3 == 0) return true; int l = (int)Math.Sqrt((double)x); // this limit works because the 40th to 80th Motzkin num...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#C.23
C#
  using System; using System.Collections.Generic; using System.Text;   namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); }   private stati...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Factor
Factor
USING: accessors arrays.shaped io kernel prettyprint sequences ;   ! Create a 4-dimensional array with increasing elements. { 2 3 4 5 } increasing   ! Check if an index is in bounds. { 0 0 0 0 } over shaped-bounds-check   ! Access and print the first element. "First element: " write get-shaped-row-major .   ! Set the f...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Forth
Forth
  4 5 6 7 8 CELL 5 darray test5d \ Creates the array i j k l m test5d \ Returns the address of test5d[ i, j, k, l, m ]   100 i j k l m test5d ! \ Sets contents of test5d[ i, j, k, l, m ] to 100 i j k l m test5d @ \ Gets contents of test5d[ i, j, k, l, m ]  
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#D
D
import std.algorithm; import std.array; import std.exception; import std.range; import std.stdio;   public class Matrix { private double[][] data; private size_t rowCount; private size_t colCount;   public this(size_t size) in(size > 0, "Must have at least one element") { this(size, size...