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/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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Standard_ML
Standard ML
fun toBase b v = let fun toBase' (a, 0) = a | toBase' (a, v) = toBase' (v mod b :: a, v div b) in toBase' ([], v) end   fun fromBase b ds = foldl (fn (k, n) => n * b + k) 0 ds   val toAlphaDigits = let fun convert n = if n < 10 then chr (n + ord #"0") else chr (n + ord #"a" - 10) in implode o map convert end   val fromAlphaDigits = let fun convert c = if Char.isDigit c then ord c - ord #"0" else if Char.isUpper c then ord c - ord #"A" + 10 else if Char.isLower c then ord c - ord #"a" + 10 else raise Match in map convert o explode end
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Quackery
Quackery
[ [] swap [ 10 /mod rot join swap dup 0 = until ] drop ] is digits ( n --> [ )   [ dup digits 0 over size rot witheach [ over ** rot + swap ] drop = ] is narcissistic ( n --> b )   [] 0 [ dup narcissistic if [ tuck join swap ] 1+ over size 25 = until ] drop echo
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#R
R
for (u in 1:10000000) { j <- nchar(u) set2 <- c() for (i in 1:j) { set2[i] <- as.numeric(substr(u, i, i)) } control <- c() for (k in 1:j) { control[k] <- set2[k]^(j) } if (sum(control) == u) print(u) }
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class Game { static init() { Window.title = "Munching squares" var w = 512 var h = 512 Window.resize(w, h) Canvas.resize(w, h) for (x in 0...w) { for (y in 0...h) { var c = (x ^ y) & 255 Canvas.pset(x, y, Color.rgb(255-c, (c/2).floor, c)) } } }   static update() {}   static draw(alpha) {} }
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64 ' Cache n ^ n for the digits 1 to 9 ' Note than 0 ^ 0 specially treated as 0 (not 1) for this purpose Dim Shared powers(1 To 9) As UInteger For i As UInteger = 1 To 9 Dim power As UInteger = i For j As UInteger = 2 To i power *= i Next j powers(i) = power Next i   Function isMunchausen(n As UInteger) As Boolean Dim p As UInteger = n Dim As UInteger digit, sum While p > 0 digit = p Mod 10 If digit > 0 Then sum += powers(digit) p \= 10 Wend Return n = sum End Function   Print "The Munchausen numbers between 0 and 500000000 are : " For i As UInteger = 0 To 500000000 If isMunchausen(i) Then Print i Next   Print Print "Press any key to quit"   Sleep
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 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#E
E
def [F, M] := [ fn n { if (n <=> 0) { 1 } else { n - M(F(n - 1)) } }, fn n { if (n <=> 0) { 0 } else { 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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#REXX
REXX
/*REXX program splits a (character) string based on different separator delimiters.*/ parse arg $ /*obtain optional string from the C.L. */ if $='' then $= "a!===b=!=c" /*None specified? Then use the default*/ say 'old string:' $ /*display the old string to the screen.*/ null= '0'x /*null char. It can be most anything.*/ seps= '== != =' /*list of separator strings to be used.*/ /* [↓] process the tokens in SEPS. */ do j=1 for words(seps) /*parse the string with all the seps. */ sep=word(seps,j) /*pick a separator to use in below code*/ /* [↓] process characters in the sep.*/ do k=1 for length(sep) /*parse for various separator versions.*/ sep=strip(insert(null, sep, k), , null) /*allow imbedded "nulls" in separator, */ $=changestr(sep, $, null) /* ··· but not trailing "nulls". */ /* [↓] process strings in the input. */ do until $==old; old=$ /*keep changing until no more changes. */ $=changestr(null || null, $, null) /*reduce replicated "nulls" in string. */ end /*until*/ /* [↓] use BIF or external program.*/ sep=changestr(null, sep, '') /*remove true nulls from the separator.*/ end /*k*/ end /*j*/   showNull= ' {} ' /*just one more thing, display the ··· */ $=changestr(null, $, showNull) /* ··· showing of "null" chars. */ say 'new string:' $ /*now, display the new string to term. */ /*stick a fork in it, we're all done. */
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#AutoHotkey
AutoHotkey
a := [] Loop, %n% a[A_Index] := 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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#BBC_BASIC
BBC BASIC
REM Determine object count at runtime: n% = RND(1000)   REM Declare an array of structures; all members are initialised to zero: DIM objects{(n%) a%, b$}   REM Initialise the objects to distinct values: FOR i% = 0 TO DIM(objects{()},1) objects{(i%)}.a% = i% objects{(i%)}.b$ = STR$(i%) NEXT   REM This is how to create an array of pointers to the same object: DIM objects%(n%), object{a%, b$} FOR i% = 0 TO DIM(objects%(),1) objects%(i%) = object{} NEXT
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Brat
Brat
n.of foo.new
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)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#11l
11l
F multifact(n, d) R product((n .< 1).step(-d))   L(d) 1..5 print(‘Degree ’d‘: ’(1..10).map(n -> multifact(n, @d)))
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 armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Common_Lisp
Common Lisp
(defun queens (n &optional (m n)) (if (zerop n) (list nil) (loop for solution in (queens (1- n) m) nconc (loop for new-col from 1 to m when (loop for row from 1 to n for col in solution always (/= new-col col (+ col row) (- col row))) collect (cons new-col solution)))))   (defun print-solution (solution) (loop for queen-col in solution do (loop for col from 1 to (length solution) do (write-char (if (= col queen-col) #\Q #\.))) (terpri)) (terpri))   (defun print-queens (n) (mapc #'print-solution (queens 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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#EchoLisp
EchoLisp
  (require 'bigint)   ;; factor-exp returns a list ((p k) ..) : a = p1^k1 * p2^k2 .. (define (factor-exp a) (map (lambda (g) (list (first g) (length g))) (group* (prime-factors a))))   ;; copied from Ruby (define (_mult_order a p k (x)) (define pk (expt p k)) (define t (* (1- p) (expt p (1- k)))) (define r 1) (for [((q e) (factor-exp t))] (set! x (powmod a (/ t (expt q e)) pk)) (while (!= x 1) (*= r q) (set! x (powmod x q pk)))) r)   (define (order a m) "multiplicative order : (order a m) → n : a^n = 1 (mod m)" (assert (= 1 (gcd a m)) "a and m must be coprimes") (define mopks (for/list [((p k) (factor-exp m))] (_mult_order a p k))) (for/fold (n 1) ((mopk mopks)) (lcm n mopk)))   ;; results order 37 1000) → 100 (order (+ (expt 10 100) 1) 7919) → 3959 (order (+ (expt 10 1000) 1) 15485863) → 15485862  
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.
#Phix
Phix
with javascript_semantics function pow_(atom x, integer e) atom r = 1 for i=1 to e do r *= x end for return r end function function nth_root(atom y, n) atom eps = 1e-15, -- relative accuracy x = 1 while 1 do -- atom d = ( y / power(x,n-1) - x ) / n atom d = ( y / pow_(x,n-1) - x ) / n x += d atom e = eps*x -- absolute accuracy if d > -e and d < e then exit end if end while return x end function procedure test(sequence yn) atom {y,n} = yn printf(1,"nth_root(%d,%d) = %.10g, builtin = %.10g\n",{y,n,nth_root(y,n),power(y,1/n)}) end procedure papply({{1024,10},{27,3},{2,2},{5642,125},{4913,3},{8,3},{16,2},{16,4},{125,3},{1000000000,3},{1000000000,9}},test)
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 the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Haskell
Haskell
import Data.Array   ordSuffs :: Array Integer String ordSuffs = listArray (0,9) ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"]   ordSuff :: Integer -> String ordSuff n = show n ++ suff n where suff m | (m `rem` 100) >= 11 && (m `rem` 100) <= 13 = "th" | otherwise = ordSuffs ! (m `rem` 10)   printOrdSuffs :: [Integer] -> IO () printOrdSuffs = putStrLn . unwords . map ordSuff   main :: IO () main = do printOrdSuffs [ 0.. 25] printOrdSuffs [ 250.. 265] printOrdSuffs [1000..1025]
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Swift
Swift
println(String(26, radix: 16)) // prints "1a"
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Racket
Racket
;; OEIS: A005188 defines these as positive numbers, so I will follow that definition in the function ;; definitions. ;; ;; 0: assuming it is represented as the single digit 0 (and not an empty string, which is not the ;; usual convention for 0 in decimal), is not: sum(0^0), which is 1. 0^0 is a strange one, ;; wolfram alpha calls returns 0^0 as indeterminate -- so I will defer to the brains behind OEIS ;; on the definition here, rather than copy what I'm seeing in some of the results here #lang racket   ;; Included for the serious efficientcy gains we get from fxvectors vs. general vectors. ;; ;; We also use fx+/fx- etc. As it stands, they do a check for fixnumness, for safety. ;; We can link them in as "unsafe" operations (see the documentation on racket/fixnum); ;; but we get a result from this program quickly enough for my tastes. (require racket/fixnum)   ; uses a precalculated (fx)vector of powers -- caller provided, please. (define (sub-narcissitic? N powered-digits) (let loop ((n N) (target N)) (cond [(fx> 0 target) #f] [(fx= 0 target) (fx= 0 n)] [(fx= 0 n) #f] [else (loop (fxquotient n 10) (fx- target (fxvector-ref powered-digits (fxremainder n 10))))])))   ; Can be used as standalone, since it doesn't require caller to care about things like order of ; magnitude etc. However, it *is* slow, since it regenerates the powered-digits vector every time. (define (narcissitic? n) ; n is +ve (define oom+1 (fx+ 1 (order-of-magnitude n))) (define powered-digits (for/fxvector ((i 10)) (expt i oom+1))) (sub-narcissitic? n powered-digits))   ;; next m primes > z (define (next-narcissitics z m) ; naming convention following math/number-theory's next-primes (let-values ([(i l) (for*/fold ((i (fx+ 1 z)) (l empty)) ((oom (in-naturals)) (dgts^oom (in-value (for/fxvector ((i 10)) (expt i (add1 oom))))) (n (in-range (expt 10 oom) (expt 10 (add1 oom)))) #:when (sub-narcissitic? n dgts^oom)  ; everyone else uses ^C to break...  ; that's a bit of a manual process, don't you think? #:final (= (fx+ 1 (length l)) m)) (values (+ i 1) (append l (list n))))]) l)) ; we only want the list   (module+ main (next-narcissitics 0 25)  ; here's another list... depending on whether you believe sloane or wolfram :-) (cons 0 (next-narcissitics 0 25)))   (module+ test (require rackunit)  ; example given at head of task (check-true (narcissitic? 153))  ; rip off the first 12 (and 0, since Armstrong numbers seem to be postivie) from  ; http://oeis.org/A005188 for testing (check-equal? (for/list ((i (in-range 12)) (n (sequence-filter narcissitic? (in-naturals 1)))) n) '(1 2 3 4 5 6 7 8 9 153 370 371)) (check-equal? (next-narcissitics 0 12) '(1 2 3 4 5 6 7 8 9 153 370 371)))
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y; [SetVid($101); \set 640x480 graphics with 8-bit color port($3C8):= 0; \set color registers with beautiful shades for X:= 0 to 256-1 do [port($3C9):= X>>1; \red port($3C9):= X>>3; \green port($3C9):= X; \blue ]; for Y:= 0 to 256-1 do \"color table" is array of 256 registers for X:= 0 to 256-1 do Point(X, Y, X|Y); \"|" = XOR, not OR which is "!" X:= ChIn(1); \wait for keystroke SetVid(3); \restore normal text mode ]
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Yabasic
Yabasic
w = 256   open window w, w   For x = 0 To w-1 For y = 0 To w-1 r =and(xor(x, y), 255) color r, and(r*2, 255), and(r*3, 255) dot x, y Next Next
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import( "fmt" "math" )   var powers [10]int   func isMunchausen(n int) bool { if n < 0 { return false } n64 := int64(n) nn := n64 var sum int64 = 0 for nn > 0 { sum += int64(powers[nn % 10]) if sum > n64 { return false } nn /= 10 } return sum == n64 }   func main() { // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose for i := 1; i <= 9; i++ { d := float64(i) powers[i] = int(math.Pow(d, d)) }   // check numbers 0 to 500 million fmt.Println("The Munchausen numbers between 0 and 500 million are:") for i := 0; i <= 500000000; i++ { if isMunchausen(i) { fmt.Printf("%d ", i) } } fmt.Println() }
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 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make -- Test of the mutually recursive functions Female and Male. do across 0 |..| 19 as c loop io.put_string (Female (c.item).out + " ") end io.new_line across 0 |..| 19 as c loop io.put_string (Male (c.item).out + " ") end end   Female (n: INTEGER): INTEGER -- Female sequence of the Hofstadter Female and Male sequences. require n_not_negative: n >= 0 do Result := 1 if n /= 0 then Result := n - Male (Female (n - 1)) end end   Male (n: INTEGER): INTEGER -- Male sequence of the Hofstadter Female and Male sequences. require n_not_negative: n >= 0 do Result := 0 if n /= 0 then Result := n - Female (Male (n - 1)) end end   end  
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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Ring
Ring
  # Project : Multisplit   str = "a!===b=!=c" sep = "=== != =! b =!=" sep = str2list(substr(sep, " ", nl)) for n = 1 to len(sep) pos = substr(str, sep[n]) see "" + n + ": " + substr(str, 1, pos-1) + " Sep By: " + sep[n] + nl next  
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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Ruby
Ruby
text = 'a!===b=!=c' separators = ['==', '!=', '=']   def multisplit_simple(text, separators) text.split(Regexp.union(separators)) end   p multisplit_simple(text, separators) # => ["a", "", "b", "", "c"]  
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#C
C
foo *foos = malloc(n * sizeof(*foos)); for (int i = 0; i < n; i++) init_foo(&foos[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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#C.2B.2B
C++
// this assumes T is a default-constructible type (all built-in types are) T* p = new T[n]; // if T is POD, the objects are uninitialized, otherwise they are default-initialized   //If default initialisation is not what you want, or if T is a POD type which will be uninitialized for(size_t i = 0; i != n; ++i) p[i] = make_a_T(); //or some other expression of type T   // when you don't need the objects any more, get rid of them delete[] p;
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)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#360_Assembly
360 Assembly
* Multifactorial 09/05/2016 MULFACR CSECT USING MULFACR,13 SAVEAR B STM-SAVEAR(15) DC 17F'0' STM STM 14,12,12(13) prolog ST 13,4(15) " ST 15,8(13) " LR 13,15 " LA I,1 i=1 LOOPI C I,D do i=1 to deg BH ELOOPI leave i LA L,W+4 l=@p LA J,1 j=1 LOOPJ C J,N do j=1 to num BH ELOOPJ leave j LA R,1 r=1 LCR S,I s=-i LR K,J k=j LOOPK C K,=F'2' do k=j to 2 by s BL ELOOPK leave k MR RR,K r=r*k AR K,S k=k+s B LOOPK next k ELOOPK CVD R,Y pack r MVC X,=XL12'402020202020202020202120' ed mask ED X,Y+2 edit r MVC 0(8,L),X+4 output r LA L,8(L) l=l+8 LA J,1(J) j=j+1 B LOOPJ next j ELOOPJ WTO MF=(E,W) LA I,1(I) i=i+1 B LOOPI next i ELOOPI L 13,4(0,13) epilog LM 14,12,12(13) " XR 15,15 " BR 14 " N DC F'10' number D DC F'5' degree W DC 0F,H'84',H'0',CL80' ' length,zero,text X DS CL12 temp Y DS D packed PL8 I EQU 6 J EQU 7 K EQU 8 S EQU 9 RR EQU 10 even reg of R for MR opcode R EQU 11 L EQU 12 END MULFACR
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)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Multifactorial(INT n,d REAL POINTER res) REAL r   IntToReal(1,res) WHILE n>1 DO IntToReal(n,r) RealMult(res,r,res) n==-d OD RETURN   PROC Main() BYTE n,d REAL r   Put(125) PutE() ;clear the screen FOR d=1 TO 5 DO PrintF("Degree %B:",d) FOR n=1 TO 10 DO Multifactorial(n,d,r) Put(32) PrintR(r) OD PutE() OD RETURN
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 to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#C.2B.2B
C++
#include <algorithm> #include <cmath> #include <cstdint> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <primesieve.hpp>   class prime_sieve { public: explicit prime_sieve(uint64_t limit); bool is_prime(uint64_t n) const { return n == 2 || ((n & 1) == 1 && sieve[n >> 1]); }   private: std::vector<bool> sieve; };   prime_sieve::prime_sieve(uint64_t limit) : sieve((limit + 1) / 2, false) { primesieve::iterator iter; uint64_t prime = iter.next_prime(); // consume 2 while ((prime = iter.next_prime()) <= limit) { sieve[prime >> 1] = true; } }   template <typename T> void print(std::ostream& out, const std::vector<T>& v) { if (!v.empty()) { out << '['; auto i = v.begin(); out << *i++; for (; i != v.end(); ++i) out << ", " << *i; out << ']'; } }   std::string to_string(const std::vector<unsigned int>& v) { static constexpr char digits[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::string str; for (auto i : v) str += digits[i]; return str; }   bool increment(std::vector<unsigned int>& digits, unsigned int max_base) { for (auto i = digits.rbegin(); i != digits.rend(); ++i) { if (*i + 1 != max_base) { ++*i; return true; } *i = 0; } return false; }   void multi_base_primes(unsigned int max_base, unsigned int max_length) { prime_sieve sieve(static_cast<uint64_t>(std::pow(max_base, max_length))); for (unsigned int length = 1; length <= max_length; ++length) { std::cout << length << "-character strings which are prime in most bases: "; unsigned int most_bases = 0; std::vector< std::pair<std::vector<unsigned int>, std::vector<unsigned int>>> max_strings; std::vector<unsigned int> digits(length, 0); digits[0] = 1; std::vector<unsigned int> bases; do { auto max = std::max_element(digits.begin(), digits.end()); unsigned int min_base = 2; if (max != digits.end()) min_base = std::max(min_base, *max + 1); if (most_bases > max_base - min_base + 1) continue; bases.clear(); for (unsigned int b = min_base; b <= max_base; ++b) { if (max_base - b + 1 + bases.size() < most_bases) break; uint64_t n = 0; for (auto d : digits) n = n * b + d; if (sieve.is_prime(n)) bases.push_back(b); } if (bases.size() > most_bases) { most_bases = bases.size(); max_strings.clear(); } if (bases.size() == most_bases) max_strings.emplace_back(digits, bases); } while (increment(digits, max_base)); std::cout << most_bases << '\n'; for (const auto& m : max_strings) { std::cout << to_string(m.first) << " -> "; print(std::cout, m.second); std::cout << '\n'; } std::cout << '\n'; } }   int main(int argc, char** argv) { unsigned int max_base = 36; unsigned int max_length = 4; for (int arg = 1; arg + 1 < argc; ++arg) { if (strcmp(argv[arg], "-max_base") == 0) max_base = strtoul(argv[++arg], nullptr, 10); else if (strcmp(argv[arg], "-max_length") == 0) max_length = strtoul(argv[++arg], nullptr, 10); } if (max_base > 62) { std::cerr << "Max base cannot be greater than 62.\n"; return EXIT_FAILURE; } if (max_base < 2) { std::cerr << "Max base cannot be less than 2.\n"; return EXIT_FAILURE; } multi_base_primes(max_base, max_length); return EXIT_SUCCESS; }
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 armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Curry
Curry
  -- 8-queens implementation with the Constrained Constructor pattern -- Sergio Antoy -- Fri Jul 13 07:05:32 PDT 2001   -- Place 8 queens on a chessboard so that no queen can capture -- (and be captured by) any other queen.   -- Non-deterministic choice operator   infixl 0 ! X ! _ = X _ ! Y = Y   -- A solution is represented by a list of integers. -- The i-th integer in the list is the column of the board -- in which the queen in the i-th row is placed. -- Rows and columns are numbered from 1 to 8. -- For example, [4,2,7,3,6,8,5,1] is a solution where the -- the queen in row 1 is in column 4, etc. -- Any solution must be a permutation of [1,2,...,8].   -- The state of a queen is its position, row and column, on the board. -- Operation column is a particularly simple instance -- of a Constrained Constructor pattern. -- When it is invoked, it produces only valid states.   column = 1 ! 2 ! 3 ! 4 ! 5 ! 6 ! 7 ! 8   -- A path of the puzzle is a sequence of successive placements of -- queens on the board. It is not explicitly defined as a type. -- A path is a potential solution in the making.   -- Constrained Constructor on a path -- Any path must be valid, i.e., any column must be in the range 1..8 -- and different from any other column in the path. -- Furthermore, the path must be safe for the queens. -- No queen in a path may capture any other queen in the path. -- Operation makePath add column n to path c or fails.   makePath c n | valid c && safe c 1 = n:c where valid c | n =:= column = uniq c where uniq [] = True uniq (c:cs) = n /= c && uniq cs safe [] _ = True safe (c:cs) k = abs (n-c) /= k && safe cs (k+1) where abs x = if x < 0 then -x else x   -- extend the path argument till all the queens are on the board -- see the Incremental Solution pattern   extend p = if (length p == 8) then p else extend (makePath p x) where x free   -- solve the puzzle   main = extend []  
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Factor
Factor
USING: kernel math math.functions math.primes.factors sequences ;   : (ord) ( a pair -- n ) first2 dupd ^ swap dupd [ /i ] keep 1 - * divisors [ swap ^mod 1 = ] 2with find nip ;     : ord ( a n -- m ) 2dup gcd nip 1 = [ group-factors [ (ord) ] with [ lcm ] map-reduce ] [ 2drop 0/0. ] if ;
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { moTest(big.NewInt(37), big.NewInt(3343)) b := big.NewInt(100) moTest(b.Add(b.Exp(ten, b, nil), one), big.NewInt(7919)) moTest(b.Add(b.Exp(ten, b.SetInt64(1000), nil), one), big.NewInt(15485863)) moTest(b.Sub(b.Exp(ten, b.SetInt64(10000), nil), one), big.NewInt(22801763489))   moTest(big.NewInt(1511678068), big.NewInt(7379191741)) moTest(big.NewInt(3047753288), big.NewInt(2257683301)) }   func moTest(a, n *big.Int) { if a.BitLen() < 100 { fmt.Printf("ord(%v)", a) } else { fmt.Print("ord([big])") } if n.BitLen() < 100 { fmt.Printf(" mod %v ", n) } else { fmt.Print(" mod [big] ") } if !n.ProbablyPrime(20) { fmt.Println("not computed. modulus must be prime for this algorithm.") return } fmt.Println("=", moBachShallit58(a, n, factor(new(big.Int).Sub(n, one)))) }   var one = big.NewInt(1) var two = big.NewInt(2) var ten = big.NewInt(10)   func moBachShallit58(a, n *big.Int, pf []pExp) *big.Int { n1 := new(big.Int).Sub(n, one) var x, y, o1, g big.Int mo := big.NewInt(1) for _, pe := range pf { y.Quo(n1, y.Exp(pe.prime, big.NewInt(pe.exp), nil)) var o int64 for x.Exp(a, &y, n); x.Cmp(one) > 0; o++ { x.Exp(&x, pe.prime, n) } o1.Exp(pe.prime, o1.SetInt64(o), nil) mo.Mul(mo, o1.Quo(&o1, g.GCD(nil, nil, mo, &o1))) } return mo }   type pExp struct { prime *big.Int exp int64 }   func factor(n *big.Int) (pf []pExp) { var e int64 for ; n.Bit(int(e)) == 0; e++ { } if e > 0 { n.Rsh(n, uint(e)) pf = []pExp{{big.NewInt(2), e}} } s := sqrt(n) q, r := new(big.Int), new(big.Int) for d := big.NewInt(3); n.Cmp(one) > 0; d.Add(d, two) { if d.Cmp(s) > 0 { d.Set(n) } for e = 0; ; e++ { q.QuoRem(n, d, r) if r.BitLen() > 0 { break } n.Set(q) } if e > 0 { pf = append(pf, pExp{new(big.Int).Set(d), e}) s = sqrt(n) } } return }   func sqrt(n *big.Int) *big.Int { a := new(big.Int) for b := new(big.Int).Set(n); ; { a.Set(b) b.Rsh(b.Add(b.Quo(n, a), a), 1) if b.Cmp(a) >= 0 { return a } } return a.SetInt64(0) }
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.
#Phixmonti
Phixmonti
def nthroot var n var y 1e-15 var eps /# relative accuracy #/ 1 var x true while y x n 1 - power / x - n / var d x d + var x eps x * var e /# absolute accuracy #/ d 0 e - < d e > or endwhile x enddef   def printList len for get print endfor enddef   10 1024 3 27 2 2 125 5642 4 16 stklen tolist   len 1 swap 2 3 tolist for var i i get swap i 1 + get rot var e var b "The " e "th root of " b " is " b 1 e / power " (" b e nthroot ")" 9 tolist printList drop nl endfor
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.
#PHP
PHP
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[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 the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every writes(" ",nth(0 to 25) | "\n") every writes(" ",nth(250 to 265) | "\n") every writes(" ",nth(1000 to 1025) | "\n") end   procedure nth(n) return n || ((n%10 = 1, n%100 ~= 11, "st") | (n%10 = 2, n%100 ~= 12, "nd") | (n%10 = 3, n%100 ~= 13, "rd") | "th") end
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Tcl
Tcl
namespace eval baseconvert { variable chars "0123456789abcdefghijklmnopqrstuvwxyz" namespace export baseconvert } proc baseconvert::dec2base {n b} { variable chars expr {$n == 0 ? 0  : "[string trimleft [dec2base [expr {$n/$b}] $b] 0][string index $chars [expr {$n%$b}]]" } } proc baseconvert::base2dec {n b} { variable chars set sum 0 foreach char [split $n ""] { set d [string first $char [string range $chars 0 [expr {$b - 1}]]] if {$d == -1} {error "invalid base-$b digit '$char' in $n"} set sum [expr {$sum * $b + $d}] } return $sum } proc baseconvert::baseconvert {n basefrom baseto} { dec2base [base2dec $n $basefrom] $baseto }   namespace import baseconvert::baseconvert baseconvert 12345 10 23 ;# ==> 107h baseconvert 107h 23 7 ;# ==> 50664 baseconvert 50664 7 10 ;# ==> 12345
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Raku
Raku
sub is-narcissistic(Int $n) { $n == [+] $n.comb »**» $n.chars }   for 0 .. * { if .&is-narcissistic { .say; last if ++state$ >= 25; } }
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#zkl
zkl
fcn muncher{ bitmap:=PPM(256,256); coolness:=(1).random(0x10000); // 55379, 18180, 40, 51950, 57619, 43514, 65465 foreach y,x in ([0 .. 255],[0 .. 255]){ b:=x.bitXor(y); // shades of blue // rgb:=b*coolness; // kaleidoscopic image // rgb:=(b*coolness + b)*coolness + b; // more coolness rgb:=(b*0x10000 + b)*0x10000 + b; // copy ADA image bitmap[x,y]=rgb; } bitmap.write(File("foo.ppm","wb")); }();
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Go
Go
package main   import( "fmt" "math" )   var powers [10]int   func isMunchausen(n int) bool { if n < 0 { return false } n64 := int64(n) nn := n64 var sum int64 = 0 for nn > 0 { sum += int64(powers[nn % 10]) if sum > n64 { return false } nn /= 10 } return sum == n64 }   func main() { // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose for i := 1; i <= 9; i++ { d := float64(i) powers[i] = int(math.Pow(d, d)) }   // check numbers 0 to 500 million fmt.Println("The Munchausen numbers between 0 and 500 million are:") for i := 0; i <= 500000000; i++ { if isMunchausen(i) { fmt.Printf("%d ", i) } } fmt.Println() }
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 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Elena
Elena
import extensions; import system'collections;   F = (n => (n == 0) ? 1 : (n - M(F(n-1))) ); M = (n => (n == 0) ? 0 : (n - F(M(n-1))) );   public program() { var ra := new ArrayList(); var rb := new ArrayList();   for(int i := 0, i <= 19, i += 1) { ra.append(F(i)); rb.append(M(i)) };   console.printLine(ra.asEnumerable()); console.printLine(rb.asEnumerable()) }
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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Run_BASIC
Run BASIC
str$ = "a!===b=!=c" sep$ = "=== != =! b =!="   while word$(sep$,i+1," ") <> "" i = i + 1 theSep$ = word$(sep$,i," ") split$ = word$(str$,1,theSep$) print i;" ";split$;" Sep By: ";theSep$ wend
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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Scala
Scala
import scala.annotation.tailrec def multiSplit(str:String, sep:Seq[String])={ def findSep(index:Int)=sep find (str startsWith (_, index)) @tailrec def nextSep(index:Int):(Int,Int)= if(index>str.size) (index, 0) else findSep(index) match { case Some(sep) => (index, sep.size) case _ => nextSep(index + 1) } def getParts(start:Int, pos:(Int,Int)):List[String]={ val part=str slice (start, pos._1) if(pos._2==0) List(part) else part :: getParts(pos._1+pos._2, nextSep(pos._1+pos._2)) } getParts(0, nextSep(0)) }   println(multiSplit("a!===b=!=c", Seq("!=", "==", "=")))
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Clojure
Clojure
user> (take 3 (repeat (rand))) ; repeating the same random number three times (0.2787011365537204 0.2787011365537204 0.2787011365537204) user> (take 3 (repeatedly rand)) ; creating three different random number (0.8334795669220695 0.08405601245793926 0.5795448744634744) user>
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Common_Lisp
Common Lisp
(make-list n :initial-element (make-the-distinct-thing)) (make-array n :initial-element (make-the-distinct-thing))
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#D
D
auto fooArray = new Foo[n]; foreach (ref item; fooArray) item = new Foo();  
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)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure Mfact is   function MultiFact (num : Natural; deg : Positive) return Natural is Result, N : Integer := num; begin if N = 0 then return 1; end if; loop N := N - deg; exit when N <= 0; Result := Result * N; end loop; return Result; end MultiFact;   begin for deg in 1..5 loop Put("Degree"& Integer'Image(deg) &":"); for num in 1..10 loop Put(Integer'Image(MultiFact(num,deg))); end loop; New_line; end loop; end Mfact;
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 to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#F.23
F#
  // Multi-base primes. Nigel Galloway: July 4th., 2021 let digits="0123456789abcdefghijklmnopqrstuvwxyz" let fG n g=let rec fN g=function i when i<n->i::g |i->fN((i%n)::g)(i/n) in primes32()|>Seq.skipWhile((>)(pown n (g-1)))|>Seq.takeWhile((>)(pown n g))|>Seq.map(fun g->(n,fN [] g)) let fN g={2..36}|>Seq.collect(fun n->fG n g)|>Seq.groupBy snd|>Seq.groupBy(snd>>(Seq.length))|>Seq.maxBy fst {1..4}|>Seq.iter(fun g->let n,i=fN g in printfn "The following strings of length %d represent primes in the maximum number of bases(%d):" g n i|>Seq.iter(fun(n,g)->printf "  %s->" (n|>List.map(fun n->digits.[n])|>Array.ofList|>System.String) g|>Seq.iter(fun(g,_)->printf "%d " g); printfn ""); printfn "")  
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 armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#D
D
void main() { import std.stdio, std.algorithm, std.range, permutations2;   enum n = 8; n.iota.array.permutations.filter!(p => n.iota.map!(i => p[i] + i).array.sort().uniq.count == n && n.iota.map!(i => p[i] - i).array.sort().uniq.count == n) .count.writeln; }
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Haskell
Haskell
powerMod :: (Integral a, Integral b) => a -> a -> b -> a powerMod m _ 0 = 1 powerMod m x n | n > 0 = f x_ (n - 1) x_ where x_ = x `rem` m f _ 0 y = y f a d y = g a d where g b i | even i = g (b * b `rem` m) (i `quot` 2) | otherwise = f b (i - 1) (b * y `rem` m) powerMod m _ _ = error "powerMod: negative exponent"
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.
#Picat
Picat
go => L = [[2,2], [34,5], [34**5,5], [7131.5**10], [7,0.5], [1024,10], [5642, 125] ], foreach([A,N] in L) R = nthroot(A,N), printf("nthroot(%8w,%8w) %20w (check: %w)\n",A,N,R,A**(1/N)) end, nl.   % % x^n = a % % Given a and n, find x (to Precision) % nthroot(A,N) = nthroot(A,N,0.000001).   nthroot(A,N,Precision) = X1 => NF = N * 1.0, % float version of N X0 = A / NF, X1 = 1.0, do X0 := X1, X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1)))) while( abs(X0-X1) > Precision).
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 the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#J
J
suf=: (;:'th st nd rd th') {::~ 4 <. 10 10 (* 1&~:)~/@#: ] nth=: [: ;:inv (": , suf)each
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Ursala
Ursala
#import std #import nat   num_to_string "b" = ||'0'! (-: num digits--letters)*+ @NiX ~&r->l ^|rrPlCrlPX/~& division\"b"   string_to_num "b" = @x =>0 sum^|/(-:@rlXS num digits--letters) product/"b"
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#VBA
VBA
Private Function to_base(ByVal number As Long, base As Integer) As String Dim digits As String, result As String Dim i As Integer, digit As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" Do While number > 0 digit = number Mod base result = Mid(digits, digit + 1, 1) & result number = number \ base Loop to_base = result End Function Private Function from_base(number As String, base As Integer) As Long Dim digits As String, result As Long Dim i As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1) For i = 2 To Len(number) result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1) Next i from_base = result End Function Public Sub Non_decimal_radices_Convert() Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16) End Sub
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#REXX
REXX
/*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */ numeric digits 39 /*be able to handle largest Armstrong #*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N=25 /*Not specified? Then use the default.*/ N=min(N, 89) /*there are only 89 narcissistic #s. */ #=0 /*number of narcissistic numbers so far*/ do j=0 until #==N; L=length(j) /*get length of the J decimal number.*/ $=left(j, 1) **L /*1st digit in J raised to the L pow.*/   do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ $=$ + substr(j, k, 1) ** L /*add digit raised to power to the sum.*/ end /*k*/ /* [↑] calculate the rest of the sum. */   if $\==j then iterate /*does the sum equal to J? No, skip it*/ #=# + 1 /*bump count of narcissistic numbers. */ say right(#, 9) ' narcissistic:' j /*display index and narcissistic number*/ end /*j*/ /*stick a fork in it, we're all done. */
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Haskell
Haskell
import Control.Monad (join) import Data.List (unfoldr)   isMunchausen :: Integer -> Bool isMunchausen = (==) <*> (sum . map (join (^)) . unfoldr digit)   digit 0 = Nothing digit n = Just (r, q) where (q, r) = n `divMod` 10   main :: IO () main = print $ filter isMunchausen [1 .. 5000]
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 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Elixir
Elixir
defmodule MutualRecursion do def f(0), do: 1 def f(n), do: n - m(f(n - 1)) def m(0), do: 0 def m(n), do: n - f(m(n - 1)) end   IO.inspect Enum.map(0..19, fn n -> MutualRecursion.f(n) end) IO.inspect Enum.map(0..19, fn n -> MutualRecursion.m(n) end)
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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Scheme
Scheme
(use srfi-13) (use srfi-42)   (define (shatter separators the-string) (let loop ((str the-string) (tmp "")) (if (string=? "" str) (list tmp) (if-let1 sep (find (^s (string-prefix? s str)) separators) (cons* tmp sep (loop (string-drop str (string-length sep)) "")) (loop (string-drop str 1) (string-append tmp (string-take str 1)))))))   (define (glean shards) (list-ec (: x (index i) shards) (if (even? i)) x))
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Delphi
Delphi
var i: Integer; lObject: TMyObject; lList: TObjectList<TMyObject>; begin lList := TObjectList<TMyObject>.Create; lObject := TMyObject.Create; for i := 1 to 10 do lList.Add(lObject); // ...
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#E
E
pragma.enable("accumulator") ...   accum [] for _ in 1..n { _.with(makeWhatever()) }
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#EchoLisp
EchoLisp
  ;; wrong - make-vector is evaluated one time - same vector   (define L (make-list 3 (make-vector 4))) L → (#(0 0 0 0) #(0 0 0 0) #(0 0 0 0)) (vector-set! (first L ) 1 '🔴) ;; sets the 'first' vector   L → (#(0 🔴 0 0) #(0 🔴 0 0) #(0 🔴 0 0))   ;; right - three different vectors   (define L(map make-vector (make-list 3 4))) L → (#(0 0 0 0) #(0 0 0 0) #(0 0 0 0)) (vector-set! (first L ) 1 '🔵) ;; sets the first vector   L → (#(0 🔵 0 0) #(0 0 0 0) #(0 0 0 0)) ;; OK  
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. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#11l
11l
V symboltable = Array(‘a’..‘z’)   F move2front_encode(strng) [Int] sequence V pad = copy(:symboltable) L(char) strng V indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] [+] pad R sequence   F move2front_decode(sequence) [Char] chars V pad = copy(:symboltable) L(indx) sequence V char = pad[indx] chars.append(char) pad = [pad.pop(indx)] [+] pad R chars.join(‘’)   L(s) [‘broood’, ‘bananaaa’, ‘hiphophiphop’] V encode = move2front_encode(s) print(‘#14 encodes to #.’.format(s, encode), end' ‘, ’) V decode = move2front_decode(encode) print(‘which decodes back to #.’.format(decode)) assert(s == decode, ‘Whoops!’)
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. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#11l
11l
V arr = [ [ [1,2,3], [4,5,6] ], [ [11,22,33], [44,55,66] ], [ [111,222,333], [444,555,666] ], [ [1111,2222,3333], [4444,5555,6666] ] ]
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , y n } {\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,} X i = { x i 1 , x i 2 , . . . , x i n } , i ∈ 1.. k {\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,} Compute the vector β = { β 1 , β 2 , . . . , β k } {\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}} using ordinary least squares regression using the following equation: y j = Σ i β i ⋅ x i j , j ∈ 1.. n {\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n} You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
#Ada
Ada
generic type Element_Type is private; Zero : Element_Type; One : Element_Type; with function "+" (Left, Right : Element_Type) return Element_Type is <>; with function "-" (Left, Right : Element_Type) return Element_Type is <>; with function "*" (Left, Right : Element_Type) return Element_Type is <>; with function "/" (Left, Right : Element_Type) return Element_Type is <>; package Matrices is type Vector is array (Positive range <>) of Element_Type; type Matrix is array (Positive range <>, Positive range <>) of Element_Type;   function "*" (Left, Right : Matrix) return Matrix; function Invert (Source : Matrix) return Matrix; function Reduced_Row_Echelon_Form (Source : Matrix) return Matrix; function Regression_Coefficients (Source  : Vector; Regressors : Matrix) return Vector; function To_Column_Vector (Source : Matrix; Row  : Positive := 1) return Vector; function To_Matrix (Source  : Vector; Column_Vector : Boolean := True) return Matrix; function To_Row_Vector (Source : Matrix; Column : Positive := 1) return Vector; function Transpose (Source : Matrix) return Matrix;   Size_Mismatch  : exception; Not_Square_Matrix : exception; Not_Invertible  : exception; end Matrices;
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)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Aime
Aime
mf(integer a, n) { integer o;   o = 1; do { o *= a; } while (0 < (a -= n));   o; }   main(void) { integer i, j;   i = 0; while ((i += 1) <= 5) { o_("degree ", i, ":"); j = 0; while ((j += 1) <= 10) { o_("\t", mf(j, i)); } o_("\n"); }   0; }
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 to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Factor
Factor
USING: assocs assocs.extras formatting io kernel math math.functions math.parser math.primes math.ranges present sequences ;   : prime?* ( n -- ? ) [ prime? ] [ f ] if* ; inline   : (bases) ( n -- range quot ) present 2 36 [a,b] [ base> prime?* ] with ; inline   : <digits> ( n -- range ) [ 1 - ] keep [ 10^ ] bi@ [a,b) ;   : multibase ( n -- assoc ) <digits> [ (bases) count ] zip-with assoc-invert expand-keys-push-at >alist [ first ] supremum-by ;   : multibase. ( n -- ) dup multibase first2 [ "%d-digit numbers that are prime in the most bases: %d\n" printf ] dip [ dup (bases) filter "%d => %[%d, %]\n" printf ] each ;   4 [1,b] [ multibase. nl ] each
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 to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Go
Go
package main   import ( "fmt" "math" "rcu" )   var maxDepth = 6 var maxBase = 36 var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true) var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var maxStrings [][][]int var mostBases = -1   func maxSlice(a []int) int { max := 0 for _, e := range a { if e > max { max = e } } return max }   func maxInt(a, b int) int { if a > b { return a } return b }   func process(indices []int) { minBase := maxInt(2, maxSlice(indices)+1) if maxBase - minBase + 1 < mostBases { return // can't affect results so return } var bases []int for b := minBase; b <= maxBase; b++ { n := 0 for _, i := range indices { n = n*b + i } if !c[n] { bases = append(bases, b) } } count := len(bases) if count > mostBases { mostBases = count indices2 := make([]int, len(indices)) copy(indices2, indices) maxStrings = [][][]int{[][]int{indices2, bases}} } else if count == mostBases { indices2 := make([]int, len(indices)) copy(indices2, indices) maxStrings = append(maxStrings, [][]int{indices2, bases}) } }   func printResults() { fmt.Printf("%d\n", len(maxStrings[0][1])) for _, m := range maxStrings { s := "" for _, i := range m[0] { s = s + string(digits[i]) } fmt.Printf("%s -> %v\n", s, m[1]) } }   func nestedFor(indices []int, length, level int) { if level == len(indices) { process(indices) } else { indices[level] = 0 if level == 0 { indices[level] = 1 } for indices[level] < length { nestedFor(indices, length, level+1) indices[level]++ } } }   func main() { for depth := 1; depth <= maxDepth; depth++ { fmt.Print(depth, " character strings which are prime in most bases: ") maxStrings = maxStrings[:0] mostBases = -1 indices := make([]int, depth) nestedFor(indices, maxBase, 0) printResults() fmt.Println() } }
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 armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Dart
Dart
/** Return true if queen placement q[n] does not conflict with other queens q[0] through q[n-1] */ isConsistent(List q, int n) { for (int i=0; i<n; i++) { if (q[i] == q[n]) { return false; // Same column }   if ((q[i] - q[n]) == (n - i)) { return false; // Same major diagonal }   if ((q[n] - q[i]) == (n - i)) { return false; // Same minor diagonal } }   return true; }   /** Print out N-by-N placement of queens from permutation q in ASCII. */ printQueens(List q) { int N = q.length; for (int i=0; i<N; i++) { StringBuffer sb = new StringBuffer(); for (int j=0; j<N; j++) { if (q[i] == j) { sb.write("Q "); } else { sb.write("* "); } } print(sb.toString()); } print(""); }   /** Try all permutations using backtracking */ enumerate(int N) { var a = new List(N); _enumerate(a, 0); }   _enumerate(List q, int n) { if (n == q.length) { printQueens(q); } else { for (int i = 0; i < q.length; i++) { q[n] = i; if (isConsistent(q, n)){ _enumerate(q, n+1); } } } }   void main() { enumerate(4); }
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#J
J
mo=: 4 : 0 a=. x: x m=. x: y assert. 1=a+.m *./ a mopk"1 |: __ q: m )
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Java
Java
import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   public class MultiplicativeOrder { private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); private static final BigInteger THREE = BigInteger.valueOf(3); private static final BigInteger TEN = BigInteger.TEN;   private static class PExp { BigInteger prime; long exp;   PExp(BigInteger prime, long exp) { this.prime = prime; this.exp = exp; } }   private static void moTest(BigInteger a, BigInteger n) { if (!n.isProbablePrime(20)) { System.out.println("Not computed. Modulus must be prime for this algorithm."); return; } if (a.bitLength() < 100) System.out.printf("ord(%s)", a); else System.out.print("ord([big])"); if (n.bitLength() < 100) System.out.printf(" mod %s ", n); else System.out.print(" mod [big] "); BigInteger mob = moBachShallit58(a, n, factor(n.subtract(ONE))); System.out.println("= " + mob); }   private static BigInteger moBachShallit58(BigInteger a, BigInteger n, List<PExp> pf) { BigInteger n1 = n.subtract(ONE); BigInteger mo = ONE; for (PExp pe : pf) { BigInteger y = n1.divide(pe.prime.pow((int) pe.exp)); long o = 0; BigInteger x = a.modPow(y, n.abs()); while (x.compareTo(ONE) > 0) { x = x.modPow(pe.prime, n.abs()); o++; } BigInteger o1 = BigInteger.valueOf(o); o1 = pe.prime.pow(o1.intValue()); o1 = o1.divide(mo.gcd(o1)); mo = mo.multiply(o1); } return mo; }   private static List<PExp> factor(BigInteger n) { List<PExp> pf = new ArrayList<>(); BigInteger nn = n; Long e = 0L; while (!nn.testBit(e.intValue())) e++; if (e > 0L) { nn = nn.shiftRight(e.intValue()); pf.add(new PExp(TWO, e)); } BigInteger s = sqrt(nn); BigInteger d = THREE; while (nn.compareTo(ONE) > 0) { if (d.compareTo(s) > 0) d = nn; e = 0L; while (true) { BigInteger[] qr = nn.divideAndRemainder(d); if (qr[1].bitLength() > 0) break; nn = qr[0]; e++; } if (e > 0L) { pf.add(new PExp(d, e)); s = sqrt(nn); } d = d.add(TWO); } return pf; }   private static BigInteger sqrt(BigInteger n) { BigInteger b = n; while (true) { BigInteger a = b; b = n.divide(a).add(a).shiftRight(1); if (b.compareTo(a) >= 0) return a; } }   public static void main(String[] args) { moTest(BigInteger.valueOf(37), BigInteger.valueOf(3343));   BigInteger b = TEN.pow(100).add(ONE); moTest(b, BigInteger.valueOf(7919));   b = TEN.pow(1000).add(ONE); moTest(b, BigInteger.valueOf(15485863));   b = TEN.pow(10000).subtract(ONE); moTest(b, BigInteger.valueOf(22801763489L));   moTest(BigInteger.valueOf(1511678068), BigInteger.valueOf(7379191741L)); moTest(BigInteger.valueOf(3047753288L), BigInteger.valueOf(2257683301L)); } }
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.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de nthRoot (N A) (let (X1 A X2 (*/ A N)) (until (= X1 X2) (setq X1 X2 X2 (*/ (+ (* X1 (dec N)) (*/ A 1.0 (pow X1 (* (dec N) 1.0))) ) N ) ) ) X2 ) )   (prinl (format (nthRoot 2 2.0) *Scl)) (prinl (format (nthRoot 3 12.3) *Scl)) (prinl (format (nthRoot 4 45.6) *Scl))
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.
#PL.2FI
PL/I
/* Finds the N-th root of the number A */ root: procedure (A, N) returns (float); declare A float, N fixed binary; declare (xi, xip1) float;   xi = 1; /* An initial guess */ do forever; xip1 = ((n-1)*xi + A/xi**(n-1) ) / n; if abs(xip1-xi) < 1e-5 then leave; xi = xip1; end; return (xi); end root;
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 the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Java
Java
public class Nth { public static String ordinalAbbrev(int n){ String ans = "th"; //most of the time it should be "th" if(n % 100 / 10 == 1) return ans; //teens are all "th" switch(n % 10){ case 1: ans = "st"; break; case 2: ans = "nd"; break; case 3: ans = "rd"; break; } return ans; }   public static void main(String[] args){ for(int i = 0; i <= 25;i++){ System.out.print(i + ordinalAbbrev(i) + " "); } System.out.println(); for(int i = 250; i <= 265;i++){ System.out.print(i + ordinalAbbrev(i) + " "); } System.out.println(); for(int i = 1000; i <= 1025;i++){ System.out.print(i + ordinalAbbrev(i) + " "); } } }
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Wolframalpha
Wolframalpha
import "/fmt" for Conv   System.print(Conv.itoa(26, 16)) System.print(Conv.atoi("1a", 16))
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Ring
Ring
  n = 0 count = 0 size = 15 while count != size m = isNarc(n) if m=1 see "" + n + " is narcisstic" + nl count = count + 1 ok n = n + 1 end   func isNarc n m = len(string(n)) sum = 0 digit = 0 for pos = 1 to m digit = number(substr(string(n), pos, 1)) sum = sum + pow(digit,m) next nr = (sum = n) return nr  
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Ruby
Ruby
class Integer def narcissistic? return false if negative? digs = self.digits m = digs.size digs.map{|d| d**m}.sum == self end end   puts 0.step.lazy.select(&:narcissistic?).first(25)
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#J
J
munch=: +/@(^~@(10&#.inv)) (#~ ] = munch"0) 1+i.5000 1 3435
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 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Erlang
Erlang
-module(mutrec). -export([mutrec/0, f/1, m/1]).   f(0) -> 1; f(N) -> N - m(f(N-1)).   m(0) -> 0; m(N) -> N - f(m(N-1)).   mutrec() -> lists:map(fun(X) -> io:format("~w ", [f(X)]) end, lists:seq(0,19)), io:format("~n", []), lists:map(fun(X) -> io:format("~w ", [m(X)]) end, lists:seq(0,19)), io:format("~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 this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#SenseTalk
SenseTalk
set source to "a!===b=!=c" set separators to ["==", "!=", "="]   put each line delimited by separators of source
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Elena
Elena
import system'routines; import extensions;   class Foo;   // create a list of disting object fill(n) = RangeEnumerator.new(1,n).selectBy:(x => new Foo()).toArray();   // testing public program() { var foos := fill(10); }
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Elixir
Elixir
randoms = for _ <- 1..10, do: :rand.uniform(1000)
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Erlang
Erlang
Randoms = [random:uniform(1000) || _ <- lists:seq(1,10)].
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#F.23
F#
>List.replicate 3 (System.Guid.NewGuid());;   val it : Guid list = [485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485]
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. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#Action.21
Action!
DEFINE SYMBOL_TABLE_SIZE="26"   PROC InitSymbolTable(BYTE ARRAY table BYTE len) BYTE i   FOR i=0 TO len-1 DO table(i)=i+'a OD RETURN   BYTE FUNC Find(BYTE ARRAY table BYTE len,c) BYTE i   FOR i=0 TO len-1 DO IF table(i)=c THEN RETURN (i) FI OD Break() RETURN (0)   PROC MoveToFront(BYTE ARRAY table BYTE len,pos) BYTE sym   sym=table(pos) WHILE pos>0 DO table(pos)=table(pos-1) pos==-1 OD table(pos)=sym RETURN   PROC Encode(CHAR ARRAY in BYTE ARRAY out BYTE POINTER outLen) BYTE ARRAY table(SYMBOL_TABLE_SIZE) BYTE i,pos   outLen^=0 InitSymbolTable(table,SYMBOL_TABLE_SIZE) FOR i=1 TO in(0) DO pos=Find(table,SYMBOL_TABLE_SIZE,in(i)) out(outLen^)=pos outLen^==+1 MoveToFront(table,SYMBOL_TABLE_SIZE,pos) OD RETURN   PROC Decode(BYTE ARRAY in BYTE inLen CHAR ARRAY out) BYTE ARRAY table(SYMBOL_TABLE_SIZE) BYTE i,pos,len   len=0 InitSymbolTable(table,SYMBOL_TABLE_SIZE) FOR i=0 TO inLen-1 DO pos=in(i) len==+1 out(len)=table(pos) MoveToFront(table,SYMBOL_TABLE_SIZE,pos) OD out(0)=len RETURN   PROC Test(CHAR ARRAY s) BYTE ARRAY encoded(255) CHAR ARRAY decoded(256) BYTE encodedLength,i   Print("Source: ") PrintE(s)   Encode(s,encoded,@encodedLength) Print("Encoded: ") FOR i=0 TO encodedLength-1 DO PrintB(encoded(i)) Put(32) OD PutE()   Decode(encoded,encodedLength,decoded) Print("Decoded: ") PrintE(decoded) IF SCompare(s,decoded)=0 THEN PrintE("Decoded is equal to the source.") ELSE PrintE("Decoded is different from the source!") FI PutE() RETURN   PROC Main() Test("broood") Test("bananaaa") Test("hiphophiphop") RETURN
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. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Ada
Ada
  type Grade is range 0..100; subtype Lower_Case is Character range 'a'..'z'; subtype Natural is Integer range 0..Integer'Last; subtype Positive is Integer range 1..Integer'Last; type Deflection is range -180..180;  
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. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#ALGOL_68
ALGOL 68
[ 1 : 5, 1 : 4, 1 : 3, 1 : 2 ]INT a;
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , y n } {\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,} X i = { x i 1 , x i 2 , . . . , x i n } , i ∈ 1.. k {\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,} Compute the vector β = { β 1 , β 2 , . . . , β k } {\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}} using ordinary least squares regression using the following equation: y j = Σ i β i ⋅ x i j , j ∈ 1.. n {\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n} You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
#BBC_BASIC
BBC BASIC
*FLOAT 64 INSTALL @lib$+"ARRAYLIB"   DIM y(14), x(2,14), c(2) y() = 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 x() = 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, \ \ 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83   FOR row% = DIM(x(),1) TO 0 STEP -1 FOR col% = 0 TO DIM(x(),2) x(row%,col%) = x(0,col%) ^ row% NEXT NEXT row%   PROCmultipleregression(y(), x(), c()) FOR i% = 0 TO DIM(c(),1) : PRINT c(i%) " "; : NEXT PRINT END   DEF PROCmultipleregression(y(), x(), c()) LOCAL m(), t() DIM m(DIM(x(),1), DIM(x(),1)), t(DIM(x(),2),DIM(x(),1)) PROC_transpose(x(), t()) m() = x().t() PROC_invert(m()) t() = t().m() c() = y().t() ENDPROC
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)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#ALGOL_68
ALGOL 68
BEGIN INT highest degree = 5; INT largest number = 10; CO Recursive implementation of multifactorial function CO PROC multi fact = (INT n, deg) INT : (n <= deg | n | n * multi fact(n - deg, deg)); CO Iterative implementation of multifactorial function CO PROC multi fact i = (INT n, deg) INT : BEGIN INT result := n, nn := n; WHILE (nn >= deg + 1) DO result TIMESAB nn - deg; nn MINUSAB deg OD; result END; CO Print out multifactorials CO FOR i TO highest degree DO printf (($l, "Degree ", g(0), ":"$, i)); FOR j TO largest number DO printf (($xg(0)$, multi fact (j, i))) OD OD END  
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.
#8086_Assembly
8086 Assembly
mov ax,3 int 33h
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 to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Julia
Julia
using Primes   function maxprimebases(ndig, maxbase) maxprimebases = [Int[]] nwithbases = [0] maxprime = 10^(ndig) - 1 for p in div(maxprime + 1, 10):maxprime dig = digits(p) bases = [b for b in 2:maxbase if (isprime(evalpoly(b, dig)) && all(i -> i < b, dig))] if length(bases) > length(first(maxprimebases)) maxprimebases = [bases] nwithbases = [p] elseif length(bases) == length(first(maxprimebases)) push!(maxprimebases, bases) push!(nwithbases, p) end end alen, vlen = length(first(maxprimebases)), length(maxprimebases) println("\nThe maximum number of prime valued bases for base 10 numeric strings of length ", ndig, " is $alen. The base 10 value list of ", vlen > 1 ? "these" : "this", " is:") for i in eachindex(maxprimebases) println(nwithbases[i], " => ", maxprimebases[i]) end end   @time for n in 1:6 maxprimebases(n, 36) end  
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 to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[OtherBasePrimes, OtherBasePrimesPower] OtherBasePrimes[n_Integer] := Module[{digs, minbase, bases}, digs = IntegerDigits[n]; minbase = Max[digs] + 1; bases = Range[minbase, 36]; Pick[bases, PrimeQ[FromDigits[digs, #] & /@ bases], True] ] OtherBasePrimesPower[p_] := Module[{min, max, out, maxlen}, min = 10^p; max = 10^(p + 1) - 1; out = {#, OtherBasePrimes[#]} & /@ Range[min, max]; maxlen = Max[Length /@ out[[All, 2]]]; Select[out, Last /* Length /* EqualTo[maxlen]] ] OtherBasePrimesPower[0] // Column OtherBasePrimesPower[1] // Column OtherBasePrimesPower[2] // Column OtherBasePrimesPower[3] // Column OtherBasePrimesPower[4] // Column OtherBasePrimesPower[5] // Column
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 armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Delphi
Delphi
  program N_queens_problem;   {$APPTYPE CONSOLE}   uses System.SysUtils;   var i: Integer; q: boolean; a: array[0..8] of boolean; b: array[0..16] of boolean; c: array[0..14] of boolean; x: array[0..8] of Integer;   procedure TryMove(i: Integer); begin var j := 1; while True do begin q := false; if a[j] and b[i + j] and c[i - j + 7] then begin x[i] := j; a[j] := false; b[i + j] := false; c[i - j + 7] := false;   if i < 8 then begin TryMove(i + 1); if not q then begin a[j] := true; b[i + j] := true; c[i - j + 7] := true; end; end else q := true; end; if q or (j = 8) then Break; inc(j); end; end;   begin for i := 1 to 8 do a[i] := true;   for i := 2 to 16 do b[i] := true;   for i := 0 to 14 do c[i] := true;   TryMove(1);   if q then for i := 1 to 8 do writeln(i, ' ', x[i]); readln; end.
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Julia
Julia
using Primes   function factors(n) f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end return length(f) == 1 ? [one(n), n] : sort!(f) end   function multorder(a, m) gcd(a,m) == 1 || error("$a and $m are not coprime") res = one(m) for (p,e) in factor(m) m = p^e t = div(m, p) * (p-1) for f in factors(t) if powermod(a, f, m) == 1 res = lcm(res, f) break end end end res end
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 the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Kotlin
Kotlin
// version 1.2.10   import java.math.BigInteger   val bigOne = BigInteger.ONE val bigTwo = 2.toBigInteger() val bigThree = 3.toBigInteger() val bigTen = BigInteger.TEN   class PExp(val prime: BigInteger, val exp: Long)   fun moTest(a: BigInteger, n: BigInteger) { if (!n.isProbablePrime(20)) { println("Not computed. Modulus must be prime for this algorithm.") return } if (a.bitLength() < 100) print("ord($a)") else print("ord([big])") if (n.bitLength() < 100) print(" mod $n ") else print(" mod [big] ") val mob = moBachShallit58(a, n, factor(n - bigOne)) println("= $mob") }   fun moBachShallit58(a: BigInteger, n: BigInteger, pf: List<PExp>): BigInteger { val n1 = n - bigOne var mo = bigOne for (pe in pf) { val y = n1 / pe.prime.pow(pe.exp.toInt()) var o = 0L var x = a.modPow(y, n.abs()) while (x > bigOne) { x = x.modPow(pe.prime, n.abs()) o++ } var o1 = o.toBigInteger() o1 = pe.prime.pow(o1.toInt()) o1 /= mo.gcd(o1) mo *= o1 } return mo }   fun factor(n: BigInteger): List<PExp> { val pf = mutableListOf<PExp>() var nn = n var e = 0L while (!nn.testBit(e.toInt())) e++ if (e > 0L) { nn = nn shr e.toInt() pf.add(PExp(bigTwo, e)) } var s = bigSqrt(nn) var d = bigThree while (nn > bigOne) { if (d > s) d = nn e = 0L while (true) { val (q, r) = nn.divideAndRemainder(d) if (r.bitLength() > 0) break nn = q e++ } if (e > 0L) { pf.add(PExp(d, e)) s = bigSqrt(nn) } d += bigTwo } return pf }   fun bigSqrt(n: BigInteger): BigInteger { var b = n while (true) { val a = b b = (n / a + a) shr 1 if (b >= a) return a } }   fun main(args: Array<String>) { moTest(37.toBigInteger(), 3343.toBigInteger())   var b = bigTen.pow(100) + bigOne moTest(b, 7919.toBigInteger())   b = bigTen.pow(1000) + bigOne moTest(b, BigInteger("15485863"))   b = bigTen.pow(10000) - bigOne moTest(b, BigInteger("22801763489"))   moTest(BigInteger("1511678068"), BigInteger("7379191741")) moTest(BigInteger("3047753288"), BigInteger("2257683301")) }
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.
#PowerShell
PowerShell
#NoTeS: This sample code does not validate inputs # Thus, if there are errors the 'scary' red-text # error messages will appear. # # This code will not work properly in floating point values of n, # and negative values of A. # # Supports negative values of n by reciprocating the root.   $epsilon=1E-10 #Sample Epsilon (Precision)   function power($x,$e){ #As I said in the comment $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ #The main Function if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} #This checks if n is negative. $ans=1   do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon)   if (0+$n -lt 0){return 1/$ans} else {return $ans} }   #Sample Inputs root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 #Quite slow here, I admit...   ((root 5 2)+1)/2 #Extra: Computes the golden ratio ((root 5 2)-1)/2
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 the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#JavaScript
JavaScript
console.log(function () {   var lstSuffix = 'th st nd rd th th th th th th'.split(' '),   fnOrdinalForm = function (n) { return n.toString() + ( 11 <= n % 100 && 13 >= n % 100 ? "th" : lstSuffix[n % 10] ); },   range = function (m, n) { return Array.apply( null, Array(n - m + 1) ).map(function (x, i) { return m + i; }); };   return [[0, 25], [250, 265], [1000, 1025]].map(function (tpl) { return range.apply(null, tpl).map(fnOrdinalForm).join(' '); }).join('\n\n');   }());
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Wren
Wren
import "/fmt" for Conv   System.print(Conv.itoa(26, 16)) System.print(Conv.atoi("1a", 16))
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 invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated string convention   func Num2Str(N, B); \Convert integer N to a numeric string in base B int N, B; char S(32); int I; [I:= 31; S(31):= 0; \terminate string repeat I:= I-1; N:= N/B; S(I):= rem(0) + (if rem(0)<=9 then ^0 else ^a-10); until N=0; return @S(I); \BEWARE! very temporary string space ];   func Str2Num(S, B); \Convert numeric string S in base B to an integer char S; int B; int I, N; [I:= 0; N:= 0; while S(I) do [N:= N*B + S(I) - (if S(I)<=^9 then ^0 else ^a-10); I:= I+1]; return N; ];   [Text(0, Num2Str(0, 10)); CrLf(0); Text(0, Num2Str(26, 16)); CrLf(0); Text(0, Num2Str($7FFF_FFFF, 2)); CrLf(0); IntOut(0, Str2Num("0100", 2)); CrLf(0); IntOut(0, Str2Num("1a", 16)); CrLf(0); IntOut(0, Str2Num("deadbeef", 16)); CrLf(0); ]
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Rust
Rust
  fn is_narcissistic(x: u32) -> bool { let digits: Vec<u32> = x .to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .collect();   digits .iter() .map(|d| d.pow(digits.len() as u32)) .sum::<u32>() == x }   fn main() { let mut counter = 0; let mut i = 0; while counter < 25 { if is_narcissistic(i) { println!("{}", i); counter += 1; } i += 1; } }  
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 the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Scala
Scala
object NDN extends App {   val narc: Int => Int = n => (n.toString map (_.asDigit) map (math.pow(_, n.toString.size)) sum) toInt val isNarc: Int => Boolean = i => i == narc(i)   println((Iterator from 0 filter isNarc take 25 toList) mkString(" "))   }
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Java
Java
  public class Main { public static void main(String[] args) { for(int i = 0 ; i <= 5000 ; i++ ){ int val = String.valueOf(i).chars().map(x -> (int) Math.pow( x-48 ,x-48)).sum(); if( i == val){ System.out.println( i + " (munchausen)"); } } } }