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/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.
#BBC_BASIC
BBC BASIC
REM >multifact FOR i% = 1 TO 5 PRINT "Degree "; i%; ":"; FOR j% = 1 TO 10 PRINT " ";FNmultifact(j%, i%); NEXT PRINT NEXT END : DEF FNmultifact(n%, degree%) LOCAL i%, mfact% mfact% = 1 FOR i% = n% TO 1 STEP -degree% mfact% = mfact% * i% NEXT = mfact%
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.
#C
C
#include <stdio.h> #include <X11/Xlib.h>   int main() { Display *d; Window inwin; /* root window the pointer is in */ Window inchildwin; /* child win the pointer is in */ int rootx, rooty; /* relative to the "root" window; we are not interested in these, but we can't pass NULL */ int childx, childy; /* the values we are interested in */ Atom atom_type_prop; /* not interested */ int actual_format; /* should be 32 after the call */ unsigned int mask; /* status of the buttons */ unsigned long n_items, bytes_after_ret; Window *props; /* since we are interested just in the first value, which is a Window id */   /* default DISPLAY */ d = XOpenDisplay(NULL);   /* ask for active window (no error check); the client must be freedesktop compliant */ (void)XGetWindowProperty(d, DefaultRootWindow(d), XInternAtom(d, "_NET_ACTIVE_WINDOW", True), 0, 1, False, AnyPropertyType, &atom_type_prop, &actual_format, &n_items, &bytes_after_ret, (unsigned char**)&props);   XQueryPointer(d, props[0], &inwin, &inchildwin, &rootx, &rooty, &childx, &childy, &mask); printf("relative to active window: %d,%d\n", childx, childy);   XFree(props); /* free mem */ (void)XCloseDisplay(d); /* and close the display */ return 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.
#REXX
REXX
/*REXX pgm finds primes whose values in other bases (2──►36) have the most diff. bases. */ parse arg widths . /*obtain optional argument from the CL.*/ if widths=='' | widths=="," then widths= 5 /*Not specified? Then use the default.*/ call genP /*build array of semaphores for primes.*/ names= 'one two three four five six seven eight' /*names for some low decimal numbers. */ $.= do j=1 for # /*only use primes that are within range*/ do b=36 by -1 for 35; n= base(@.j, b) /*use different bases for each prime. */ L= length(n); if L>widths then iterate /*obtain length; Length too big? Skip.*/ if L==1 then $.L.n= b $.L.n /*Length = unity? Prepend the base.*/ else $.L.n= $.L.n b /* " ¬= " Append " " */ end /*b*/ end /*j*/ /*display info for each of the widths. */ do w=1 for widths; cnt= 0 /*show for each width: cnt,number,bases*/ bot= left(1, w, 0); top= left(9, w, 9) /*calculate range for DO. */ do n=bot to top; y= words($.w.n) /*find the sets of numbers for a width.*/ if y>cnt then do; mxn=n; cnt= max(cnt, y); end /*found a max? Remember it*/ end /*n*/ say say; say center(' 'word(names, w)"─character numbers that are" , 'prime in the most bases: ('cnt "bases) ", 101, '─') do n=bot to top; y= words($.w.n) /*search again for maximums.*/ if y==cnt then say n '──►' strip($.w.n) /*display ───a─── maximum. */ end /*n*/ end /*w*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ base: procedure; parse arg x,r,,z; @= '0123456789abcdefghijklmnopqrsruvwxyz' do j=1; _= r**j; if _>x then leave end /*j*/ do k=j-1 to 1 by -1; _= r**k; z= z || substr(@, (x % _) + 1, 1); x= x // _ end /*k*/; return z || substr(@, x+1, 1) /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */ #= 5; sq.#= @.# ** 2 /*number primes so far; prime squared.*/ do j=@.#+2 by 2 to 2 * 36 * 10**widths /*find odd primes from here on. */ parse var j '' -1 _; if _==5 then iterate /*J is ÷ by 5? (right dig).*/ if j//3==0 then iterate; if j//7==0 then iterate /*" " " " 3?; ÷ by 7? */ do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ if j//@.k==0 then iterate j /*Is J ÷ X? Then not prime. ___ */ end /*k*/ /* [↑] only process numbers ≤ √ J */ #= # + 1; @.#= j; sq.#= j*j /*bump # Ps; assign next P; P squared.*/ end /*j*/; return
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
#Elixir
Elixir
defmodule RC do def queen(n, display \\ true) do solve(n, [], [], [], display) end   defp solve(n, row, _, _, display) when n==length(row) do if display, do: print(n,row) 1 end defp solve(n, row, add_list, sub_list, display) do Enum.map(Enum.to_list(0..n-1) -- row, fn x -> add = x + length(row) # \ diagonal check sub = x - length(row) # / diagonal check if (add in add_list) or (sub in sub_list) do 0 else solve(n, [x|row], [add | add_list], [sub | sub_list], display) end end) |> Enum.sum # total of the solution end   defp print(n, row) do IO.puts frame = "+" <> String.duplicate("-", 2*n+1) <> "+" Enum.each(row, fn x -> line = Enum.map_join(0..n-1, fn i -> if x==i, do: "Q ", else: ". " end) IO.puts "| #{line}|" end) IO.puts frame end end   Enum.each(1..6, fn n -> IO.puts " #{n} Queen : #{RC.queen(n)}" end)   Enum.each(7..12, fn n -> IO.puts " #{n} Queen : #{RC.queen(n, false)}" # no display 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)).
#Python
Python
def gcd(a, b): while b != 0: a, b = b, a % b return a   def lcm(a, b): return (a*b) / gcd(a, b)   def isPrime(p): return (p > 1) and all(f == p for f,e in factored(p))   primeList = [2,3,5,7] def primes(): for p in primeList: yield p while 1: p += 2 while not isPrime(p): p += 2 primeList.append(p) yield p   def factored( a): for p in primes(): j = 0 while a%p == 0: a /= p j += 1 if j > 0: yield (p,j) if a < p*p: break if a > 1: yield (a,1)     def multOrdr1(a,(p,e) ): m = p**e t = (p-1)*(p**(e-1)) # = Phi(p**e) where p prime qs = [1,] for f in factored(t): qs = [ q * f[0]**j for j in range(1+f[1]) for q in qs ] qs.sort()   for q in qs: if pow( a, q, m )==1: break return q     def multOrder(a,m): assert gcd(a,m) == 1 mofs = (multOrdr1(a,r) for r in factored(m)) return reduce(lcm, mofs, 1)     if __name__ == "__main__": print multOrder(37, 1000) # 100 b = 10**20-1 print multOrder(2, b) # 3748806900 print multOrder(17,b) # 1499522760 b = 100001 print multOrder(54,b) print pow( 54, multOrder(54,b),b) if any( (1==pow(54,r, b)) for r in range(1,multOrder(54,b))): print 'Exists a power r < 9090 where pow(54,r,b)==1' else: print 'Everything checks.'
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.
#Raku
Raku
sub nth-root ($n, $A, $p=1e-9) { my $x0 = $A / $n; loop { my $x1 = (($n-1) * $x0 + $A / ($x0 ** ($n-1))) / $n; return $x1 if abs($x1-$x0) < abs($x0 * $p); $x0 = $x1; } }   say nth-root(3,8);
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.
#Liberty_BASIC
Liberty BASIC
  call printImages 0, 25 call printImages 250, 265 call printImages 1000, 1025 end   sub printImages loLim, hiLim loLim = int(loLim) hiLIm = int(hiLim) for i = loLim to hiLim print str$(i) + suffix$(i) + " "; next i print end sub   function suffix$(n) n = int(n) nMod10 = n mod 10 nMod100 = n mod 100 if (nMod10 = 1) and (nMod100 <> 11) then suffix$ = "st" else if (nMod10 = 2) and (nMod100 <> 12) then suffix$ = "nd" else if (NMod10 = 3) and (NMod100 <> 13) then suffix$ = "rd" else suffix$ = "th" end if end if end if end function  
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.
#VBScript
VBScript
Function Narcissist(n) i = 0 j = 0 Do Until j = n sum = 0 For k = 1 To Len(i) sum = sum + CInt(Mid(i,k,1)) ^ Len(i) Next If i = sum Then Narcissist = Narcissist & i & ", " j = j + 1 End If i = i + 1 Loop End Function   WScript.StdOut.Write Narcissist(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
#Lambdatalk
Lambdatalk
  {def munch {lambda {:w} {= :w {+ {S.map {{lambda {:w :i} {pow {W.get :i :w} {W.get :i :w}}} :w} {S.serie 0 {- {W.length :w} 1}}}}} }} -> munch   {S.map {lambda {:i} {if {munch :i} then :i else}} {S.serie 1 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).
#FOCAL
FOCAL
01.01 C--PRINT F(0..15) AND M(0..15) 01.10 T "F(0..15)" 01.20 F X=0,15;S N=X;D 4;T %1,N 01.30 T !"M(0..15)" 01.40 F X=0,15;S N=X;D 5;T %1,N 01.50 T ! 01.60 Q   04.01 C--N = F(N) 04.10 I (N(D)),4.11,4.2 04.11 S N(D)=1;R 04.20 S D=D+1;S N(D)=N(D-1)-1;D 4;D 5 04.30 S D=D-1;S N(D)=N(D)-N(D+1)   05.01 C--N = M(N) 05.10 I (N(D)),5.11,5.2 05.11 R 05.20 S D=D+1;S N(D)=N(D-1)-1;D 5;D 4 05.30 S D=D-1;S N(D)=N(D)-N(D+1)
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
#Latitude
Latitude
arr := n times to (Array) map { Object clone. }.
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
#Logtalk
Logtalk
  | ?- create_protocol(statep, [], [public(state/1)]), findall( Id, (integer::between(1, 10, N), create_object(Id, [implements(statep)], [], [state(N)])), Ids ). Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].  
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
#Lua
Lua
-- This concept is relevant to tables in Lua local table1 = {1,2,3}   -- The following will create a table of references to table1 local refTab = {} for i = 1, 10 do refTab[i] = table1 end   -- Instead, tables should be copied using a function like this function copy (t) local new = {} for k, v in pairs(t) do new[k] = v end return new end   -- Now we can create a table of independent copies of table1 local copyTab = {} for i = 1, 10 do copyTab[i] = copy(table1) end
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#C.2B.2B
C++
#include <cstdint> #include <iomanip> #include <iostream>   bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; }   class motzkin_generator { public: uint64_t next(); private: uint64_t n = 0; uint64_t m0 = 1; uint64_t m1 = 1; };   uint64_t motzkin_generator::next() { uint64_t m = n > 1 ? (m1 * (2 * n + 1) + m0 * (3 * n - 3)) / (n + 2) : 1; ++n; m0 = m1; m1 = m; return m; }   int main() { std::cout.imbue(std::locale("")); std::cout << " n M(n) Prime?\n"; std::cout << "-----------------------------------\n"; std::cout << std::boolalpha; motzkin_generator mgen; for (int i = 0; i < 42; ++i) { uint64_t n = mgen.next(); std::cout << std::setw(2) << i << std::setw(25) << n << " " << is_prime(n) << '\n'; } }
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.)
#C.2B.2B
C++
  #include <iostream> #include <iterator> #include <sstream> #include <vector>   using namespace std;   class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *it == symbolTable[i] ) { output.push_back( i ); moveToFront( i ); break; } } } string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { ostringstream ss; ss << *it; r += ss.str() + " "; } return r; }   string decode( string str ) { fillSymbolTable(); istringstream iss( str ); vector<int> output; copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) ); string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { r.append( 1, symbolTable[*it] ); moveToFront( *it ); } return r; }   private: void moveToFront( int i ) { char t = symbolTable[i]; for( int z = i - 1; z >= 0; z-- ) symbolTable[z + 1] = symbolTable[z];   symbolTable[0] = t; }   void fillSymbolTable() { for( int x = 0; x < 26; x++ ) symbolTable[x] = x + 'a'; }   char symbolTable[26]; };   int main() { MTF mtf; string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; for( int x = 0; x < 3; x++ ) { a = str[x]; cout << a << " -> encoded = "; a = mtf.encode( a ); cout << a << "; decoded = " << mtf.decode( a ) << endl; } return 0; }  
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).
#Fortran
Fortran
DIMENSION A(5,4,3,2) !Declares a (real) array A of four dimensions, storage permitting. X = 3*A(2,I,1,K) !Extracts a certain element, multiplies its value by three, result to X. A(1,2,3,4) = X + 1 !Places a value (the result of the expression X + 1) ... somewhere...
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).
#Emacs_Lisp
Emacs Lisp
(let ((x1 '(0 1 2 3 4 5 6 7 8 9 10)) (x2 '(0 1 1 3 3 7 6 7 3 9 8)) (y '(1 6 17 34 57 86 121 162 209 262 321))) (apply #'calc-eval "fit(a*X1+b*X2+c,[X1,X2],[a,b,c],[$1 $2 $3])" nil (mapcar (lambda (items) (cons 'vec items)) (list x1 x2 y))))
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.
#C
C
  /* Include statements and constant definitions */ #include <stdio.h> #define HIGHEST_DEGREE 5 #define LARGEST_NUMBER 10   /* Recursive implementation of multifactorial function */ int multifact(int n, int deg){ return n <= deg ? n : n * multifact(n - deg, deg); }   /* Iterative implementation of multifactorial function */ int multifact_i(int n, int deg){ int result = n; while (n >= deg + 1){ result *= (n - deg); n -= deg; } return result; }   /* Test function to print out multifactorials */ int main(void){ int i, j; for (i = 1; i <= HIGHEST_DEGREE; i++){ printf("\nDegree %d: ", i); for (j = 1; j <= LARGEST_NUMBER; j++){ printf("%d ", multifact(j, i)); } } }  
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.
#c_sharp
c_sharp
  using System; using System.Windows.Forms; static class Program { [STAThread] static void Main() { Console.WriteLine(Control.MousePosition.X); Console.WriteLine(Control.MousePosition.Y); } }  
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.
#Rust
Rust
// [dependencies] // primal = "0.3"   fn digits(mut n: u32, dig: &mut [u32]) { for i in 0..dig.len() { dig[i] = n % 10; n /= 10; } }   fn evalpoly(x: u64, p: &[u32]) -> u64 { let mut result = 0; for y in p.iter().rev() { result *= x; result += *y as u64; } result }   fn max_prime_bases(ndig: u32, maxbase: u32) { let mut maxlen = 0; let mut maxprimebases = Vec::new(); let limit = 10u32.pow(ndig); let mut dig = vec![0; ndig as usize]; for n in limit / 10..limit { digits(n, &mut dig); let bases: Vec<u32> = (2..=maxbase) .filter(|&x| dig.iter().all(|&y| y < x) && primal::is_prime(evalpoly(x as u64, &dig))) .collect(); if bases.len() > maxlen { maxlen = bases.len(); maxprimebases.clear(); } if bases.len() == maxlen { maxprimebases.push((n, bases)); } } println!( "{} character numeric strings that are prime in maximum bases: {}", ndig, maxlen ); for (n, bases) in maxprimebases { println!("{} => {:?}", n, bases); } println!(); }   fn main() { for n in 1..=6 { max_prime_bases(n, 36); } }
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.
#Sidef
Sidef
func max_prime_bases(ndig, maxbase=36) {   var maxprimebases = [[]] var nwithbases = [0] var maxprime = (10**ndig - 1)   for p in (idiv(maxprime + 1, 10) .. maxprime) { var dig = p.digits var bases = (2..maxbase -> grep {|b| dig.all { _ < b } && dig.digits2num(b).is_prime }) if (bases.len > maxprimebases.first.len) { maxprimebases = [bases] nwithbases = [p] } elsif (bases.len == maxprimebases.first.len) { maxprimebases << bases nwithbases << p } }   var (alen, vlen) = (maxprimebases.first.len, maxprimebases.len)   say("\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:") maxprimebases.each_kv {|k,v| say(nwithbases[k], " => ", v) } }   for n in (1..5) { max_prime_bases(n) }
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
#Erlang
Erlang
  -module( n_queens ).   -export( [display/1, solve/1, task/0] ).   display( Board ) -> %% Queens are in the positions in the Board list. %% Top left corner is {1, 1}, Bottom right is {N, N}. There is a queen in the max column. N = lists:max( [X || {X, _Y} <- Board] ), [display_row(Y, N, Board) || Y <- lists:seq(1, N)].   solve( N ) -> Positions = [{X, Y} || X <- lists:seq(1, N), Y <- lists:seq(1, N)], try bt( N, Positions, [] )   catch _:{ok, Board} -> Board   end.   task() -> task( 4 ), task( 8 ).       bt( N, Positions, Board ) -> bt_reject( is_not_allowed_queen_placement(N, Board), N, Positions, Board ).   bt_accept( true, _N, _Positions, Board ) -> erlang:throw( {ok, Board} ); bt_accept( false, N, Positions, Board ) -> bt_loop( N, Positions, [], Board ).   bt_loop( _N, [], _Rejects, _Board ) -> failed; bt_loop( N, [Position | T], Rejects, Board ) -> bt( N, T ++ Rejects, [Position | Board] ), bt_loop( N, T, [Position | Rejects], Board ).   bt_reject( true, _N, _Positions, _Board ) -> backtrack; bt_reject( false, N, Positions, Board ) -> bt_accept( is_all_queens(N, Board), N, Positions, Board ).   diagonals( N, {X, Y} ) -> D1 = diagonals( N, X + 1, fun diagonals_add1/1, Y + 1, fun diagonals_add1/1 ), D2 = diagonals( N, X + 1, fun diagonals_add1/1, Y - 1, fun diagonals_subtract1/1 ), D3 = diagonals( N, X - 1, fun diagonals_subtract1/1, Y + 1, fun diagonals_add1/1 ), D4 = diagonals( N, X - 1, fun diagonals_subtract1/1, Y - 1, fun diagonals_subtract1/1 ), D1 ++ D2 ++ D3 ++ D4.   diagonals( _N, 0, _Change_x, _Y, _Change_y ) -> []; diagonals( _N, _X, _Change_x, 0, _Change_y ) -> []; diagonals( N, X, _Change_x, _Y, _Change_y ) when X > N -> []; diagonals( N, _X, _Change_x, Y, _Change_y ) when Y > N -> []; diagonals( N, X, Change_x, Y, Change_y ) -> [{X, Y} | diagonals( N, Change_x(X), Change_x, Change_y(Y), Change_y )].   diagonals_add1( N ) -> N + 1.   diagonals_subtract1( N ) -> N - 1.   display_row( Row, N, Board ) -> [io:fwrite("~s", [display_queen(X, Row, Board)]) || X <- lists:seq(1, N)], io:nl().   display_queen( X, Y, Board ) -> display_queen( lists:member({X, Y}, Board) ). display_queen( true ) -> " Q"; display_queen( false ) -> " .".   is_all_queens( N, Board ) -> N =:= erlang:length( Board ).   is_diagonal( _N, [] ) -> false; is_diagonal( N, [Position | T] ) -> Diagonals = diagonals( N, Position ), T =/= (T -- Diagonals) orelse is_diagonal( N, T ).   is_not_allowed_queen_placement( N, Board ) -> Pieces = erlang:length( Board ), {Xs, Ys} = lists:unzip( Board ), Pieces =/= erlang:length( lists:usort(Xs) ) orelse Pieces =/= erlang:length( lists:usort(Ys) ) orelse is_diagonal( N, Board ).   task( N ) -> io:fwrite( "N = ~p. One solution.~n", [N] ), Board = solve( N ), display( Board ).  
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)).
#Racket
Racket
  #lang racket (require math)   (define (order a n) (unless (coprime? a n) (error 'order "arguments must be coprime")) (for/fold ([o 1]) ([r (factorize n)]) (lcm o (order1 a r))))   (define (order1 a p&e) (match-define (list p e) p&e) (define m (expt p e)) (define t (* (- p 1) (expt p (- e 1)))) (define qs (for/fold ([qs '(1)]) ([f (factorize t)]) (match f [(list f0 f1) (for*/list ([q qs] [j (in-range (+ 1 f1))]) (* q (expt f0 j)))]))) (for/or ([q (sort qs <)] #:when (= (modular-expt a q m) 1)) q))     (order 37 1000) (order (+ (expt 10 100) 1) 7919) (order (+ (expt 10 1000) 1) 15485863) (order (- (expt 10 10000) 1) 22801763489) (order 13 (+ 1 (expt 10 80)))  
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)).
#Raku
Raku
use Prime::Factor;   sub mo-prime($a, $p, $e) { my $m = $p ** $e; my $t = ($p - 1) * ($p ** ($e - 1)); # = Phi($p**$e) where $p prime my @qs = 1; for prime-factors($t).Bag -> $f { @qs = flat @qs.map(-> $q { (0..$f.value).map(-> $j { $q * $f.key ** $j }) }); }   @qs.sort.first: -> $q { expmod( $a, $q, $m ) == 1 }; }   sub mo($a, $m) { $a gcd $m == 1 or die "$a and $m are not relatively prime"; [lcm] flat 1, prime-factors($m).Bag.map: { mo-prime($a, .key, .value) }; }   multi MAIN('test') { use Test;   for (10, 21, 25, 150, 1231, 123141, 34131) -> $n { is ([*] prime-factors($n).Bag.map( { .key ** .value } )), $n, "$n factors correctly"; }   is mo(37, 1000), 100, 'mo(37,1000) == 100'; my $b = 10**20-1; is mo(2, $b), 3748806900, 'mo(2,10**20-1) == 3748806900'; is mo(17, $b), 1499522760, 'mo(17,10**20-1) == 1499522760'; $b = 100001; is mo(54, $b), 9090, 'mo(54,100001) == 9090'; }
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.
#RATFOR
RATFOR
  program nth # integer root real number, precision real temp0, temp1   1 format('Enter the base number: ') 2 format('Enter the desired root: ') 3 format('Enter the desired precision: ') 4 format(F12.6) 5 format(I6) write(6,1) read(5,4)number write(6,2) read(5,5)root write(6,3) read(5,4)precision   temp0 = number temp1 = number/root   while ( abs(temp0 - temp1) > precision ) { temp0 = temp1 temp1 = ((root - 1.0) * temp1 + number / temp1 ** (root - 1.0)) / root }   6 format(' number root precision') write(6,6) 7 format(f12.6,i6,f12.6) write (6,7)number,root,precision 8 format('The root is: ',F12.6) write (6,8)temp1   end  
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.
#REXX
REXX
/*REXX program calculates the Nth root of X, with DIGS (decimal digits) accuracy. */ parse arg x root digs . /*obtain optional arguments from the CL*/ if x=='' | x=="," then x= 2 /*Not specified? Then use the default.*/ if root=='' | root=="," then root= 2 /* " " " " " " */ if digs=='' | digs=="," then digs=65 /* " " " " " " */ numeric digits digs /*set the decimal digits to DIGS. */ say ' x = ' x /*echo the value of X. */ say ' root = ' root /* " " " " ROOT. */ say ' digits = ' digs /* " " " " DIGS. */ say ' answer = ' root(x, root) /*show the value of ANSWER. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ root: procedure; parse arg x 1 Ox, r 1 Or /*arg1 ──► x & Ox, 2nd ──► r & Or*/ if r=='' then r=2 /*Was root specified? Assume √. */ if r=0 then return '[n/a]' /*oops-ay! Can't do zeroth root.*/ complex= x<0 & R//2==0 /*will the result be complex? */ oDigs=digits() /*get the current number of digs.*/ if x=0 | r=1 then return x/1 /*handle couple of special cases.*/ dm=oDigs+5 /*we need a little guard room. */ r=abs(r); x=abs(x) /*the absolute values of R and X.*/ rm=r-1 /*just a fast version of ROOT -1*/ numeric form /*take a good guess at the root─┐*/ parse value format(x,2,1,,0) 'E0' with ? 'E' _ . /* ◄────────────────────────────┘*/ g= (? / r'E'_ % r) + (x>1) /*kinda uses a crude "logarithm".*/ d=5 /*start with five decimal digits.*/ do until d==dm; d=min(d+d,dm) /*each time, precision doubles. */ numeric digits d /*tell REXX to use D digits. */ old=-1 /*assume some kind of old guess. */ do until old=g; old=g /*where da rubber meets da road─┐*/ g=format((rm*g**r+x)/r/g**rm,, d-2) /* ◄────── the root computation─┘*/ end /*until old=g*/ /*maybe until the cows come home.*/ end /*until d==dm*/ /*and wait for more cows to come.*/   if g=0 then return 0 /*in case the jillionth root = 0.*/ if Or<0 then g=1/g /*root < 0 ? Reciprocal it is! */ if \complex then g=g*sign(Ox) /*adjust the sign (maybe). */ numeric digits oDigs /*reinstate the original digits. */ return (g/1) || left('j', complex) /*normalize # to digs, append j ?*/
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.
#Lua
Lua
function getSuffix (n) local lastTwo, lastOne = n % 100, n % 10 if lastTwo > 3 and lastTwo < 21 then return "th" end if lastOne == 1 then return "st" end if lastOne == 2 then return "nd" end if lastOne == 3 then return "rd" end return "th" end   function Nth (n) return n .. "'" .. getSuffix(n) end   for i = 0, 25 do print(Nth(i), Nth(i + 250), Nth(i + 1000)) 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.
#Wren
Wren
var narc = Fn.new { |n| var power = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] var limit = 10 var result = [] var x = 0 while (result.count < n) { if (x >= limit) { for (i in 0..9) power[i] = power[i] * i limit = limit * 10 } var sum = 0 var xx = x while (xx > 0) { sum = sum + power[xx%10] xx = (xx/10).floor } if (sum == x) result.add(x) x = x + 1 } return result }   System.print(narc.call(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
#langur
langur
# sum power of digits val .spod = f(.n) fold f{+}, map(f (.x-'0') ^ (.x-'0'), s2cp toString .n)   # Munchausen writeln "Answers: ", where f(.n) .n == .spod(.n), series 0..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).
#Forth
Forth
defer m   : f ( n -- n ) dup 0= if 1+ exit then dup 1- recurse m - ;   :noname ( n -- n ) dup 0= if exit then dup 1- recurse f - ; is m   : test ( xt n -- ) cr 0 do i over execute . loop drop ;   ' m defer@ 20 test \ 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 ' f 20 test \ 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Form 60, 40 Foo=Lambda Id=1 (m)->{ class Alfa { x, id Class: Module Alfa(.x, .id) {} } =Alfa(m, id) id++ }   Dim A(10)<<Foo(20) \\ for each arrayitem call Foo(20) TestThis()     \\ call once foo(20) and result copy to each array item Dim A(10)=Foo(20) TestThis()   Bar=Lambda Foo (m)->{ ->Foo(m) } \\ Not only the same id, but the same group \\ each item is pointer to group Dim A(10)=Bar(20) TestThis()   Sub TestThis() Local i For i=0 to 9 { For A(i){ .x++ Print .id , .x } } Print End Sub } Checkit  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{x, x, x, x} /. x -> Random[]
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
#Maxima
Maxima
a: [1, 2]$   b: makelist(copy(a), 3); [[1,2],[1,2],[1,2]]   b[1][2]: 1000$   b; [[1,1000],[1,2],[1,2]]
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#F.23
F#
  // Motzkin numbers. Nigel Galloway: September 10th., 2021 let M=let rec fN g=seq{yield List.item 1 g; yield! fN(0L::(g|>List.windowed 3|>List.map(List.sum))@[0L;0L])} in fN [0L;1L;0L;0L] M|>Seq.take 42|>Seq.iter(printfn "%d")  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Factor
Factor
USING: combinators formatting io kernel math math.primes tools.memory.private ;   MEMO: motzkin ( m -- n ) dup 2 < [ drop 1 ] [ { [ 2 * 1 + ] [ 1 - motzkin * ] [ 3 * 3 - ] [ 2 - motzkin * + ] [ 2 + /i ] } cleave ] if ;   " n motzkin(n)\n" print 42 [ dup motzkin [ commas ] keep prime? "prime" "" ? "%2d %24s  %s\n" printf ] each-integer
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.)
#Clojure
Clojure
(def lowercase (map char (range (int \a) (inc (int \z)))))   (defn move-to-front [x xs] (cons x (remove #{x} xs)))   (defn encode [text table & {:keys [acc] :or {acc []}}] (let [c (first text) idx (.indexOf table c)] (if (empty? text) acc (recur (drop 1 text) (move-to-front c table) {:acc (conj acc idx)}))))   (defn decode [indices table & {:keys [acc] :or {acc []}}] (if (empty? indices) (apply str acc) (let [n (first indices) c (nth table n)] (recur (drop 1 indices) (move-to-front c table) {:acc (conj acc c)}))))   (doseq [word ["broood" "bananaaa" "hiphophiphop"]] (let [encoded (encode word lowercase) decoded (decode encoded lowercase)] (println (format "%s encodes to %s which decodes back to %s." word encoded decoded))))
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).
#Go
Go
package main   import "fmt"   type md struct { dim []int ele []float64 }   func newMD(dim ...int) *md { n := 1 for _, d := range dim { n *= d } return &md{append([]int{}, dim...), make([]float64, n)} }   func (m *md) index(i ...int) (x int) { for d, dx := range m.dim { x = x*dx + i[d] } return }   func (m *md) at(i ...int) float64 { return m.ele[m.index(i...)] }   func (m *md) set(x float64, i ...int) { m.ele[m.index(i...)] = x }   func (m *md) show(i ...int) { fmt.Printf("m%d = %g\n", i, m.at(i...)) }   func main() { m := newMD(5, 4, 3, 2) m.show(4, 3, 2, 1) m.set(87, 4, 3, 2, 1) m.show(4, 3, 2, 1)   for i := 0; i < m.dim[0]; i++ { for j := 0; j < m.dim[1]; j++ { for k := 0; k < m.dim[2]; k++ { for l := 0; l < m.dim[3]; l++ { x := m.index(i, j, k, l) m.set(float64(x)+.1, i, j, k, l) } } } } fmt.Println(m.ele[:10]) fmt.Println(m.ele[len(m.ele)-10:]) m.show(4, 3, 2, 1) }
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).
#ERRE
ERRE
PROGRAM MULTIPLE_REGRESSION   !$DOUBLE   CONST N=14,M=2,Q=3 ! number of points and M.R. polynom degree   DIM X[N],Y[N]  ! data points DIM S[N],T[N]  ! linear system coefficient DIM A[M,Q]  ! sistem to be solved   BEGIN   DATA(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) DATA(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)   FOR I%=0 TO N DO READ(X[I%]) END FOR   FOR I%=0 TO N DO READ(Y[I%]) END FOR   FOR K%=0 TO 2*M DO S[K%]=0 T[K%]=0 FOR I%=0 TO N DO S[K%]=S[K%]+X[I%]^K% IF K%<=M THEN T[K%]=T[K%]+Y[I%]*X[I%]^K% END IF END FOR END FOR   ! build linear system   FOR ROW%=0 TO M DO FOR COL%=0 TO M DO A[ROW%,COL%]=S[ROW%+COL%] END FOR A[ROW%,COL%]=T[ROW%] END FOR   PRINT("LINEAR SYSTEM COEFFICENTS") PRINT FOR I%=0 TO M DO FOR J%=0 TO M+1 DO WRITE(" ######.#";A[I%,J%];) END FOR PRINT END FOR PRINT   FOR J%=0 TO M DO FOR I%=J% TO M DO EXIT IF A[I%,J%]<>0 END FOR IF I%=M+1 THEN PRINT("SINGULAR MATRIX !")  !$STOP END IF FOR K%=0 TO M+1 DO SWAP(A[J%,K%],A[I%,K%]) END FOR Y=1/A[J%,J%] FOR K%=0 TO M+1 DO A[J%,K%]=Y*A[J%,K%] END FOR FOR I%=0 TO M DO IF I%<>J% THEN Y=-A[I%,J%] FOR K%=0 TO M+1 DO A[I%,K%]=A[I%,K%]+Y*A[J%,K%] END FOR END IF END FOR END FOR PRINT   PRINT("SOLUTIONS") PRINT FOR I%=0 TO M DO PRINT("c";I%;"=";) WRITE("#####.#######";A[I%,M+1]) END FOR   END PROGRAM
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).
#Fortran
Fortran
*----------------------------------------------------------------------- * MR - multiple regression using the SLATEC library routine DHFTI * * Finds the nearest approximation to BETA in the system of linear equations: * * X(j,i) . BETA(i) = Y(j) * where * 1 ... j ... N * 1 ... i ... K * and * K .LE. N * * INPUT ARRAYS ARE DESTROYED! * *___Name___________Type_______________In/Out____Description_____________ * X(N,K) Double precision In Predictors * Y(N) Double precision Both On input: N Observations * On output: K beta weights * N Integer In Number of observations * K Integer In Number of predictor variables * DWORK(N+2*K) Double precision Neither Workspace * IWORK(K) Integer Neither Workspace *----------------------------------------------------------------------- SUBROUTINE MR (X, Y, N, K, DWORK, IWORK) IMPLICIT NONE INTEGER K, N, IWORK DOUBLE PRECISION X, Y, DWORK DIMENSION X(N,K), Y(N), DWORK(N+2*K), IWORK(K)   * local variables INTEGER I, J DOUBLE PRECISION TAU, TOT   * maximum of all column sums of magnitudes TAU = 0. DO J = 1, K TOT = 0. DO I = 1, N TOT = TOT + ABS(X(I,J)) END DO IF (TOT > TAU) TAU = TOT END DO TAU = TAU * EPSILON(TAU) ! tolerance argument   * call function CALL DHFTI (X, N, N, K, Y, N, 1, TAU, $ J, DWORK(1), DWORK(N+1), DWORK(N+K+1), IWORK) IF (J < K) PRINT *, 'mr: solution is rank deficient!' RETURN END ! of MR   *----------------------------------------------------------------------- PROGRAM t_mr ! polynomial regression example IMPLICIT NONE INTEGER N, K PARAMETER (N=15, K=3) INTEGER IWORK(K), I, J DOUBLE PRECISION XIN(N), X(N,K), Y(N), DWORK(N+2*K)   DATA XIN / 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 / DATA 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 /   * make coefficient matrix DO J = 1, K DO I = 1, N X(I,J) = XIN(I) **(J-1) END DO END DO   * solve CALL MR (X, Y, N, K, DWORK, IWORK)   * print result 10 FORMAT ('beta: ', $) 20 FORMAT (F12.4, $) 30 FORMAT () PRINT 10 DO J = 1, K PRINT 20, Y(J) END DO PRINT 30 STOP 'program complete' END  
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.
#C.23
C#
namespace RosettaCode.Multifactorial { using System; using System.Linq;   internal static class Program { private static void Main() { Console.WriteLine(string.Join(Environment.NewLine, Enumerable.Range(1, 5) .Select( degree => string.Join(" ", Enumerable.Range(1, 10) .Select( number => Multifactorial(number, degree)))))); }   private static int Multifactorial(int number, int degree) { if (degree < 1) { throw new ArgumentOutOfRangeException("degree"); }   var count = 1 + (number - 1) / degree; if (count < 1) { throw new ArgumentOutOfRangeException("number"); }   return Enumerable.Range(0, count) .Aggregate(1, (accumulator, index) => accumulator * (number - degree * index)); } } }
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.
#Clojure
Clojure
(let [point (.. java.awt.MouseInfo getPointerInfo getLocation)] [(.getX point) (.getY point)])
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.
#Common_Lisp
Common Lisp
  (ql:quickload "ltk") (in-package :ltk-user) (defun motion (event) (format t "~a x position is ~a~&" event (event-x event)))   (with-ltk () ;; create a small window. Enter the mouse to see lots of events. (bind *tk* "<Motion>" #'motion))  
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.
#Wren
Wren
import "/math" for Int, Nums   var maxDepth = 5 var maxBase = 36 var c = Int.primeSieve(maxBase.pow(maxDepth), false) var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var maxStrings = [] var mostBases = -1   var process = Fn.new { |indices| var minBase = 2.max(Nums.max(indices) + 1) if (maxBase - minBase + 1 < mostBases) return // can't affect results so return var bases = [] for (b in minBase..maxBase) { var n = 0 for (i in indices) n = n * b + i if (!c[n]) bases.add(b) } var count = bases.count if (count > mostBases) { mostBases = count maxStrings = [[indices.toList, bases]] } else if (count == mostBases) { maxStrings.add([indices.toList, bases]) } }   var printResults = Fn.new { System.print("%(maxStrings[0][1].count)") for (m in maxStrings) { var s = m[0].reduce("") { |acc, i| acc + digits[i] } System.print("%(s) -> %(m[1])") } }   var nestedFor // recursive nestedFor = Fn.new { |indices, length, level| if (level == indices.count) { process.call(indices) } else { indices[level] = (level == 0) ? 1 : 0 while (indices[level] < length) { nestedFor.call(indices, length, level + 1) indices[level] = indices[level] + 1 } } }   for (depth in 1..maxDepth) { System.write("%(depth) character strings which are prime in most bases: ") maxStrings = [] mostBases = -1 var indices = List.filled(depth, 0) nestedFor.call(indices, maxBase, 0) printResults.call() System.print() }
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
#ERRE
ERRE
  !------------------------------------------------ ! QUEENS.R : solve queens problem on a NxN board !------------------------------------------------   PROGRAM QUEENS   DIM COL%[15]   BEGIN MAXSIZE%=15 PRINT(TAB(25);" --- PROBLEMA DELLE REGINE --- ") PRINT PRINT("Board dimension ";) INPUT(N%) PRINT IF (N%<1 OR N%>MAXSIZE%) THEN PRINT("Illegal dimension!!") ELSE FOR CURCOLNBR%=1 TO N% COL%[CURCOLNBR%]=0 END FOR CURCOLNBR%=1 WHILE CURCOLNBR%>0 DO PLACEDAQUEEN%=FALSE I%=COL%[CURCOLNBR%]+1 WHILE (I%<=N%) AND NOT PLACEDAQUEEN% DO PLACEDAQUEEN%=TRUE J%=1 WHILE PLACEDAQUEEN% AND (J%<CURCOLNBR%) DO PLACEDAQUEEN%=COL%[J%]<>I% J%=J%+1 END WHILE IF PLACEDAQUEEN% THEN DIAGNBR%=I%+CURCOLNBR% J%=1 WHILE PLACEDAQUEEN% AND (J%<CURCOLNBR%) DO PLACEDAQUEEN%=(COL%[J%]+J%)<>DIAGNBR% J%=J%+1 END WHILE ELSE END IF IF PLACEDAQUEEN% THEN DIAGNBR%=I%-CURCOLNBR% J%=1 WHILE PLACEDAQUEEN% AND (J%<CURCOLNBR%) DO PLACEDAQUEEN%=(COL%[J%]-J%)<>DIAGNBR% J%=J%+1 END WHILE ELSE END IF IF NOT PLACEDAQUEEN% THEN I%=I%+1 ELSE COL%[CURCOLNBR%]=I% END IF END WHILE IF NOT PLACEDAQUEEN% THEN COL%[CURCOLNBR%]=0 CURCOLNBR%=CURCOLNBR%-1 ELSE IF CURCOLNBR%=N% THEN NSOL%=NSOL%+1 PRINT("Soluzione";NSOL%;":";) FOR I%=1 TO N% PRINT(COL%[I%];) END FOR PRINT ELSE CURCOLNBR%=CURCOLNBR%+1 END IF END IF END WHILE PRINT("Search completed") REPEAT GET(CH$) UNTIL CH$<>"" END IF END PROGRAM  
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)).
#REXX
REXX
/*REXX pgm computes multiplicative order of a minimum integer N such that a^n mod m≡1*/ wa= 0; wm= 0 /* ═a═ ══m══ */ /*maximum widths of the A and M values.*/ @.=.; @.1= 3 10 @.2= 37 1000 @.3= 37 10000 @.4= 37 3343 @.5= 37 3344 @.6= 2 1000 pad= left('', 9) d= 500 /*use 500 decimal digits for a starter.*/ do w=1 for 2 /*when W≡1, find max widths of A and M.*/ do j=1 while @.j\==.; parse var @.j a . 1 r m , n if w==1 then do; wa= max(wa, length(a) ); wm= max(wm, length(m) ); iterate end if m//a==0 then n= ' [solution not possible]' /*test co─prime for A and B. */ numeric digits d /*start with 100 decimal digits. */ if n=='' then do n= 2; p= r * a /*compute product──may have an exponent*/ parse var p 'E' _ /*try to extract the exponent from P. */ if _\=='' then do; numeric digits _+d /*bump the decimal digs.*/ p=r*a /*recalculate integer P.*/ end if p//m==1 then leave /*now, perform the nitty─gritty modulo.*/ r= p /*assign product to R for next multiply*/ end /*n*/ /* [↑] // is really ÷ remainder.*/ say pad 'a=' right(a,wa) pad "m=" right(m,wm) pad 'multiplicative order:' n end /*j*/ end /*w*/ /*stick a fork in it, we're all done. */
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.
#Ring
Ring
  decimals(12) see "cube root of 5 is : " + root(3, 5, 0) + nl   func root n, a, d y = 0 x = a / n while fabs (x - y) > d y = ((n - 1)*x + a/pow(x,(n-1))) / n temp = x x = y y = temp end return x  
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.
#Ruby
Ruby
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end   p nthroot(5,34) # => 2.02439745849989
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.
#Maple
Maple
toOrdinal := proc(n:: nonnegint) if 1 <= n and n <= 10 then if n >= 4 then printf("%ath", n); elif n = 3 then printf("%ard", n); elif n = 2 then printf("%and", n); else printf("%ast", n); end if: else printf(convert(n, 'ordinal')); end if: return NULL; end proc:   a := [[0, 25], [250, 265], [1000, 1025]]: for i in a do for j from i[1] to i[2] do toOrdinal(j); printf(" "); end do; printf("\n\n"); end do;
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.
#XPL0
XPL0
func IPow(A, B); \A^B int A, B, T, I; [T:= 1; for I:= 1 to B do T:= T*A; return T; ];   int Count, M, N, Sum, T, Dig; [Text(0, "0 "); Count:= 1; for M:= 1 to 9 do for N:= IPow(10, M-1) to IPow(10, M)-1 do [Sum:= 0; T:= N; while T do [T:= T/10; Dig:= rem(0); Sum:= Sum + IPow(Dig, M); ]; if Sum = N then [IntOut(0, N); ChOut(0, ^ ); Count:= Count+1; if Count >= 25 then exit; ]; ]; ]
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
#Lua
Lua
function isMunchausen (n) local sum, nStr, digit = 0, tostring(n) for pos = 1, #nStr do digit = tonumber(nStr:sub(pos, pos)) sum = sum + digit ^ digit end return sum == n end   -- alternative, faster version based on the C version, -- avoiding string manipulation, for Lua 5.3 or higher local function isMunchausen (n) local sum, digit, acc = 0, 0, n while acc > 0 do digit = acc % 10.0 sum = sum + digit ^ digit acc = acc // 10 -- integer div end return sum == n end   for i = 1, 5000 do if isMunchausen(i) then print(i) end end
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).
#Fortran
Fortran
module MutualRec implicit none contains pure recursive function m(n) result(r) integer :: r integer, intent(in) :: n if ( n == 0 ) then r = 0 return end if r = n - f(m(n-1)) end function m   pure recursive function f(n) result(r) integer :: r integer, intent(in) :: n if ( n == 0 ) then r = 1 return end if r = n - m(f(n-1)) end function f   end module
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
#Modula-3
Modula-3
VAR a: ARRAY[1..N] OF T
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
#NGS
NGS
{ [foo()] * n }
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need 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
#Nim
Nim
import sequtils, strutils   # Creating a sequence containing sequences of integers. var s1 = newSeq[seq[int]](5) for item in s1.mitems: item = @[1] echo "s1 = ", s1 # @[@[1], @[1], @[1], @[1], @[1]] s1[0].add 2 echo "s1 = ", s1 # @[@[1, 2], @[1], @[1], @[1], @[1]]   # Using newSeqWith. var s2 = newSeqWith(5, @[1]) echo "s2 = ", s2 # @[@[1], @[1], @[1], @[1], @[1]] s2[0].add 2 echo "s2 = ", s2 # @[@[1, 2], @[1], @[1], @[1], @[1]]   # Creating a sequence containing pointers. proc newInt(n: int): ref int = new(result) result[] = n var s3 = newSeqWith(5, newInt(1)) echo "s3 contains references to ", s3.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1 s3[0][] = 2 echo "s3 contains references to ", s3.mapIt(it[]).join(", ") # 2, 1, 1, 1, 1   # How to create non distinct elements. let p = newInt(1) var s4 = newSeqWith(5, p) echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1 s4[0][] = 2 echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 2, 2, 2, 2, 2
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Fermat
Fermat
  Array m[42]; m[1]:=1; m[2]:=2; !!(1,0); {precompute and print m[0] thru m[2]} !!(1,0); !!(2,1); for n=3 to 41 do m[n]:=(m[n-1]*(2*n+1) + m[n-2]*(3*n-3))/(n+2);  !!(m[n],Isprime(m[n])); od;   ; {built-in Isprime function returns 0 for 1, 1 for primes, and} ; {the smallest prime factor for composites, so this actually gives} ; {slightly more information than requested}  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#FreeBASIC
FreeBASIC
  #include "isprime.bas"   dim as ulongint M(0 to 41) M(0) = 1 : M(1) = 1 print "1" : print "1" for n as integer = 2 to 41 M(n) = M(n-1) for i as uinteger = 0 to n-2 M(n) += M(i)*M(n-2-i) next i print M(n), if isprime(M(n)) then print "is a prime" else print next n  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Go
Go
package main   import ( "fmt" "rcu" )   func motzkin(n int) []int { m := make([]int, n+1) m[0] = 1 m[1] = 1 for i := 2; i <= n; i++ { m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2) } return m }   func main() { fmt.Println(" n M[n] Prime?") fmt.Println("-----------------------------------") m := motzkin(41) for i, e := range m { fmt.Printf("%2d  %23s  %t\n", i, rcu.Commatize(e), rcu.IsPrime(e)) } }
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.)
#Common_Lisp
Common Lisp
(defconstant +lower+ (coerce "abcdefghijklmnopqrstuvwxyz" 'list))   (defun move-to-front (x xs) (cons x (remove x xs)))   (defun enc (text table) (map 'list (lambda (c) (let ((idx (position c table))) (setf table (move-to-front c table)) idx)) text))   (defun dec (indices table) (coerce (mapcar (lambda (idx) (let ((c (nth idx table))) (setf table (move-to-front c table)) c)) indices) 'string))   (loop for word in '("broood" "bananaaa" "hiphophiphop") do (let* ((encoded (enc word +lower+)) (decoded (dec encoded +lower+))) (assert (string= word decoded)) (format T "~s encodes to ~a which decodes back to ~s.~%" word encoded decoded)))
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#ALGOL_68
ALGOL 68
BEGIN MODE MWRITER = STRUCT( LONG REAL value , STRING log ); PRIO BIND = 9; OP BIND = ( MWRITER m, PROC( LONG REAL )MWRITER f )MWRITER: ( MWRITER n := f( value OF m ); log OF n := log OF m + log OF n; n );   OP LEN = ( STRING s )INT: ( UPB s + 1 ) - LWB s; PRIO PAD = 9; OP PAD = ( STRING s, INT width )STRING: IF LEN s >= width THEN s ELSE s + ( width - LEN s ) * " " FI;   PROC unit = ( LONG REAL v, STRING s )MWRITER: ( v, " " + s PAD 17 + ":" + fixed( v, -19, 15 ) + REPR 10 );   PROC root = ( LONG REAL v )MWRITER: unit( long sqrt( v ), "Took square root" ); PROC add one = ( LONG REAL v )MWRITER: unit( v+1, "Added one" ); PROC half = ( LONG REAL v )MWRITER: unit( v/2, "Divided by two" );   MWRITER mw2 := unit( 5, "Initial value" ) BIND root BIND add one BIND half; print( ( "The Golden Ratio is", fixed( value OF mw2, -19, 15 ), newline ) ); print( ( newline, "This was derived as follows:-", newline ) ); print( ( log OF mw2 ) ) END
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).
#J
J
A1=:5 4 3 2$0
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).
#Java
Java
public class MultiDimensionalArray { public static void main(String[] args) { // create a regular 4 dimensional array and initialize successive elements to the values 1 to 120 int m = 1; int[][][][] a4 = new int[5][4][3][2]; for (int i = 0; i < a4.length; ++i) { for (int j = 0; j < a4[0].length; ++j) { for (int k = 0; k < a4[0][0].length; ++k) { for (int l = 0; l < a4[0][0][0].length; ++l) { a4[i][j][k][l] = m++; } } } }   System.out.println("First element = " + a4[0][0][0][0]); // access and print value of first element a4[0][0][0][0] = 121; // change value of first element System.out.println();   for (int i = 0; i < a4.length; ++i) { for (int j = 0; j < a4[0].length; ++j) { for (int k = 0; k < a4[0][0].length; ++k) { for (int l = 0; l < a4[0][0][0].length; ++l) { System.out.printf("%4d", a4[i][j][k][l]); } } } } } }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#11l
11l
V n = 12 L(j) 1..n print(‘#3’.format(j), end' ‘ ’) print(‘│’) L 1..n print(‘────’, end' ‘’) print(‘┼───’)   L(i) 1..n L(j) 1..n print(I j < i {‘ ’} E ‘#3 ’.format(i * j), end' ‘’) print(‘│ ’i)
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).
#Go
Go
package main   import ( "fmt"   "github.com/gonum/matrix/mat64" )   func givens() (x, y *mat64.Dense) { height := []float64{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} weight := []float64{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} degree := 2 x = Vandermonde(height, degree) y = mat64.NewDense(len(weight), 1, weight) return }   func Vandermonde(a []float64, degree int) *mat64.Dense { x := mat64.NewDense(len(a), degree+1, nil) for i := range a { for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] { x.Set(i, j, p) } } return x }   func main() { x, y := givens() fmt.Printf("%.4f\n", mat64.Formatted(mat64.QR(x).Solve(y))) }
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.
#C.2B.2B
C++
  #include <algorithm> #include <iostream> #include <iterator> /*Generate multifactorials to 9   Nigel_Galloway November 14th., 2012. */ int main(void) { for (int g = 1; g < 10; g++) { int v[11], n=0; generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&]{n++; return v[n]=(g<n)? v[n-g]*n : n;}); std::cout << std::endl; } return 0; }  
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.
#Delphi
Delphi
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin lblMousePosition.Caption := ('X:' + IntToStr(X) + ', Y:' + IntToStr(Y)); 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.
#EasyLang
EasyLang
on mouse_move clear text mouse_x & " " & mouse_y .
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
#F.23
F#
  let rec iterate f value = seq { yield value yield! iterate f (f value) }   let up i = i + 1 let right i = i let down i = i - 1   let noCollisionGivenDir solution number dir = Seq.forall2 (<>) solution (Seq.skip 1 (iterate dir number))   let goodAddition solution number = List.forall (noCollisionGivenDir solution number) [ up; right; down ]   let rec extendSolution n ps = [0..n - 1] |> List.filter (goodAddition ps) |> List.map (fun num -> num :: ps)   let allSolutions n = iterate (List.collect (extendSolution n)) [[]]   // Print one solution for the 8x8 case let printOneSolution () = allSolutions 8 |> Seq.item 8 |> Seq.head |> List.iter (fun rowIndex -> printf "|" [0..8] |> List.iter (fun i -> printf (if i = rowIndex then "X|" else " |")) printfn "")   // Print number of solution for the other cases let printNumberOfSolutions () = printfn "Size\tNr of solutions" [1..11] |> List.map ((fun i -> Seq.item i (allSolutions i)) >> List.length) |> List.iteri (fun i cnt -> printfn "%d\t%d" (i+1) cnt)   printOneSolution()   printNumberOfSolutions()  
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)).
#Ruby
Ruby
require 'prime'   def powerMod(b, p, m) p.to_s(2).each_char.inject(1) do |result, bit| result = (result * result) % m bit=='1' ? (result * b) % m : result end end   def multOrder_(a, p, k) pk = p ** k t = (p - 1) * p ** (k - 1) r = 1 for q, e in t.prime_division x = powerMod(a, t / q**e, pk) while x != 1 r *= q x = powerMod(x, q, pk) end end r end   def multOrder(a, m) m.prime_division.inject(1) do |result, f| result.lcm(multOrder_(a, *f)) end end   puts multOrder(37, 1000) b = 10**20-1 puts multOrder(2, b) puts multOrder(17,b) b = 100001 puts multOrder(54,b) puts powerMod(54, multOrder(54,b), b) if (1...multOrder(54,b)).any? {|r| powerMod(54, r, b) == 1} puts 'Exists a power r < 9090 where powerMod(54,r,b)==1' else puts 'Everything checks.' end
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.
#Run_BASIC
Run BASIC
print "Root 125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 )) print "125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 )) print "125th Root of 5643 Precision .00001 ";using( "#.###############", NthRoot( 125, 5642, 0.00001)) print " 3rd Root of 27 Precision .00001 ";using( "#.###############", NthRoot( 3, 27, 0.00001)) print " 2nd Root of 2 Precision .00001 ";using( "#.###############", NthRoot( 2, 2, 0.00001)) print " 10th Root of 1024 Precision .00001 ";using( "#.###############", NthRoot( 10, 1024, 0.00001))   wait   function NthRoot( root, A, precision) x0 = A x1 = A /root while abs( x1 -x0) >precision x0 = x1 x1 = x1 / 1.0 ' force float x1 = (( root -1.0) *x1 +A /x1^( root -1.0)) /root wend NthRoot =x1 end function   end
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.
#Rust
Rust
// 20210212 Rust programming solution   fn nthRoot(n: f64, A: f64) -> f64 {   let p = 1e-9_f64 ; let mut x0 = A / n ;   loop { let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n; if (x1-x0).abs() < (x0*p).abs() { return x1 }; x0 = x1 } }   fn main() { println!("{}", nthRoot(3. , 8. )); }
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
suffixlist = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th","th"}; addsuffix[n_] := Module[{suffix}, suffix = Which[ Mod[n, 100] <= 10, suffixlist[[Mod[n, 10] + 1]], Mod[n, 100] > 20, suffixlist[[Mod[n, 10] + 1]], True, "th" ]; ToString[n] <> suffix ] addsuffix[#] & /@ Range[0, 25] (* test 1 *) addsuffix[#] & /@ Range[250, 265] (* test 2 *) addsuffix[#] & /@ Range[1000, 1025] (* test 3 *)
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.
#zkl
zkl
fcn isNarcissistic(n){ ns,m := n.split(), ns.len() - 1; ns.reduce('wrap(s,d){ z:=d; do(m){z*=d} s+z },0) == n }
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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
1 DIM K(10): DIM M(10) 2 FOR Y=0 TO 9: LET M(Y+1)=Y: NEXT Y 3 FOR N=1 TO 7 4 FOR J=N TO 0 STEP -1 5 FOR I=N-J TO 0 STEP -1 6 FOR H=N-J-I TO 0 STEP -1 7 FOR G=N-J-I-H TO 0 STEP -1 8 FOR F=N-J-I-H-G TO 0 STEP -1 9 FOR E=N-J-I-H-G-F TO 0 STEP -1 10 FOR D=N-J-I-H-G-F-E TO 0 STEP -1 11 FOR C=N-J-I-H-G-F-E-D TO 0 STEP -1 12 FOR B=N-J-I-H-G-F-E-D-C TO 0 STEP -1 13 LET A=N-J-I-H-G-F-E-D-C-B 14 LET X=B+C*M(3)+D*M(4)+E*M(5)+F*M(6)+G*M(7)+H*M(8)+I*M(9)+J*M(10) 15 LET S$=STR$ (X) 16 IF LEN (S$)<N THEN GO TO 34 17 IF LEN (S$)<>N THEN GO TO 33 18 FOR Y=1 TO 10: LET K(Y)=0: NEXT Y 19 FOR Y=1 TO N 20 LET Z= CODE (S$(Y))-47 21 LET K(Z)=K(Z)+1 22 NEXT Y 23 IF A<>K(1) THEN GO TO 33 24 IF B<>K(2) THEN GO TO 33 25 IF C<>K(3) THEN GO TO 33 26 IF D<>K(4) THEN GO TO 33 27 IF E<>K(5) THEN GO TO 33 28 IF F<>K(6) THEN GO TO 33 29 IF G<>K(7) THEN GO TO 33 30 IF H<>K(8) THEN GO TO 33 31 IF I<>K(9) THEN GO TO 33 32 IF J=K(10) THEN PRINT X, 33 NEXT B: NEXT C: NEXT D: NEXT E: NEXT F: NEXT G: NEXT H: NEXT I: NEXT J 34 FOR Y=2 TO 9 35 LET M(Y+1)=M(Y+1)*Y 36 NEXT Y 37 NEXT N 38 PRINT 39 PRINT "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
#M2000_Interpreter
M2000 Interpreter
  Module Munchausen { Inventory p=0:=0,1:=1 for i=2 to 9 {Append p, i:=i**i} Munchausen=lambda p (x)-> { m=0 t=x do { m+=p(x mod 10) x=x div 10 } until x=0 =m=t } For i=1 to 5000 If Munchausen(i) then print i, Next i Print } Munchausen  
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).
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Need forward declaration of M as it's used ' by F before its defined Declare Function M(n As Integer) As Integer   Function F(n As Integer) As Integer If n = 0 Then Return 1 End If Return n - M(F(n - 1)) End Function   Function M(n As Integer) As Integer If n = 0 Then Return 0 End If Return n - F(M(n - 1)) End Function   Dim As Integer n = 24 Print "n :"; For i As Integer = 0 to n : Print Using "###"; i;  : Next Print Print String(78, "-") Print "F :"; For i As Integer = 0 To n : Print Using "###"; F(i); : Next Print Print "M :"; For i As Integer = 0 To n : Print Using "###"; M(i); : Next Print Print "Press any key to quit" Sleep
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
#OCaml
OCaml
Array.make n (new foo);; (* here (new foo) can be any expression that returns a new object, record, array, or string *)
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
#Oforth
Oforth
ListBuffer init(10, #[ Float rand ]) println
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
#ooRexx
ooRexx
-- get an array of directory objects array = fillArrayWith(3, .directory) say "each object will have a different identityHash" say loop d over array say d d~identityHash end   ::routine fillArrayWith use arg size, class   array = .array~new(size) loop i = 1 to size -- Note, this assumes this object class can be created with -- no arguments array[i] = class~new end   return array
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Haskell
Haskell
import Control.Monad.Memo (Memo, memo, startEvalMemo) import Math.NumberTheory.Primes.Testing (isPrime) import System.Environment (getArgs) import Text.Printf (printf)   type I = Integer   -- The n'th Motzkin number, where n is assumed to be ≥ 0. We memoize the -- computations using MonadMemo. motzkin :: I -> Memo I I I motzkin 0 = return 1 motzkin 1 = return 1 motzkin n = do m1 <- memo motzkin (n-1) m2 <- memo motzkin (n-2) return $ ((2*n+1)*m1 + (3*n-3)*m2) `div` (n+2)   -- The first n+1 Motzkin numbers, starting at 0. motzkins :: I -> [I] motzkins = startEvalMemo . mapM motzkin . enumFromTo 0   -- For i = 0 to n print i, the i'th Motzkin number, and if it's a prime number. printMotzkins :: I -> IO () printMotzkins n = mapM_ prnt $ zip [0 :: I ..] (motzkins n) where prnt (i, m) = printf "%2d %20d %s\n" i m $ prime m prime m = if isPrime m then "prime" else ""   main :: IO () main = do [n] <- map read <$> getArgs printMotzkins n
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.)
#D
D
import std.stdio, std.string, std.ascii, std.algorithm;   ptrdiff_t[] mtfEncoder(in string data) pure nothrow @safe in { assert(data.countchars("a-z") == data.length); } out(result) { assert(result.length == data.length); assert(result.all!(e => e >= 0 && e < lowercase.length)); } body { ubyte[lowercase.length] order = lowercase.representation; auto encoded = new typeof(return)(data.length);   size_t i = 0; foreach (immutable b; data) { immutable j = encoded[i++] = order[].countUntil(b); bringToFront(order[0 .. j], order[j .. j + 1]); }   return encoded; }   string mtfDecoder(in ptrdiff_t[] encoded) pure nothrow @safe in { assert(encoded.all!(e => e >= 0 && e < lowercase.length)); } out(result) { assert(result.length == encoded.length); assert(result.countchars("a-z") == result.length); } body { ubyte[lowercase.length] order = lowercase.representation; auto decoded = new char[encoded.length];   size_t i = 0; foreach (immutable code; encoded) { decoded[i++] = order[code]; bringToFront(order[0 .. code], order[code .. code + 1]); }   return decoded; }   void main() { foreach (immutable word; ["broood", "bananaaa", "hiphophiphop"]) { immutable encoded = word.mtfEncoder; immutable decoded = encoded.mtfDecoder; writefln("'%s' encodes to %s, which decodes back to '%s'", word, encoded, decoded); assert(word == decoded); } }
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#AppleScript
AppleScript
-- WRITER MONAD FOR APPLESCRIPT   -- How can we compose functions which take simple values as arguments -- but return an output value which is paired with a log string ?   -- We can prevent functions which expect simple values from choking -- on log-wrapped output (from nested functions) -- by writing Unit/Return() and Bind() for the Writer monad in AppleScript   on run {}   -- Derive logging versions of three simple functions, pairing -- each function with a particular comment string   -- (a -> b) -> (a -> (b, String)) set wRoot to writerVersion(root, "obtained square root") set wSucc to writerVersion(succ, "added one") set wHalf to writerVersion(half, "divided by two")   loggingHalfOfRootPlusOne(5)   --> value + log string end run     -- THREE SIMPLE FUNCTIONS on root(x) x ^ (1 / 2) end root   on succ(x) x + 1 end succ   on half(x) x / 2 end half   -- DERIVE A LOGGING VERSION OF A FUNCTION BY COMBINING IT WITH A -- LOG STRING FOR THAT FUNCTION -- (SEE 'on run()' handler at top of script) -- (a -> b) -> String -> (a -> (b, String)) on writerVersion(f, strComment) script on call(x) {value:sReturn(f)'s call(x), comment:strComment} end call end script end writerVersion     -- DEFINE A COMPOSITION OF THE SAFE VERSIONS on loggingHalfOfRootPlusOne(x) logCompose([my wHalf, my wSucc, my wRoot], x) end loggingHalfOfRootPlusOne     -- Monadic UNIT/RETURN and BIND functions for the writer monad on writerUnit(a) try set strValue to ": " & a as string on error set strValue to "" end try {value:a, comment:"Initial value" & strValue} end writerUnit   on writerBind(recWriter, wf) set recB to wf's call(value of recWriter) set v to value of recB   try set strV to " -> " & (v as string) on error set strV to "" end try   {value:v, comment:(comment of recWriter) & linefeed & (comment of recB) & strV} end writerBind   -- THE TWO HIGHER ORDER FUNCTIONS ABOVE ENABLE COMPOSITION OF -- THE LOGGING VERSIONS OF EACH FUNCTION on logCompose(lstFunctions, varValue) reduceRight(lstFunctions, writerBind, writerUnit(varValue)) end logCompose   -- xs: list, f: function, a: initial accumulator value -- the arguments available to the function f(a, x, i, l) are -- v: current accumulator value -- x: current item in list -- i: [ 1-based index in list ] optional -- l: [ a reference to the list itself ] optional on reduceRight(xs, f, a) set sf to sReturn(f)   repeat with i from length of xs to 1 by -1 set a to sf's call(a, item i of xs, i, xs) end repeat end reduceRight   -- Unit/Return and bind for composing handlers in script wrappers -- lift 2nd class function into 1st class wrapper -- handler function --> first class script object on sReturn(f) script property call : f end script end sReturn   -- return a new script in which function g is composed -- with the f (call()) of the Mf script -- Mf -> (f -> Mg) -> Mg on sBind(mf, g) script on call(x) sReturn(g)'s call(mf's call(x)) end call end script end sBind
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String Compose the two functions with bind
#AppleScript
AppleScript
-- MONADIC FUNCTIONS (for list monad) ------------------------------------------   -- Monadic bind for lists is simply ConcatMap -- which applies a function f directly to each value in the list, -- and returns the set of results as a concat-flattened list   -- bind :: (a -> [b]) -> [a] -> [b] on bind(f, xs) -- concat :: a -> a -> [a] script concat on |λ|(a, b) a & b end |λ| end script   foldl(concat, {}, map(f, xs)) end bind   -- Monadic return/unit/inject for lists: just wraps a value in a list -- a -> [a] on unit(a) [a] end unit   -- TEST ------------------------------------------------------------------------ on run -- Pythagorean triples drawn from integers in the range [1..n] -- {(x, y, z) | x <- [1..n], y <- [x+1..n], z <- [y+1..n], (x^2 + y^2 = z^2)}   pythagoreanTriples(25)   --> {{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17}, -- {9, 12, 15}, {12, 16, 20}, {15, 20, 25}}   end run   -- pythagoreanTriples :: Int -> [(Int, Int, Int)] on pythagoreanTriples(maxInteger) script X on |λ|(X) script Y on |λ|(Y) script Z on |λ|(Z) if X * X + Y * Y = Z * Z then unit([X, Y, Z]) else [] end if end |λ| end script   bind(Z, enumFromTo(1 + Y, maxInteger)) end |λ| end script   bind(Y, enumFromTo(1 + X, maxInteger)) end |λ| end script   bind(X, enumFromTo(1, maxInteger))   end pythagoreanTriples     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if n < m then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end enumFromTo   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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).
#JavaScript
JavaScript
function array() { var dimensions= Array.prototype.slice.call(arguments); var N=1, rank= dimensions.length; for (var j= 0; j<rank; j++) N*= dimensions[j]; this.dimensions= dimensions; this.values= new Array(N); }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#360_Assembly
360 Assembly
* 12*12 multiplication table 14/08/2015 MULTTABL CSECT USING MULTTABL,R12 LR R12,R15 LA R10,0 buffer pointer LA R3,BUFFER MVC 0(4,R3),=C' | ' LA R10,4(R10) LA R5,12 LA R4,1 i=1 LOOPN LA R3,BUFFER do i=1 to 12 AR R3,R10 XDECO R4,XDEC i MVC 0(4,R3),XDEC+8 output i LA R10,4(R10) LA R4,1(R4) BCT R5,LOOPN end i XPRNT BUFFER,52 XPRNT PORT,52 border LA R5,12 LA R4,1 i=1 (R4) LOOPI LA R10,0 do i=1 to 12 MVC BUFFER,=CL52' ' LA R3,BUFFER AR R3,R10 XDECO R4,XDEC MVC 0(2,R3),XDEC+10 LA R10,2(R10) LA R3,BUFFER AR R3,R10 MVC 0(2,R3),=C'| ' LA R10,2(R10) LA R7,12 LA R6,1 j=1 (R6) LOOPJ CR R6,R4 do j=1 to 12 BNL MULT LA R3,BUFFER AR R3,R10 MVC 0(4,R3),=C' ' LA R10,4(R10) B NEXTJ MULT LR R9,R4 i MR R8,R6 i*j in R8R9 LA R3,BUFFER AR R3,R10 XDECO R9,XDEC MVC 0(4,R3),XDEC+8 LA R10,4(R10) NEXTJ LA R6,1(R6) BCT R7,LOOPJ end j ELOOPJ XPRNT BUFFER,52 LA R4,1(R4) BCT R5,LOOPI end i ELOOPI XR R15,R15 BR R14 BUFFER DC CL52' ' XDEC DS CL12 PORT DC C'--+-------------------------------------------------' YREGS END MULTTABL
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).
#Haskell
Haskell
import Numeric.LinearAlgebra import Numeric.LinearAlgebra.LAPACK   m :: Matrix Double m = (3><3) [7.589183,1.703609,-4.477162, -4.597851,9.434889,-6.543450, 0.4588202,-6.115153,1.331191]   v :: Matrix Double v = (3><1) [1.745005,-4.448092,-4.160842]
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.
#Clojure
Clojure
(defn !! [m n] (->> (iterate #(- % m) n) (take-while pos?) (apply *)))   (doseq [m (range 1 6)] (prn m (map #(!! m %) (range 1 11))))
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.
#EchoLisp
EchoLisp
  (lib 'plot) (plot-x-minmax 10) ; set logical dimensions of plotting area (plot-y-minmax 100) → (("x" 0 10) ("y" 0 100)) ;; press ESC to see the canvas ;; the mouse position is displayed as , for example, [ x: 5.6 y : 88.7] ;; 0 <= x <= 10, 0 <= y <= 100  
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.
#Elm
Elm
import Graphics.Element exposing (Element, show) import Mouse     main : Signal Element main = Signal.map show Mouse.position
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
#Factor
Factor
USING: kernel sequences math math.combinatorics formatting io locals ; IN: queens   : /= ( x y -- ? ) = not ; inline   :: safe? ( board q -- ? ) [let q board nth :> x q <iota> [ x swap [ board nth ] keep q swap - [ + /= ] [ - /= ] 3bi and ] all? ] ;   : solution? ( board -- ? ) dup length <iota> [ dupd safe? ] all? nip ;   : queens ( n -- l ) <iota> all-permutations [ solution? ] filter ;   : .queens ( n -- ) queens [ [ 1 + "%d " printf ] each nl ] each ;
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)).
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const type: oneFactor is new struct var bigInteger: prime is 0_; var integer: exp is 0; end struct;   const func oneFactor: oneFactor (in bigInteger: prime, in integer: exp) is func result var oneFactor: aFactor is oneFactor.value; begin aFactor.prime := prime; aFactor.exp := exp; end func;   const func array oneFactor: factor (in var bigInteger: n) is func result var array oneFactor: pf is 0 times oneFactor.value; local var integer: e is 0; var bigInteger: d is 0_; var bigInteger: s is 0_; begin e := lowestSetBit(n); if e > 0 then n >>:= e; pf := [] (oneFactor(2_, e)); end if; s := sqrt(n); d := 3_; while n > 1_ do if d > s then d := n; end if; e := 0; while n rem d = 0_ do n := n div d; incr(e); end while; if e > 0 then pf &:= oneFactor(d, e); s := sqrt(n); end if; d +:= 2_; end while; end func;   const func bigInteger: moBachShallit58(in bigInteger: a, in bigInteger: n, in array oneFactor: pf) is func result var bigInteger: mo is 0_; local var bigInteger: n1 is 0_; var oneFactor: pe is oneFactor.value; var bigInteger: x is 0_; var bigInteger: y is 0_; var integer: o is 0; var bigInteger: o1 is 0_; begin n1 := n - 1_; mo := 1_; for pe range pf do y := n1 div pe.prime ** pe.exp; x := modPow(a, y, n); o := 0; while x > 1_ do x := modPow(x, pe.prime, n); incr(o); end while; o1 := pe.prime ** o; mo *:= o1 div gcd(mo, o1); end for; end func;   const func boolean: isProbablyPrime (in bigInteger: primeCandidate, in var integer: count) is func result var boolean: isProbablyPrime is TRUE; local var bigInteger: aRandomNumber is 0_; begin while isProbablyPrime and count > 0 do aRandomNumber := rand(1_, pred(primeCandidate)); isProbablyPrime := modPow(aRandomNumber, pred(primeCandidate), primeCandidate) = 1_; decr(count); end while; # writeln(count); end func;   const proc: moTest (in bigInteger: a, in bigInteger: n) is func begin if bitLength(a) < 100 then write("ord(" <& a <& ")"); else write("ord([big])"); end if; if bitLength(n) < 100 then write(" mod " <& n <& " "); else write(" mod [big] "); end if; if not isProbablyPrime(n, 20) then writeln("not computed. modulus must be prime for this algorithm.") else writeln("= " <& moBachShallit58(a, n, factor(n - 1_))); end if; end func;   const proc: main is func local var bigInteger: b is 100_; begin moTest(37_, 3343_); moTest(10_ ** 100 + 1_, 7919_); moTest(10_ ** 1000 + 1_, 15485863_); moTest(10_ ** 10000 - 1_, 22801763489_); moTest(1511678068_, 7379191741_); moTest(3047753288_, 2257683301_); end func;
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)).
#Sidef
Sidef
say 37.znorder(1000) #=> 100 say 54.znorder(100001) #=> 9090
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.
#Sather
Sather
class MATH is nthroot(n:INT, a:FLT):FLT pre n > 0 is x0 ::= a / n.flt; m  ::= n - 1; loop x1 ::= (m.flt * x0 + a/(x0^(m.flt))) / n.flt; if (x1 - x0).abs < (x0 * 1.0e-9).abs then return x1; end; x0 := x1; end; end;   end;
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.
#Scala
Scala
def nroot(n: Int, a: Double): Double = { @tailrec def rec(x0: Double) : Double = { val x1 = ((n - 1) * x0 + a/math.pow(x0, n-1))/n if (x0 <= x1) x0 else rec(x1) }   rec(a) }
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.
#MATLAB
MATLAB
function s = nth(n) tens = mod(n, 100); if tens > 9 && tens < 20 suf = 'th'; else switch mod(n, 10) case 1 suf = 'st'; case 2 suf = 'nd'; case 3 suf = 'rd'; otherwise suf = 'th'; end end s = sprintf('%d%s', n, suf); end
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
#MAD
MAD
NORMAL MODE IS INTEGER DIMENSION P(5)   THROUGH CLCPOW, FOR D=0, 1, D.G.5 P(D) = D THROUGH CLCPOW, FOR X=1, 1, X.GE.D CLCPOW P(D) = P(D) * D   THROUGH TEST, FOR D1=0, 1, D1.G.5 THROUGH TEST, FOR D2=0, 1, D2.G.5 THROUGH TEST, FOR D3=0, 1, D3.G.5 THROUGH TEST, FOR D4=1, 1, D4.G.5 N = D1*1000 + D2*100 + D3*10 + D4 WHENEVER P(D1)+P(D2)+P(D3)+P(D4) .E. N PRINT FORMAT FMT,N TEST END OF CONDITIONAL   VECTOR VALUES FMT = $I4*$ END OF PROGRAM
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).
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main import "fmt"   func F(n int) int { if n == 0 { return 1 } return n - M(F(n-1)) }   func M(n int) int { if n == 0 { return 0 } return n - F(M(n-1)) }   func main() { for i := 0; i < 20; i++ { fmt.Printf("%2d ", F(i)) } fmt.Println() for i := 0; i < 20; i++ { fmt.Printf("%2d ", M(i)) } fmt.Println() }
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
#Oz
Oz
declare Xs = {MakeList 5} %% a list of 5 unbound variables in {ForAll Xs OS.rand} %% fill it with random numbers (CORRECT) {Show Xs}
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
#Pascal
Pascal
(Foo->new) x $n # here Foo->new can be any expression that returns a reference representing # a new object
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
#Perl
Perl
(Foo->new) x $n # here Foo->new can be any expression that returns a reference representing # a new object
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#J
J
nextMotzkin=: , (({:*1+2*#) + _2&{*3*#-1:)%2+#