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/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Phix
Phix
with javascript_semantics function Moebius(integer n) if n=1 then return 1 end if sequence f = prime_factors(n,true) for i=2 to length(f) do if f[i] = f[i-1] then return 0 end if end for return iff(odd(length(f))?-1:+1) end function sequence s = {" ."} for i=1 to 199 do s = append(s,sprint...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Racket
Racket
  #lang racket (define (natural-sort l) (define (list<? l1 l2) (cond [(null? l2) #f] [(null? l1) #t] [(number? (car l1)) (cond [(< (car l1) (car l2)) #t] [(< (car l2) (car l1)) #f] [else (list<? (cdr l1) (cdr l2))])] ...
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Wren
Wren
import "/fmt" for Fmt   var ncs = Fn.new { |a| var f = "$d " if (a[0] is String) { for (i in 0...a.count) a[i] = a[i].bytes[0] f = "$c " } var generate // recursive generate = Fn.new { |m, k, c| if (k == m) { if (c[m - 1] != c[0] + m - 1) { for (i ...
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Lua
Lua
function dec2base (base, n) local result, digit = "" while n > 0 do digit = n % base if digit > 9 then digit = string.char(digit + 87) end n = math.floor(n / base) result = digit .. result end return result end   local x = dec2base(16, 26) print(x) --> ...
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...
#Elixir
Elixir
defmodule RC do def narcissistic(m) do Enum.reduce(1..10, [0], fn digits,acc -> digitPowers = List.to_tuple(for i <- 0..9, do: power(i, digits)) Enum.reduce(power(10, digits-1) .. power(10, digits)-1, acc, fn n,result -> sum = divsum(n, digitPowers, 0) if n == sum do if lengt...
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...
#ERRE
ERRE
PROGRAM NARCISISTIC   !$DOUBLE   BEGIN N=0 LOOP C$=MID$(STR$(N),2) LENG=LEN(C$) SUM=0 FOR I=1 TO LENG DO C=VAL(MID$(C$,I,1)) SUM+=C^LENG END FOR IF N=SUM THEN PRINT(N;) COUNT=COUNT+1 EXIT IF COUNT=25 END IF N=N+1 END LOO...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#F.C5.8Drmul.C3.A6
Fōrmulæ
vec3 color; float c,p; vec2 b;   void main(void) { vec2 uv = gl_FragCoord.xy / iResolution.xy; float scale = iResolution.x / iResolution.y; uv = uv-0.5; uv.y/=scale;   b = uv*256.0+256.0; c = 0.0;     for(float i=16.0;i>=1.0;i-=1.0) { p = pow(2.0,i);   if((p < b.x) ^^ (p < b.y)) { c += p; }  ...
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 ...
#APL
APL
(⊢(/⍨)⊢=+/∘(*⍨∘⍎¨⍕)¨)⍳ 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 ) ) , ...
#ARM_Assembly
ARM Assembly
.text .global _start @@@ Implementation of F(n), n in R0. n is considered unsigned. F: tst r0,r0 @ n = 0? moveq r0,#1 @ In that case, the result is 1 bxeq lr @ And we can return to the caller push {r0,lr} @ Save link register and argument to stack sub r0,r0,#1 @ r0 -= 1 = n-1 bl F @ r0 = F(r0) = F(n-1) b...
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#J
J
require'media/wav' 0.25 wavnote 0 2 4 5 7 9 11 12
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#JavaScript
JavaScript
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Sample Page</title> </head> <body> Upon loading the page you should hear the scale. <script type="text/javascript"> function musicalScale(freqArr){ // create web audio api context var AudioContext = window.AudioContext || window.webkitAudioContext; ...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#C
C
#include <stdio.h> #include <string.h>   void parse_sep(const char *str, const char *const *pat, int len) { int i, slen; while (*str != '\0') { for (i = 0; i < len || !putchar(*(str++)); i++) { slen = strlen(pat[i]); if (strncmp(str, pat[i], slen)) continue; printf("{%.*s}", slen, str); str += slen; ...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory qw<primes>; use List::Util qw<min>;   #use bigint # works, but slow use Math::GMPz; # this module gives roughly 16x speed-up   sub smooth_numbers { # my(@m) = @_; # use with 'bigint' my @m = map { Math::GMPz->new($_) } @_;...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#LabVIEW
LabVIEW
define mymethod( -first::integer, // with no default value the param is required -second::integer, -delimiter::string = ':' // when given a default value the param becomes optional ) => #first + #delimiter + #second   mymethod( -first = 54, -second = 45 ) '<br />' mymethod( -second = 45, // named params can be gi...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Lasso
Lasso
define mymethod( -first::integer, // with no default value the param is required -second::integer, -delimiter::string = ':' // when given a default value the param becomes optional ) => #first + #delimiter + #second   mymethod( -first = 54, -second = 45 ) '<br />' mymethod( -second = 45, // named params can be gi...
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.
#Go
Go
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#BCPL
BCPL
get "libhdr"   // Generate ASCII string of number n with ordinal suffix // The string is stored at v. let nth(n, v) = valof $( let sfx = "thstndrd" let c, s = 0, ? // Generate digits $( c := c + 1 v%c := n rem 10 + '0' n := n / 10 $) repeatuntil n = 0   // Put digits in correct ord...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Python
Python
  # Python Program to evaluate # Mobius def M(N) = 1 if N = 1 # M(N) = 0 if any prime factor # of N is contained twice # M(N) = (-1)^(no of distinct # prime factors) # Python Program to # evaluate Mobius def # M(N) = 1 if N = 1 # M(N) = 0 if any # prime factor of # N is contained twice # M(N) = (-1)^(no of # distinct p...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Raku
Raku
# Sort groups of digits in number order. Sort by order of magnitude then lexically. sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~$0.chars.chr~$0},:g) ~"\x0"~$a }   # Collapse multiple ws characters to a single. sub collapse ($a) { $a.subst( / ( \s ) $0+ /, -> $/ { $0 }, :g ) }   # Convert all ws characters to a sp...
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#zkl
zkl
fcn non_continuous_subsequences(ary){ pwerSet(ary).filter(fcn(list){(not isContinuous(list)) }) } fcn isContinuous(ary){ if(ary.len()<2) return(True); foreach n in (ary.len()-1){ if(1+ary[n]!=ary[n+1]) return(False); } return(True); } non_continuous_subsequences(T(1,2,3,4)).println();
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { k$=lambda$ (m, b as integer=16) -> { if b<2 or b>16 then error "base out of range" if m=0 then ="0" : exit z$="0123456789ABCDEF" =lambda$ z$, b (m) ->{ =if$(m=0->"", lambda$(m div b)+mid$(z$, m mod b + 1, 1)) }(m) } k=lambda (m$, b as integer=16) -> { if b<2 or b>...
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...
#F.23
F#
  //Naïve solution of Narcissitic number: Nigel Galloway - Febryary 18th., 2015 open System let rec _Digits (n,g) = if n < 10 then n::g else _Digits(n/10,n%10::g)   seq{0 .. Int32.MaxValue} |> Seq.filter (fun n -> let d = _Digits (n, []) d |> List.fold (fun a l -> a + int ((float l) ** (float (List.length d)))) 0 =...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#GLSL
GLSL
vec3 color; float c,p; vec2 b;   void main(void) { vec2 uv = gl_FragCoord.xy / iResolution.xy; float scale = iResolution.x / iResolution.y; uv = uv-0.5; uv.y/=scale;   b = uv*256.0+256.0; c = 0.0;     for(float i=16.0;i>=1.0;i-=1.0) { p = pow(2.0,i);   if((p < b.x) ^^ (p < b.y)) { c += p; }  ...
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 ...
#AppleScript
AppleScript
------------------- MUNCHAUSEN NUMBER ? --------------------   -- isMunchausen :: Int -> Bool on isMunchausen(n)   -- digitPowerSum :: Int -> Character -> Int script digitPowerSum on |λ|(a, c) set d to c as integer a + (d ^ d) end |λ| end script   (class of n is i...
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Arturo
Arturo
f: $[n][ if? n=0 -> 1 else -> n-m f n-1 ] m: $[n][ if? n=0 -> 0 else -> n-f m n-1 ]   loop 0..20 'i [ print ["f(" i ")=" f i] print ["m(" i ")=" m i] print "" ]
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Julia
Julia
using PortAudio   function paudio() devs = PortAudio.devices() devnum = findfirst(x -> x.maxoutchans > 0, devs) (devnum == nothing) && error("No output device for audio found") return PortAudioStream(devs[devnum].name, 0, 2) end   function play(ostream, pitch, durationseconds) sinewave(t) = 0.6sin(t...
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Kotlin
Kotlin
// Kotlin Native v0.3   import kotlinx.cinterop.* import win32.*   fun main(args: Array<String>) { val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523) // CDEFGABc val dur = 500 repeat(5) { for (freq in freqs) Beep(freq, dur) } }
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Multisplit { internal static class Program { private static void Main(string[] args) { foreach (var s in "a!===b=!=c".Multisplit(true, "==", "!=", "=")) // Split the string and return th...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Phix
Phix
with javascript_semantics include mpfr.e function nsmooth(integer n, integer needed) -- note that n is a prime index, ie 1,2,3,4... for 2,3,5,7... sequence smooth = {mpz_init(1)}, nexts = get_primes(-n), indices = repeat(1,n) for i=1 to n do nexts[i] = mpz_init(nexts[i]) end for ...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Lingo
Lingo
-- accepts either 3 integers or a single property list on foo (arg1, arg2, arg3) if ilk(arg1)=#propList then args = arg1 arg1 = args[#arg1] arg2 = args[#arg2] arg3 = args[#arg3] end if put "arg1="&arg1 put "arg2="&arg2 put "arg3="&arg3 end   foo(1,2) -- 3rd argument omitted -- "arg1=1" -- "arg...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Lua
Lua
  function CreatePet(options) local name=options.name local species=options.species local breed=options.breed print('Created a '..breed..' '..species..' named '..name) end CreatePet{name='Rex',species='Dog',breed='Irish Setter'} --position does not matter here.  
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.
#Groovy
Groovy
import static Constants.tolerance import static java.math.RoundingMode.HALF_UP   def root(double base, double n) { double xOld = 1 double xNew = 0 while (true) { xNew = ((n - 1) * xOld + base/(xOld)**(n - 1))/n if ((xNew - xOld).abs() < tolerance) { break } xOld = xNew } (xNew as...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Befunge
Befunge
0>55*:>1-\:0\`!v #v$#$<^:\+*8"}"_ >35*:>1-\:0\`!v #v$#$<^:\+*2"}"_ 5< v$_v#!::-<0*5 @v <,*>#81#4^# _   >>:0\>:55+%68*v: tsnr |:/+ 55\+<, htdd >$>:#,_$:vg v"d"\*!`3:%+55<9 >%55+/1-!!*:8g,^
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Raku
Raku
use Prime::Factor;   sub μ (Int \n) { return 0 if n %% 4 or n %% 9 or n %% 25 or n %% 49 or n %% 121; my @p = prime-factors(n); +@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0 }   my @möbius = lazy flat '', 1, (2..*).hyper.map: -> \n { μ(n) };   # The Task put "Möbius sequence - First 199 terms:\n", @möbi...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#REXX
REXX
/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/ parse arg LO HI grp . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 199 ...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ruby
Ruby
ar.sort_by{|str| str.downcase.gsub(/\Athe |\Aa |\Aan /, "").lstrip.gsub(/\s+/, " ")}
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#M4
M4
eval(26,16) define(`frombase',`eval(0r$2:$1)') frombase(1a,16)
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Factor
Factor
USING: io kernel lists lists.lazy math math.functions math.text.utils prettyprint sequences ; IN: rosetta-code.narcissistic-decimal-number   : digit-count ( n -- count ) log10 floor >integer 1 + ;   : narcissist? ( n -- ? ) dup [ 1 digit-groups ] [ digit-count [ ^ ] curry ] bi map-sum = ;   : first25 ( -- seq ) 25 ...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Gnuplot
Gnuplot
set pm3d map set size square set isosamples 255,255 splot [0:255][0:255]-(floor(x)^floor(y))
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Go
Go
package main   import ( "image" "image/png" "os" )   func main() { g := image.NewGray(image.Rect(0, 0, 256, 256)) for i := range g.Pix { g.Pix[i] = uint8(i>>8 ^ i) } f, _ := os.Create("xor.png") png.Encode(f, g) f.Close() }
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 ...
#Arturo
Arturo
munchausen?: function [n][ n = sum map split to :string n 'digit [ d: to :integer digit d^d ] ]   loop 1..5000 'x [ if munchausen? x -> print x ]
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 ) ) , ...
#AutoHotkey
AutoHotkey
Loop 20 i := A_Index-1, t .= "`n" i "`t " M(i) "`t " F(i) MsgBox x`tmale`tfemale`n%t%   F(n) { Return n ? n - M(F(n-1)) : 1 }   M(n) { Return n ? n - F(M(n-1)) : 0 }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Lilypond
Lilypond
% Start at middle C \relative c' { c d e f g a b c }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Locomotive_Basic
Locomotive Basic
10 mode 1 20 print "Note","Freq. (Hz)","Period" 30 ' program loop: 40 if sq(1)<128 then gosub 70 ' play next note if channel is inactive 50 goto 40 60 ' play next note 70 read n 80 if n<0 then end 90 note=note+1 100 ' calculation from chapter 7, page 26 of the CPC manual: 110 f=440*(2^((n-10)/12)) 120 p=round(62500/f)...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#C.2B.2B
C++
#include <iostream> #include <boost/tokenizer.hpp> #include <string>   int main( ) { std::string str( "a!===b=!=c" ) , output ; typedef boost::tokenizer<boost::char_separator<char> > tokenizer ; boost::char_separator<char> separator ( "==" , "!=" ) , sep ( "!" ) ; tokenizer mytok( str , separator ) ; to...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Python
Python
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]   def isPrime(n): if n < 2: return False   for i in primes: if n == i: return True if n % i == 0: return False if i * i > n: return True print "Oops,", n, " is too large"   def init(): s = 24 ...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#M2000_Interpreter
M2000 Interpreter
  module namedparam (x as decimal=10, y as integer=50) { Print type$(x), x Print type$(y), y } namedparam 10, 20 namedparam  ?, ? Push 1, 2 : namedparam Stack New { \\ it is empty namedparam namedparam  %y=500 namedparam  %x=20 } namedparam %x=1, %y=1  
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Maple
Maple
f := proc(a, {b:= 1, c:= 1}) print (a*(c+b)); end proc: #a is a mandatory positional parameter, b and c are optional named parameters f(1);#you must have a value for a for the procedure to work 2 f(1, c = 1, b = 2); ...
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.
#Haskell
Haskell
n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n)
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#BQN
BQN
Nth ← { sfx ← ⟨"th","st","nd","rd"⟩ (•Fmt 𝕩)∾sfx⊑˜ (1≠10|⌊𝕩÷10)×(3≥10|𝕩)×10|𝕩 }   ∘‿4⥊ Nth¨ (↕26) ∾ (250+↕16) ∾ (1000+↕26)
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Ring
Ring
  mobStr = " . "   for i = 1 to 200 if mobius(i) >= 0 mobStr + = " " ok temp = string(mobius(i)) if left(temp,2) = "-0" temp = right(temp,len(temp)-1) ok mobStr += temp + " " if i % 10 = 9 see mobStr + nl mobStr = " " ok next   func mobius(n) ...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Ruby
Ruby
require 'prime'   def μ(n) pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end   ([" "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }    
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Scala
Scala
object NaturalSorting { implicit object ArrayOrdering extends Ordering[Array[String]] { // 4 val INT = "([0-9]+)".r def compare(a: Array[String], b: Array[String]) = { val l = Math.min(a.length, b.length) (0 until l).prefixLength(i => a(i) equals b(i)) match { case i if i == l => Math.sign...
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Maple
Maple
#converts a number to a given based represented by a string to_base := proc(num, based) local i; local chart := "0123456789abcdefghijklmnopqrstuvwxyz"; local conversion := ListTools:-Reverse((convert(num,base,based))); local str := StringTools:-StringBuffer(); for i in conversion do str:-append(chart[i+1]...
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
IntegerString[26,16] FromDigits["1a", 16])
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Forth
Forth
   : dig.num \ returns input number and the number of its digits ( n -- n n1 ) dup 0 swap begin swap 1 + swap dup 10 >= while 10 / repeat drop ;    : zero.divmod \ /mod that returns zero if number is zero dup 0 = if drop 0 else /...
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...
#FreeBASIC
FreeBASIC
' normal version: 14-03-2017 ' compile with: fbc -s console ' can go up to 18 digits (ulongint is 64bit), above 18 overflow will occur   Dim As Integer n, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, a, b Dim As Integer d() Dim As ULongInt d2pow(0 To 9) = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} Dim As ULongInt x Dim As String str_x ...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Haskell
Haskell
import qualified Data.ByteString as BY (writeFile, pack)   import Data.Bits (xor)   main :: IO () main = BY.writeFile "out.pgm" (BY.pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [ x `xor` y | x <- [0 .. 255] , y <- [0 .. 255] ]))
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main(A) #: XOR graphic wsize := 512 cmax := 32768 wparms := ["Xmas Xor Graphic","g",sprintf("size=%d,%d",wsize),"bg=black"] &window := open!wparms | stop("Unable to open window")   every y := 0 to wsize - 1 do every x := 0 to wsize - 1 do { c := cmax/wsize * iand...
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 ...
#AutoHotkey
AutoHotkey
Loop, 5000 { Loop, Parse, A_Index var += A_LoopField**A_LoopField if (var = A_Index) num .= var "`n" var := 0 } Msgbox, %num%
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 ) ) , ...
#AWK
AWK
cat mutual_recursion.awk: #!/usr/local/bin/gawk -f   # User defined functions function F(n) { return n == 0 ? 1 : n - M(F(n-1)) }   function M(n) { return n == 0 ? 0 : n - F(M(n-1)) }   BEGIN { for(i=0; i <= 20; i++) { printf "%3d ", F(i) } print "" for(i=0; i <= 20; i++) { printf "%3d ", M(i) } pri...
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Lua
Lua
c = string.char midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) -- header midi = midi .. "MTrk" .. c(0,0,0,8*8+4) -- track for _,note in ipairs{60,62,64,65,67,69,71,72} do midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0) -- notes end midi = midi .. c(0, 0xFF, 0x2F, 0) -- end   file = io.open("scale.mid", "wb") fil...
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#CoffeeScript
CoffeeScript
  multi_split = (text, separators) -> # Split text up, using separators to break up text and discarding # separators. # # Returns an array of strings, which can include empty strings when # separators are found either adjacent to each other or at the # beginning/end of the text. # # Separators have prec...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Quackery
Quackery
  [ behead 0 swap rot witheach [ 2dup < iff drop done nip nip i^ 1+ swap ] ] is smallest ( [ --> n n )   [ stack ] is end.test ( --> s )   [ ]'[ end.test put dup temp put ' [ 1 ] 0 rot size of [ over end.test shar...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Raku
Raku
sub smooth-numbers (*@list) { cache my \Smooth := gather { my %i = (flat @list) Z=> (Smooth.iterator for ^@list); my %n = (flat @list) Z=> 1 xx *;   loop { take my $n := %n{*}.min;   for @list -> \k { %n{k} = %i{k}.pull-one * k if %n{k} == $n; ...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Options[fn]={Add->False,Offset-> 0}; fn[x_,y_,OptionsPattern[]]:=If[OptionValue[Add]==True,x+y+OptionValue[Offset],{x,y,OptionValue[Offset]}] fn[3,4,{Add->True,Offset->2}] fn[3,4,{Offset->2,Add->True}]
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#MATLAB_.2F_Octave
MATLAB / Octave
function foo(varargin) for k= 1:2:length(varargin); switch (varargin{k}) case {'param1'} param1 = varargin{k+1}; case {'param2'} param2 = varargin{k+1}; end; end; printf('param1: %s\n',param1); printf('param2: %s\n',param2); end;   fo...
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.
#HicEst
HicEst
WRITE(Messagebox) NthRoot(5, 34) WRITE(Messagebox) NthRoot(10, 7131.5^10)   FUNCTION NthRoot(n, A) REAL :: prec = 0.001   IF( (n > 0) * (A > 0) ) THEN NthRoot = A / n DO i = 1, 1/prec x = ((n-1)*NthRoot + A/(NthRoot^(n-1))) / n IF( ABS(x - NthRoot) <= prec ) THEN RETUR...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#C
C
#include <stdio.h>   char* addSuffix(int num, char* buf, size_t len) { char *suffixes[4] = { "th", "st", "nd", "rd" }; int i;   switch (num % 10) { case 1 : i = (num % 100 == 11) ? 0 : 1; break; case 2 : i = (num % 100 == 12) ? 0 : 2; break; case 3 : i ...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Sidef
Sidef
say moebius(53) #=> -1 say moebius(54) #=> 0 say moebius(55) #=> 1
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Tiny_BASIC
Tiny BASIC
PRINT "Enter an integer" INPUT N IF N < 0 THEN LET N = -N IF N < 2 THEN GOTO 100 + N LET C = 1 LET F = 2 10 IF ((N/F)/F)*F*F = N THEN GOTO 100 IF (N/F)*F = N THEN GOTO 30 20 LET F = F + 1 IF F<=N THEN GOTO 10 GOTO 100 + C 30 LET N = N / F LET C = -C GOTO 20 99 PRINT "-1" ...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int   var isSquareFree = Fn.new { |n| var i = 2 while (i * i <= n) { if (n%(i*i) == 0) return false i = (i > 2) ? i + 2 : i + 1 } return true }   var mu = Fn.new { |n| if (n < 1) Fiber.abort("Argument must be a positive integer") if (n == ...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme write) (only (srfi 1) drop take-while) (only (srfi 13) string-drop string-join string-prefix-ci? string-tokenize) (srfi 132))     ;; Natural sort function (define (natural-sort lst) ; <1><2> ignores leading, trailing and multiple ad...
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#MATLAB_.2F_Octave
MATLAB / Octave
dec2base(26,16) base2dec('1a', 16)
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#FunL
FunL
def narcissistic( start ) = power = 1 powers = array( 0..9 )   def narc( n ) = num = n.toString() m = num.length()   if power != m power = m powers( 0..9 ) = [i^m | i <- 0..9]   if n == sum( powers(int(d)) | d <- num ) n # narc( n + 1 ) else narc( n + 1 )   narc( star...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#J
J
require 'viewmat' viewmat ~:"1/&.#: ~ i.256
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Java
Java
import java.awt.Color; import java.awt.Graphics;   import javax.swing.JFrame; import javax.swing.JPanel;   public class XorPattern extends JFrame{ private JPanel xorPanel;   public XorPattern(){ xorPanel = new JPanel(){ @Override public void paint(Graphics g) { fo...
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 ...
#AWK
AWK
  # syntax: GAWK -f MUNCHAUSEN_NUMBERS.AWK BEGIN { for (i=1; i<=5000; i++) { sum = 0 for (j=1; j<=length(i); j++) { digit = substr(i,j,1) sum += digit ^ digit } if (i == sum) { printf("%d\n",i) } } exit(0) }  
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 ) ) , ...
#BaCon
BaCon
' Mutually recursive FUNCTION F(int n) TYPE int RETURN IIF(n = 0, 1, n - M(F(n -1))) END FUNCTION   FUNCTION M(int n) TYPE int RETURN IIF(n = 0, 0, n - F(M(n - 1))) END FUNCTION   ' Get iteration limit, default 20 SPLIT ARGUMENT$ BY " " TO arg$ SIZE args limit = IIF(args > 1, VAL(arg$[1]), 20)   FOR i = 0 TO li...
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#M2000_Interpreter
M2000 Interpreter
  Module checkit { \\ using internal speaker TUNE 300, "C3DEFGABC4" TUNE 300, "C3C#DD#EFF#GG#AA#BC4" Thread { score 10, 100, "CAC" Play 10, 1 } as drums interval 1000 \\ Play in background (16 scores - no 10 for drum machine) SCORE 1, 300, "C3DEFGABC4" ...
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
EmitSound@Sound[SoundNote /@ {0, 2, 4, 5, 7, 9, 11, 12}]
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#D
D
import std.stdio, std.array, std.algorithm;   string[] multiSplit(in string s, in string[] divisors) pure nothrow { string[] result; auto rest = s.idup;   while (true) { bool done = true; string delim; { string best; foreach (const div; divisors) { ...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#11l
11l
-V BoardSize = 8   F underAttack(col, queens) I col C queens R 1B L(x) queens I abs(col - x) == queens.len - L.index R 1B R 0B   F solve(n) V result = [[Int]()] [[Int]] newSolutions L(row) 1 .. n L(solution) result L(i) 1 .. BoardSize I !underAttack(i, s...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#REXX
REXX
/*REXX pgm computes&displays X n-smooth numbers; both X and N can be specified as ranges*/ numeric digits 200 /*be able to handle some big numbers. */ parse arg LOx HIx LOn HIn . /*obtain optional arguments from the CL*/ if LOx=='' | LOx=="," then LOx= 1 ...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Modula-3
Modula-3
PROCEDURE Foo(Arg1: INTEGER; Arg2: REAL := 0.0);
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Nemerle
Nemerle
Foo(number : int, word = "Default", option = true) : void // note type inference with default values   Foo(word = "Bird", number = 3) // an argument with a default value can be omitted from function call Foo(3, option = false, word = "Bird") // unnamed arguments must be in same order as function definition and p...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Nim
Nim
proc subtract(x, y): auto = x - y   echo subtract(5, 3) # used as positional parameters echo subtract(y = 3, x = 5) # used as named parameters
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() showroot(125,3) showroot(27,3) showroot(1024,10) showroot(39.0625,4) showroot(7131.5^10,10) end   procedure showroot(a,n) printf("%i-th root of %i = %i\n",n,a,root(a,n)) end   procedure root(a,n,p) #: finds the n-th root of the number a to precision p if n < 0 | type(n) !== "intege...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#C.23
C#
using System; using System.Linq;   class Program { private static string Ordinalize(int i) { i = Math.Abs(i);   if (new[] {11, 12, 13}.Contains(i%100)) return i + "th";   switch (i%10) { case 1: return i + "st"; case 2: ...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#XPL0
XPL0
func Mobius(N); int N, Cnt, F, K; [Cnt:= 0; F:= 2; K:= 0; repeat if rem(N/F) = 0 then [Cnt:= Cnt+1; N:= N/F; K:= K+1; if K >= 2 then return 0; ] else [F:= F+1; K:= 0]; until F > N; return if Cnt&1 then -1 else 1; ];   int ...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Yabasic
Yabasic
outstr$ = " . " for i = 1 to 200 if mobius(i) >= 0 then outstr$ = outstr$ + " " : fi outstr$ = outstr$ + str$(mobius(i)) + " " if mod(i, 10) = 9 then print outstr$ outstr$ = "" end if next i end   sub mobius(n) if n = 1 then return 1 : fi for d = 2 to int(sqr(n)) if mo...
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#zkl
zkl
fcn mobius(n){ pf:=primeFactors(n); sq:=pf.filter1('wrap(f){ (n % (f*f))==0 }); // False if square free if(sq==False){ if(pf.len().isEven) 1 else -1 } else 0 } fcn primeFactors(n){ // Return a list of prime factors of n acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum if(n==1 or k>maxD)...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Sidef
Sidef
class String { # Sort groups of digits in number order. Sort by order of magnitude then lexically. -> naturally { self.lc.gsub(/(\d+)/, {|s1| "0" + s1.len.chr + s1 }) + "\x0" + self };   # Collapse multiple ws characters to a single. -> collapse { self.gsub(/(\s)\1+/, {|s1| s1 }) };   # Convert all ...
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П8 -> 1 0 П0 ПП 13 ИП7 П0 ИП8 ПП 13 С/П П7 -> П6 -> 1 П4 П5 Сx <-> ^ ПП 68 П3 - ИП7 * П2 ПП 68 ИП4 ИП6 * П4 / + ИП2 ИП1 - x#0 45 L0 27 -> ИП3 ^ ИП7 / ПП 68 ИП7 * - ИП5 * + ИП5 ИП6 * П5 -> ИП1 x=0 47 -> В/О 1 + П1 КИП1 -> -> ИП1 В/О
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func narc(n int) []int { power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} limit := 10 result := make([]int, 0, n) for x := 0; len(result) < n; x++ { if x >= limit { for i := range power { power[i] *= i // i^m } limit *= 10 } sum := 0 for xx := x; xx > 0; xx /= 10 { ...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#jq
jq
jq -n -r -f Munching_squares.jq > Munching_squares.svg
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Julia
Julia
using Gtk, Cairo   const can = @GtkCanvas() const win = GtkWindow(can, "Munching Squares", 512, 512)   @guarded draw(can) do widget ctx = getgc(can) for x in 0:255, y in 0:255 set_source_rgb(ctx, abs(255 - x - y) / 255, ((255 - x) ⊻ y) / 255, (x ⊻ (255 - y)) / 255) circle(ctx, 2x, 2y, 2) ...
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 ...
#BASIC
BASIC
10 DEF FN P(X)=INT(X^X*SGN(X)) 20 FOR I=0 TO 5 30 FOR J=0 TO 5 40 FOR K=0 TO 5 50 FOR L=0 TO 5 60 M=FN P(I)+FN P(J)+FN P(K)+FN P(L) 70 N=1000*I+100*J+10*K+L 80 IF M=N AND M>0 THEN PRINT M 90 NEXT L 100 NEXT K 110 NEXT J 120 NEXT I
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#BASIC
BASIC
DECLARE FUNCTION f! (n!) DECLARE FUNCTION m! (n!)   FUNCTION f! (n!) IF n = 0 THEN f = 1 ELSE f = m(f(n - 1)) END IF END FUNCTION   FUNCTION m! (n!) IF n = 0 THEN m = 0 ELSE m = f(m(n - 1)) END IF END FUNCTION
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Nanoquery
Nanoquery
import tonegen   note_freqs = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}   tg = new(tonegen) for freq in note_freqs tg.beep(freq) end