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/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Ursala
Ursala
#import nat   triangle = ~&a^?\<<&>>! ^|RNSiDlrTSPxSxNiCK9xSx4NiCSplrTSPT/~& predecessor
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Racket
Racket
  #lang racket (define (carpet n) (if (zero? n) '("#") (let* ([prev (carpet (sub1 n))] [spaces (regexp-replace* #rx"#" (car prev) " ")]) (append (map (λ(x) (~a x x x)) prev) (map (λ(x) (~a x spaces x)) prev) (map (λ(x) (~a x x x)) prev))))) (for-each displayln (carpet 3))  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Haskell
Haskell
import qualified Data.Set as S   semordnilaps :: (Ord a, Foldable t) => t [a] -> [[a]] semordnilaps = let f x (s, w) | S.member (reverse x) s = (s, x : w) | otherwise = (S.insert x s, w) in snd . foldr f (S.empty, [])   main :: IO () main = do s <- readFile "unixdict.txt" let l = semordnilaps (lines s) print $ length l mapM_ (print . ((,) <*> reverse)) $ take 5 (filter ((4 <) . length) l)
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#SQL_PL
SQL PL
  UPDATE DB CFG FOR myDb USING SMTP_SERVER 'smtp.ibm.com';   CALL UTL_MAIL.SEND ('[email protected]','[email protected]', '[email protected]', NULL, 'The subject of the message', 'The content of the message');  
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Tcl
Tcl
package require smtp package require mime package require tls   set gmailUser ******* set gmailPass hunter2; # Hello, bash.org!   proc send_simple_message {recipient subject body} { global gmailUser gmailPass   # Build the message set token [mime::initialize -canonical text/plain -string $body] mime::setheader $token Subject $subject   # Send it! smtp::sendmessage $token -userame $gamilUser -password $gmailPass \ -recipients $recipient -servers smtp.gmail.com -ports 587   # Clean up mime::finalize $token }   send_simple_message [email protected] "Testing" "This is a test message."
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Lua
Lua
  function semiprime (n) local divisor, count = 2, 0 while count < 3 and n ~= 1 do if n % divisor == 0 then n = n / divisor count = count + 1 else divisor = divisor + 1 end end return count == 2 end   for n = 1675, 1680 do print(n, semiprime(n)) end  
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Maple
Maple
SemiPrimes := proc( n ) local fact; fact := NumberTheory:-Divisors( n ) minus {1, n}; if numelems( fact ) in {1,2} and not( member( 'false', isprime ~ ( fact ) ) ) then return n; else return NULL; end if; end proc: { seq( SemiPrimes( i ), i = 1..100 ) };
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#D
D
import std.stdio, std.algorithm, std.string, std.numeric, std.ascii;   char checksum(in char[] sedol) pure @safe /*@nogc*/ in { assert(sedol.length == 6); foreach (immutable c; sedol) assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { assert(result.isDigit); } body { static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); return digits[10 - (d % 10)]; }   void main() { foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".split) writeln(sedol, sedol.checksum); }
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#LiveCode
LiveCode
function selfDescNumber n local tSelfD, tLen put len(n) into tLen repeat with x = 0 to (tLen - 1) put n into nCopy replace x with empty in nCopy put char (x + 1) of n = (tLen - len(nCopy)) into tSelfD if not tSelfD then exit repeat end repeat return tSelfD end selfDescNumber
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Logo
Logo
TO XX BT MAKE "AA (ARRAY 10 0) MAKE "BB (ARRAY 10 0) FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ] FOR [A 1 50000][ MAKE "B COUNT :A MAKE "Y 0 MAKE "X 0 MAKE "R 0 MAKE "J 0 MAKE "K 0   FOR [C 1 :B][MAKE "D ITEM :C :A SETITEM :C - 1 :AA :D MAKE "X ITEM :D :BB MAKE "Y :X + 1 SETITEM :D :BB :Y MAKE "R 0] FOR [Z 0 9][MAKE "J ITEM :Z :AA MAKE "K ITEM :Z :BB IF :J = :K [MAKE "R :R + 1]] IF :R = 10 [PR :A] FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ]] PR [END] END
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[primeq] primeq[1]:=False primeq[2]:=True primeq[n_Integer?(GreaterThan[2])]:=Module[{}, AllTrue[Range[2,Sqrt[n]+1],Mod[n,#]!=0&] ] Select[Range[100],primeq]
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#MATLAB
MATLAB
function primeList = sieveOfEratosthenes(lastNumber)   list = (2:lastNumber); %Construct list of numbers primeList = []; %Preallocate prime list   while( list(1)^2 <lastNumber )   primeList = [primeList list(1)]; %add prime to the prime list list( mod(list,list(1))==0 ) = []; %filter out all multiples of the current prime   end   primeList = [primeList list]; %The rest of the numbers in the list are primes   end
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#GAP
GAP
# Here we use generators : the given formula doesn't need one, but the alternate # non-squares function is better done with a generator.   # The formula is implemented with exact floor(sqrt(n)), so we use # a trick: multiply by 100 to get the first decimal digit of the # square root of n, then add 5 (that's 1/2 multiplied by 10). # Then just divide by 10 to get floor(1/2 + sqrt(n)) exactly. # It looks weird, but unlike floating point, it will do the job # for any n. NonSquaresGen := function() local ns, n; n := 0; ns := function() n := n + 1; return n + QuoInt(5 + RootInt(100*n), 10); end; return ns; end;   NonSquaresAlt := function() local ns, n, q, k; n := 1; q := 4; k := 3; ns := function() n := n + 1; if n = q then n := n + 1; k := k + 2; q := q + k; fi; return n; end; return ns; end;   gen := NonSquaresGen(); List([1 .. 22] i -> gen()); # [ 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27 ]   a := NonSquaresGen(); b := NonSquaresAlt();   ForAll([1 .. 1000000], i -> a() = b()); # true
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Go
Go
package main   import ( "fmt" "math" )   func remarkable(n int) int { return n + int(.5+math.Sqrt(float64(n))) }   func main() { // task 1 fmt.Println(" n r(n)") fmt.Println("--- ---") for n := 1; n <= 22; n++ { fmt.Printf("%3d  %3d\n", n, remarkable(n)) }   // task 2 const limit = 1e6 fmt.Println("\nChecking for squares for n <", limit) next := 2 nextSq := 4 for n := 1; n < limit; n++ { r := remarkable(n) switch { case r == nextSq: panic(n) case r > nextSq: fmt.Println(nextSq, "didn't occur") next++ nextSq = next * next } } fmt.Println("No squares occur for n <", limit) }
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Forth
Forth
include FMS-SI.f include FMS-SILib.f   : union {: a b -- c :} begin b each: while dup a indexOf: if 2drop else a add: then repeat b <free a dup sort: ; ok   i{ 2 5 4 3 } i{ 5 6 7 } union p: i{ 2 3 4 5 6 7 } ok     : free2 ( a b -- ) <free <free ; : intersect {: a b | c -- c :} heap> 1-array2 to c begin b each: while dup a indexOf: if drop c add: else drop then repeat a b free2 c dup sort: ;   i{ 2 5 4 3 } i{ 5 6 7 } intersect p: i{ 5 } ok     : diff {: a b | c -- c :} heap> 1-array2 to c begin a each: while dup b indexOf: if 2drop else c add: then repeat a b free2 c dup sort: ;   i{ 2 5 4 3 } i{ 5 6 7 } diff p: i{ 2 3 4 } ok   : subset {: a b -- flag :} begin a each: while b indexOf: if drop else false exit then repeat a b free2 true ;   i{ 2 5 4 3 } i{ 5 6 7 } subset . 0 ok i{ 5 6 } i{ 5 6 7 } subset . -1 ok     : set= {: a b -- flag :} a size: b size: <> if a b free2 false exit then a sort: b sort: begin a each: drop b each: while <> if a b free2 false exit then repeat a b free2 true ;   i{ 5 6 } i{ 5 6 7 } set= . 0 ok i{ 6 5 7 } i{ 5 6 7 } set= . -1 ok  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Bracmat
Bracmat
( ( eratosthenes = n j i .  !arg:?n & 1:?i & whl ' ( (1+!i:?i)^2:~>!n:?j & ( !!i | whl ' ( !j:~>!n & nonprime:?!j & !j+!i:?j ) ) ) & 1:?i & whl ' ( 1+!i:~>!n:?i & (!!i|put$(!i " ")) ) ) & eratosthenes$100 )
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/*REXX program displays an ASCII table of characters (within a 16x16 indexed grid).*/ parse upper version !ver . /*some REXXes can't display '1b'x glyph*/ !pcRexx= 'REXX/PERSONAL'==!ver | "REXX/PC"==!ver /*is this PC/REXX or REXX/Personal? */ func= ' nul soh stx etx eot enq ack bel bs tab lf vt ff cr so si ' ||, " dle dc1 dc2 dc3 dc4 nak syn etb can em eof esc fs gs rs us " @.= @.1= "x'07' x'08' x'09' x'0a' x'0d' x'1a' x'1b' x'20'" @.2= "bel b/s tab l/f c/r eof esc bla" @.3= "bell backspace tabchar linefeed carriage end-of- escape blank" @.4= " return file" @.5= copies('≈', 79) do a=1 for 8; say @.a /*display header info (abbreviations).*/ end /*a*/ /*also included are three blank lines. */ b= ' '; hdr= left(b, 7) /*prepend blanks to HDR (indentation).*/ call xhdr /*construct a top index for the grid.*/ call grid '╔', "╤", '╗', "═══" /*construct & display bottom of a cell.*/ iidx= left(b, length(hdr) - 4 ) /*the length of the indentation of idx.*/ cant= copies('═', 3) /*can't show a character with this REXX*/ /* [↓] construct a sixteen-row grid. */ do j=0 by 16 for 16; idx= left(d2x(j),1,2) /*prepend an index literal for the grid*/ _= iidx idx b; _h= iidx " " /*an index and indent; without an index*/ sep= '║' /*assign a character to cell separator.*/ do #=j to j+15; chr= center( d2c(#), 3) /*true char glyph.*/ if #>6 & #<11 | #==13 then chr= cant /*can't show these glyphs.*/ /*esc*/ if #==27 then if !pcRexx then chr= cant /* " " this glyph. */ else chr= center( d2c(#), 3) /*true char glyph.*/ if # <32 then _h= _h || sep || right(word(func, #+1), 3) /*show a function.*/ if #==32 then chr= 'bla' /*spell out (within 3 chars) a "BLAnk".*/ if # >31 then _h= /*Above a blank? Then nullify 3rd line*/ _= _ || sep || chr; sep= '│' /*append grid cell; use a new sep char.*/ end /*#*/ if _h\=='' then say _h"║ " /*append the last grid cell character.*/ say _'║ ' idx /*append an index to the grid line.*/ if j\==240 then call grid '╟',"┼",'╢',"───" /*construct & display most cell bottoms*/ end /*j*/   call grid '╚', "╧", '╝', "═══" /*construct & display last cell bottom.*/ call xhdr /*construct a bottom index for the grid*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ xhdr: say; _= hdr; sep= b; do k=0 for 16; _=_||b d2x(k)b; end; say _; say; return grid: arg $1,$2,$3,$4; _=hdr; do 16; _=_ || $1 || $4; $1= $2; end; say _ || $3; return
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#VBA
VBA
Sub sierpinski(n As Integer) Dim lim As Integer: lim = 2 ^ n - 1 For y = lim To 0 Step -1 Debug.Print String$(y, " ") For x = 0 To lim - y Debug.Print IIf(x And y, " ", "# "); Next Debug.Print Next y End Sub Public Sub main() Dim i As Integer For i = 1 To 5 sierpinski i Next i End Sub
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Raku
Raku
sub carpet { (['#'], -> @c { [ |@c.map({$_ x 3}), |@c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}), |@c.map({$_ x 3}) ] } ... *).map: { .join("\n") }; }   say carpet[3];   # Same as above, structured as an array bound to a sequence, with a separate sub for clarity. sub weave ( @c ) { [ |@c.map({ $_ x 3 }), |@c.map({ $_ ~ .trans( '#' => ' ' ) ~ $_ }), |@c.map({ $_ x 3 }) ] }   my @carpet = ( ['#'], &weave ... * ).map: { .join: "\n" };   say @carpet[3];   # Output of both versions matches task example.
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Icon_and_Unicon
Icon and Unicon
procedure main(a) words := set() found := 0 every word := map(!&input) do { if member(words, reverse(word)) then { if (found +:= 1) <= 5 then write("\t",reverse(word),"/",word) } else insert(words, word) } write("\nFound ",found," semordnilap words") end  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#J
J
isSemordnilap=: |.&.> (~: *. e.) ] unixdict=: <;._2 freads 'unixdict.txt' #semordnilaps=: ~. /:~"1 (,. |.&.>) (#~ isSemordnilap) unixdict 158
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT   system=SYSTEM ()   IF (system=="WIN") THEN SET to="[email protected]" SET cc="[email protected]" subject="test" text=* DATA how are you?   status = SEND_MAIL (to,cc,subject,text,-)   ENDIF  
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#TXR
TXR
#!/usr/bin/txr @(next :args) @(cases) @TO @SUBJ @ (maybe) @CC @ (or) @ (bind CC "") @ (end) @(or) @ (throw error "must specify at least To and Subject") @(end) @(next *stdin*) @(collect) @BODY @(end) @(output (open-command `mail -s "@SUBJ" -a CC: "@CC" "@TO"` "w")) @(repeat) @BODY @(end) . @(end)
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#VBA
VBA
Option Explicit Const olMailItem = 0   Sub SendMail(MsgTo As String, MsgTitle As String, MsgBody As String) Dim OutlookApp As Object, Msg As Object Set OutlookApp = CreateObject("Outlook.Application") Set Msg = OutlookApp.CreateItem(olMailItem) With Msg .To = MsgTo .Subject = MsgTitle .Body = MsgBody .Send End With Set OutlookApp = Nothing End Sub   Sub Test() SendMail "somebody@somewhere", "Title", "Hello" End Sub
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
semiPrimeQ[n_Integer] := Module[{factors, numfactors}, factors = FactorInteger[n] // Transpose; numfactors = factors[[2]] // Total  ; numfactors == 2 ]
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#MiniScript
MiniScript
isSemiprime = function(num) divisor = 2 primes = 0 while primes < 3 and num != 1 if num % divisor == 0 then num = num / divisor; primes = primes + 1 else divisor = divisor + 1 end if end while return primes == 2 end function   print "Semiprimes up to 100:" results = [] for i in range(2, 100) if isSemiprime(i) then results.push i end for print results
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Delphi
Delphi
program Sedol;   {$APPTYPE CONSOLE}   uses SysUtils;     const SEDOL_CHR_COUNT = 6; DIGITS = ['0'..'9']; LETTERS = ['A'..'Z']; VOWELS = ['A', 'E', 'I', 'O', 'U']; ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); LETTER_OFFSET = 9;     function AddSedolCheckDigit(Sedol : string) : string; var iChr : integer; Checksum : integer; CheckDigit : char; begin if Sedol <> uppercase(Sedol) then raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); if length(Sedol) <> SEDOL_CHR_COUNT then raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]);   Checksum := 0; for iChr := 1 to SEDOL_CHR_COUNT do begin   if Sedol[iChr] in Vowels then raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); if not (Sedol[iChr] in ACCEPTABLE_CHRS) then raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]);   if Sedol[iChr] in DIGITS then Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] else Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr];   end;   Checksum := (Checksum mod 10); if Checksum <> 0 then Checksum := 10 - Checksum; CheckDigit := chr(CheckSum + ord('0'));   Result := Sedol + CheckDigit; end;     procedure Test(First6 : string); begin writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); end;     begin try Test('710889'); Test('B0YBKJ'); Test('406566'); Test('B0YBLH'); Test('228276'); Test('B0YBKL'); Test('557910'); Test('B0YBKR'); Test('585284'); Test('B0YBKT'); Test('B00030'); except on E : Exception do writeln(E.Message); end; readln; end.  
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Lua
Lua
function Is_self_describing( n ) local s = tostring( n )   local t = {} for i = 0, 9 do t[i] = 0 end   for i = 1, s:len() do local idx = tonumber( s:sub(i,i) ) t[idx] = t[idx] + 1 end   for i = 1, s:len() do if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end end   return true end   for i = 1, 999999999 do print( Is_self_describing( i ) ) end
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Nim
Nim
import strformat   func isPrime(n: int): bool = if n < 2: return false if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 var d = 5 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 true   var count = 1 write(stdout, " 2") for i in countup(3, 1999, 2): if isPrime(i): inc count write(stdout, fmt"{i:5}") if count mod 15 == 0: write(stdout, "\n") echo()
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Oforth
Oforth
: primeSeq(n) n seq filter(#isPrime) ;
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Groovy
Groovy
def nonSquare = { long n -> n + ((1/2 + n**0.5) as long) }
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#FreeBASIC
FreeBASIC
function is_in( N as integer, S() as integer ) as boolean 'test if the value N is in the set S for i as integer = 0 to ubound(S) if N=S(i) then return true next i return false end function   sub add_to_set( N as integer, S() as integer ) 'adds the element N to the set S if is_in( N, S() ) then return dim as integer k = ubound(S) redim preserve S(0 to k+1) S(k+1)=N end sub   sub setunion( S() as integer, T() as integer, U() as integer ) 'makes U() the union of the sets S and T dim as integer k = ubound(S) redim U(-1) for i as integer = 0 to k add_to_set( S(i), U() ) next i k = ubound(T) for i as integer = 0 to k if not is_in( T(i), U() ) then add_to_set( T(i), U() ) end if next i end sub   sub setintersect( S() as integer, T() as integer, U() as integer ) 'makes U() the intersection of the sets S and T dim as integer k = ubound(S) redim U(-1) for i as integer = 0 to k if is_in(S(i), T()) then add_to_set( S(i), U() ) next i end sub   sub setsubtract( S() as integer, T() as integer, U() as integer ) 'makes U() the difference of the sets S and T dim as integer k = ubound(S) redim U(-1) for i as integer = 0 to k if not is_in(S(i), T()) then add_to_set( S(i), U() ) next i end sub   function is_subset( S() as integer, T() as integer ) as boolean for i as integer = 0 to ubound(S) if not is_in( S(i), T() ) then return false next i return true end function   function is_equal( S() as integer, T() as integer ) as boolean if not is_subset( S(), T() ) then return false if not is_subset( T(), S() ) then return false return true end function   function is_proper_subset( S() as integer, T() as integer ) as boolean if not is_subset( S(), T() ) then return false if is_equal( S(), T() ) then return false return true end function   sub show_set( L() as integer ) 'display a set dim as integer num = ubound(L) if num=-1 then print "[]" return end if print "["; for i as integer = 0 to num-1 print str(L(i))+", "; next i print str(L(num))+"]" end sub   'sets are created by making an empty array redim as integer S1(-1), S2(-1), S3(-1), S4(-1), S5(-1) 'and populated by adding elements one-by-one add_to_set( 20, S1() )  : add_to_set( 30, S1() ) add_to_set( 40, S1() )  : add_to_set( 50, S1() ) add_to_set( 19, S2() )  : add_to_set( 20, S2() ) add_to_set( 21, S2() )  : add_to_set( 22, S2() ) add_to_set( 22, S3() )  : add_to_set( 21, S3() ) add_to_set( 19, S3() )  : add_to_set( 20, S3() ) add_to_set( 21, S3() ) ' attempt to add a number that's already in the set add_to_set( 21, S4() ) print "S1 ", show_set S1() print "S2 ", show_set S2() print "S3 ", show_set S3() print "S4 ", show_set S4() print "S5 ", show_set S5() print "----" redim as integer S_U(-1) setunion S1(), S2(), S_U() print "S1 U S2 ", show_set S_U() redim as integer S_U(-1) setintersect S1(), S2(), S_U() print "S1 n S2 ", show_set S_U() redim as integer S_U(-1) setsubtract S1(), S2(), S_U() print "S1 \ S2 ", show_set S_U() redim as integer S_U(-1) setsubtract S3(), S1(), S_U() print "S3 \ S1 ", show_set S_U() print "S4 in S3? ", is_subset(S4(), S3()) print "S3 in S4? ", is_subset(S3(), S4()) print "S5 in S3? ", is_subset(S5(), S3()) 'empty set is a subset of every set print "S2 = S3? ", is_equal(S2(), S3()) print "S4 proper subset of S3? ", is_proper_subset( S4(), S3() ) print "S2 proper subset of S3? ", is_proper_subset( S2(), S3() )
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#C
C
#include <stdlib.h> #include <math.h>   char* eratosthenes(int n, int *c) { char* sieve; int i, j, m;   if(n < 2) return NULL;   *c = n-1; /* primes count */ m = (int) sqrt((double) n);   /* calloc initializes to zero */ sieve = calloc(n+1,sizeof(char)); sieve[0] = 1; sieve[1] = 1; for(i = 2; i <= m; i++) if(!sieve[i]) for (j = i*i; j <= n; j += i) if(!sieve[j]){ sieve[j] = 1; --(*c); } return sieve; }
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ring
Ring
  # Project : Show Ascii table   load "guilib.ring" load "stdlib.ring"   decarr = newlist(16,6) ascarr = newlist(16,6)   new qapp { win1 = new qwidget() { setwindowtitle("Show Ascii table") setgeometry(100,100,800,600) for n = 1 to 16 for m = 1 to 6 decarr[n][m] = new qpushbutton(win1) { x = 150+m*60 y = 30 + n*30 ind = string((m-1)*16+n+31) setgeometry(x,y,30,30) settext(ind) } next next for n = 1 to 16 for m = 1 to 6 ascarr[n][m] = new qpushbutton(win1) { x = 180+m*60 y = 30 + n*30 ind = (m-1)*16+n+31 setgeometry(x,y,30,30) if ind = 32 settext("Spc") loop ok if ind = 127 settext("Del") loop ok settext(char(ind)) } next next show() } exec() }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#VBScript
VBScript
  Sub triangle(o) n = 2 ^ o Dim line() ReDim line(2*n) line(n) = "*" i = 0 Do While i < n WScript.StdOut.WriteLine Join(line,"") u = "*" j = n - i Do While j < (n+i+1) If line(j-1) = line(j+1) Then t = " " Else t = "*" End If line(j-1) = u u = t j = j + 1 Loop line(n+i) = t line(n+i+1) = "*" i = i + 1 Loop End Sub   triangle(4)  
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Relation
Relation
  function incarpet(x,y) set a = x set b = y while floor(a)>0 and floor(b)>0 if floor(a mod 3) = 1 and floor(b mod 3) = 1 set a = -1 set b = -1 else set a = a / 3 set b = b / 3 end if end while if a < 0 set result = "_" else set result = "#" end if end function   program carpet(n) set d = pow(3,n) set y = 0 while y < d set x = 0 set result = " " while x < d set result = result . incarpet(x,y) set x = x + 1 end while echo result set y = y + 1 end while end program   run carpet(3)  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Java
Java
import java.nio.file.*; import java.util.*;   public class Semordnilap {   public static void main(String[] args) throws Exception { List<String> lst = Files.readAllLines(Paths.get("unixdict.txt")); Set<String> seen = new HashSet<>(); int count = 0; for (String w : lst) { w = w.toLowerCase(); String r = new StringBuilder(w).reverse().toString(); if (seen.contains(r)) { if (count++ < 5) System.out.printf("%-10s %-10s\n", w, r); } else seen.add(w); } System.out.println("\nSemordnilap pairs found: " + count); } }
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#VBScript
VBScript
  Function send_mail(from,recipient,cc,subject,message) With CreateObject("CDO.Message") .From = from .To = recipient .CC = cc .Subject = subject .Textbody = message .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ "mystmpserver" .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 .Configuration.Fields.Update .Send End With End Function   Call send_mail("[email protected]","[email protected]","","Test Email","this is a test message")  
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation. Note how portable the solution given is between operating systems when multi-OS languages are used. (Remember to obfuscate any sensitive data used in examples)
#Wren
Wren
/* send_email.wren */   foreign class Authority { construct plainAuth(identity, username, password, host) {} }   class SMTP { foreign static sendMail(address, auth, from, to, msg) }   class Message { static check(host, user, pass) { if (host == "") Fiber.abort("Bad host") if (user == "") Fiber.abort("Bad username") if (pass == "") Fiber.abort("Bad password") }   construct new(from, to, cc, subject, content) { _from = from _to = to _cc = cc _subject = subject _content = content }   toString { var to = _to.join(",") var cc = _cc.join(",") var s1 = "From: " + _from + "\n" var s2 = "To: " + to + "\n" var s3 = "Cc: " + cc + "\n" var s4 = "Subject: " + _subject + "\n\n" return s1 + s2 + s3 + s4 + _content }   send(host, port, user, pass) { Message.check(host, user, pass) SMTP.sendMail( "%(host):%(port)", Authority.plainAuth("", user, pass, host), _from, _to, toString ) } }   foreign class Reader { construct new() {}   foreign readString(delim) }   var host = "smtp.gmail.com" var port = 587 var user = "[email protected]" var pass = "secret"   var bufin = Reader.new() var NL = 10   System.write("From: ") var from = bufin.readString(NL).trim()   var to = [] while (true) { System.write("To (Blank to finish): ") var tmp = bufin.readString(NL).trim() if (tmp == "") break to.add(tmp) }   var cc = [] while (true) { System.write("Cc (Blank to finish): ") var tmp = bufin.readString(NL).trim() if (tmp == "") break cc.add(tmp) }   System.write("Subject: ") var subject = bufin.readString(NL).trim()   var contentLines = [] while (true) { System.write("Content line (Blank to finish): ") var line = bufin.readString(NL).trim() if (line == "") break contentLines.add(line) } var content = contentLines.join("\r\n")   var m = Message.new(from, to, cc, subject, content) System.print("\nSending message...") m.send(host, port, user, pass) System.print("Message sent.")
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#NewLisp
NewLisp
  ;;; Practically identical to the EchoLisp solution (define (semiprime? n) (= (length (factor n)) 2)) ; ;;; Example (sadly factor doesn't accept bigints) (println (filter semiprime? (sequence 2 100))) (setq x 9223372036854775807) (while (not (semiprime? x)) (-- x)) (println "Biggest semiprime reachable: " x " = " ((factor x) 0) " x " ((factor x) 1))  
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Nim
Nim
proc isSemiPrime(k: int): bool = var i = 2 count = 0 x = k while i <= x and count < 3: if x mod i == 0: x = x div i inc count else: inc i result = count == 2   for k in 1675..1680: echo k, (if k.isSemiPrime(): " is" else: " isn’t"), " semi-prime"
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#E
E
def weights := [1,3,1,7,3,9] def Digit := ('0'..'9') def Letter := ('B'..'D'|'F'..'H'|'J'..'N'|'P'..'T'|'V'..'Z') def sedolCharValue(c) { switch (c) { match digit :Digit { return digit - '0' } match letter :Letter { return letter - 'A' } } }   def checksum(sedol :String) { require(sedol.size() == 6) var sum := 0 for i => c in sedol { sum += weights[i] * sedolCharValue(c) } return E.toString((10 - sum %% 10) %% 10) }   def addChecksum(sedol :String) { return sedol + checksum(sedol) }   for sedol in "710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT".trim().split("\n") { println(addChecksum(sedol.trim())) }
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
isSelfDescribing[n_Integer] := (RotateRight[DigitCount[n]] == PadRight[IntegerDigits[n], 10])
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#MATLAB_.2F_Octave
MATLAB / Octave
function z = isSelfDescribing(n) s = int2str(n)-'0'; % convert to vector of digits y = hist(s,0:9); z = all(y(1:length(s))==s); end;
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#PARI.2FGP
PARI/GP
trial(n)={ if(n < 4, return(n > 1)); /* Handle negatives */ forprime(p=2,sqrt(n), if(n%p == 0, return(0)) ); 1 };   select(trial, [1..100])
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Pascal
Pascal
  program PrimeRng; uses primTrial; var Range : ptPrimeList; i : integer; Begin Range := PrimeRange(1000*1000*1000,1000*1000*1000+100); For i := Low(Range) to High(Range) do write(Range[i]:12); writeln; end.
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Haskell
Haskell
nonsqr :: Integral a => a -> a nonsqr n = n + round (sqrt (fromIntegral n))
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#HicEst
HicEst
REAL :: n=22, nonSqr(n)   nonSqr = $ + FLOOR(0.5 + $^0.5) WRITE() nonSqr   squares_found = 0 DO i = 1, 1E6 non2 = i + FLOOR(0.5 + i^0.5) root = FLOOR( non2^0.5 ) squares_found = squares_found + (non2 == root*root) ENDDO WRITE(Name) squares_found END
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Frink
Frink
  a = new set[1, 2] b = toSet[[2,3]] // Construct a set from an array   a.contains[2] // Element test (returns true) union[a,b] intersection[a,b] setDifference[a,b] isSubset[a,b] // Returns true if a is a subset of b a==b // set equality test  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#C.23
C#
using System; using System.Collections; using System.Collections.Generic;   namespace SieveOfEratosthenes { class Program { static void Main(string[] args) { int maxprime = int.Parse(args[0]); var primelist = GetAllPrimesLessThan(maxprime); foreach (int prime in primelist) { Console.WriteLine(prime); } Console.WriteLine("Count = " + primelist.Count); Console.ReadLine(); }   private static List<int> GetAllPrimesLessThan(int maxPrime) { var primes = new List<int>(); var maxSquareRoot = (int)Math.Sqrt(maxPrime); var eliminated = new BitArray(maxPrime + 1);   for (int i = 2; i <= maxPrime; ++i) { if (!eliminated[i]) { primes.Add(i); if (i <= maxSquareRoot) { for (int j = i * i; j <= maxPrime; j += i) { eliminated[j] = true; } } } } return primes; } } }
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ruby
Ruby
chars = (32..127).map do |ord| k = case ord when 32 then "␠" when 127 then "␡" else ord.chr end "#{ord.to_s.ljust(3)}: #{k}" end   chars.each_slice(chars.size/6).to_a.transpose.each{|s| puts s.join(" ")}
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Vedit_macro_language
Vedit macro language
#3 = 16 // size (height) of the triangle Buf_Switch(Buf_Free) // Open a new buffer for output Ins_Char(' ', COUNT, #3*2+2) // fill first line with spaces Ins_Newline Line(-1) Goto_Col(#3) Ins_Char('*', OVERWRITE) // the top of triangle for (#10=0; #10 < #3-1; #10++) { BOL Reg_Copy(9,1) Reg_Ins(9) // duplicate the line #20 = '*' for (#11 = #3-#10; #11 < #3+#10+1; #11++) { Goto_Col(#11-1) if (Cur_Char==Cur_Char(2)) { #21=' ' } else { #21='*' } Ins_Char(#20, OVERWRITE) #20 = #21 } Ins_Char(#21, OVERWRITE) Ins_Char('*', OVERWRITE) }
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#REXX
REXX
/*REXX program draws any order Sierpinski carpet (order 20 would be ≈ 3.4Gx3.4G carpet).*/ parse arg N char . /*get the order of the carpet. */ if N=='' | N=="," then N= 3 /*if none specified, then assume 3. */ if char=='' then char= "*" /*use the default of an asterisk (*). */ if length(char)==2 then char= x2c(char) /*it was specified in hexadecimal char.*/ if length(char)==3 then char= d2c(char) /* " " " " decimal character*/ width= linesize() /*the width of the terminal screen. */ if N>18 then numeric digits 100 /*just in case the user went ka─razy. */ nnn= 3**N /* [↓] NNN is the cube of N. */   do j=0 for nnn; z= /*Z: will be the line to be displayed.*/ do k=0 for nnn; jj= j; kk= k; x= char do while jj\==0 & kk\==0 /*one symbol for a not (¬) is a \ */ if jj//3==1 then if kk//3==1 then do /*in REXX: // ≡ division remainder*/ x= ' ' /*use a blank for this display line. */ leave /*LEAVE terminates this DO WHILE. */ end jj= jj % 3; kk= kk % 3 /*in REXX:  % ≡ integer division. */ end /*while*/   z= z || x /*X is either black or white. */ end /*k*/ /* [↑] " " " " blank. */   if length(z)<width then say z /*display the line if it fits on screen*/ call lineout 'Sierpinski.'N, z /*also, write the line to a (disk) file*/ end /*j*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#JavaScript
JavaScript
#!/usr/bin/env node var fs = require('fs'); var sys = require('sys');   var dictFile = process.argv[2] || "unixdict.txt";   var dict = {}; fs.readFileSync(dictFile) .toString() .split('\n') .forEach(function(word) { dict[word] = word.split("").reverse().join(""); });   function isSemordnilap(word) { return dict[dict[word]]; };   var semordnilaps = [] for (var key in dict) { if (isSemordnilap(key)) { var rev = dict[key]; if (key < rev) { semordnilaps.push([key,rev]) ; } } }   var count = semordnilaps.length; sys.puts("There are " + count + " semordnilaps in " + dictFile + ". Here are 5:" );   var indices=[] for (var i=0; i<count; ++i) { if (Math.random() < 1/Math.ceil(i/5.0)) { indices[i%5] = i } } indices.sort() for (var i=0; i<5; ++i) { sys.puts(semordnilaps[indices[i]]); }
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Objeck
Objeck
  class SemiPrime { function : Main(args : String[]) ~ Nil { for(i := 0; i < 100; i+=1;) { if(SemiPrime(i)) { "{$i} "->Print(); }; }; IO.Console->PrintLine(); }   function : native : SemiPrime(n : Int) ~ Bool { nf := 0; for(i := 2; i <= n; i+=1;) { while(n%i = 0) { if(nf = 2) { return false; }; nf+=1; n /= i; }; };   return nf = 2; } }
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Elixir
Elixir
defmodule SEDOL do @sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints @sedolweight [1,3,1,7,3,9]   defp char2value(c) do unless c in @sedol_char, do: raise ArgumentError, "No vowels" String.to_integer(c,36) end   def checksum(sedol) do if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length" sum = Enum.zip(String.codepoints(sedol), @sedolweight) |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end) |> Enum.sum to_string(rem(10 - rem(sum, 10), 10)) end end   data = ~w{ 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A }   Enum.each(data, fn sedol ->  :io.fwrite "~-8s ", [sedol] try do IO.puts sedol <> SEDOL.checksum(sedol) rescue e in ArgumentError -> IO.inspect e end end)
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#MiniScript
MiniScript
numbers = [12, 1210, 1300, 2020, 21200, 5]   occurrences = function(test, values) count = 0 for i in values if i.val == test then count = count + 1 end for return count end function   for number in numbers check = "" + number digits = check.values describing = true for digit in digits.indexes if digits[digit].val != occurrences(digit, digits) then describing = false end if end for if describing then print number + " is self describing" else print number + " is not self describing" end if end for  
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Modula-2
Modula-2
  MODULE SelfDescribingNumber;   FROM WholeStr IMPORT CardToStr; FROM STextIO IMPORT WriteString, WriteLn; FROM SWholeIO IMPORT WriteCard;   PROCEDURE Check(Number: CARDINAL): BOOLEAN; VAR I, D: CARDINAL; A: ARRAY [0 .. 9] OF CHAR; Count, W: ARRAY [0 .. 9] OF CARDINAL; Result: BOOLEAN; BEGIN CardToStr(Number, A); FOR I := 0 TO 9 DO Count[I] := 0; W[I] := 0; END; FOR I := 0 TO LENGTH(A) - 1 DO D := ORD(A[I]) - ORD("0"); INC(Count[D]); W[I] := D; END; Result := TRUE; I := 0; WHILE Result AND (I <= 9) DO Result := (Count[I] = W[I]); INC(I); END; RETURN Result; END Check;   VAR X: CARDINAL;   BEGIN WriteString("Autodescriptive numbers from 1 to 100000000:"); WriteLn; FOR X := 1 TO 100000000 DO IF Check(X) THEN WriteString(" "); WriteCard(X, 1); WriteLn; END; END; WriteString("Job done."); WriteLn; END SelfDescribingNumber.  
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Perl
Perl
sub isprime { my $n = shift; return ($n >= 2) if $n < 4; return unless $n % 2 && $n % 3; my $sqrtn = int(sqrt($n)); for (my $i = 5; $i <= $sqrtn; $i += 6) { return unless $n % $i && $n % ($i+2); } 1; }   print join(" ", grep { isprime($_) } 0 .. 100 ), "\n"; print join(" ", grep { isprime($_) } 12345678 .. 12345678+100 ), "\n";
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Icon_and_Unicon
Icon and Unicon
link numbers   procedure main()   every n := 1 to 22 do write("nsq(",n,") := ",nsq(n))   every x := sqrt(nsq(n := 1 to 1000000)) do if x = floor(x)^2 then write("nsq(",n,") = ",x," is a square.") write("finished.") end   procedure nsq(n) # return non-squares return n + floor(0.5 + sqrt(n)) end
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#FunL
FunL
A = {1, 2, 3} B = {3, 4, 5} C = {1, 2, 3, 4, 5} D = {2, 1, 3}   println( '2 is in A: ' + (2 in A) ) println( '4 is in A: ' + (4 in A) ) println( 'A union B: ' + A.union(B) ) println( 'A intersect B: ' + A.intersect(B) ) println( 'A difference B: ' + A.diff(B) ) println( 'A subset of B: ' + A.subsetOf(B) ) println( 'A subset of B: ' + A.subsetOf(C) ) println( 'A equal B: ' + (A == B) ) println( 'A equal D: ' + (A == D) )   S = set( A )   println( 'S (mutable version of A): ' + S ) S.add( 4 ) println( 'S with 4 added: ' + S ) println( 'S subset of C: ' + S.subsetOf(C) ) S.remove( 1 ) println( 'S after 1 removed: ' + S )
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include <vector>   // requires Iterator satisfies RandomAccessIterator template <typename Iterator> size_t prime_sieve(Iterator start, Iterator end) { if (start == end) return 0; // clear the container with 0 std::fill(start, end, 0); // mark composites with 1 for (Iterator prime_it = start + 1; prime_it != end; ++prime_it) { if (*prime_it == 1) continue; // determine the prime number represented by this iterator location size_t stride = (prime_it - start) + 1; // mark all multiples of this prime number up to max Iterator mark_it = prime_it; while ((end - mark_it) > stride) { std::advance(mark_it, stride); *mark_it = 1; } } // copy marked primes into container Iterator out_it = start; for (Iterator it = start + 1; it != end; ++it) { if (*it == 0) { *out_it = (it - start) + 1; ++out_it; } } return out_it - start; }   int main(int argc, const char* argv[]) { std::vector<int> primes(100); size_t count = prime_sieve(primes.begin(), primes.end()); // display the primes for (size_t i = 0; i < count; ++i) std::cout << primes[i] << " "; std::cout << std::endl; return 1; }
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rust
Rust
fn main() { for i in 0u8..16 { for j in ((32+i)..128).step_by(16) { let k = (j as char).to_string(); print!("{:3} : {:<3} ", j, match j { 32 => "Spc", 127 => "Del", _ => &k, }); } println!(); } }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Wren
Wren
var size = 1 << 4 for (y in size-1..0) { System.write(" " * y) for (x in 0...size-y) System.write((x&y != 0) ? " " : "* ") System.print() }
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Ring
Ring
  load "guilib.ring"   new qapp { win1 = new qwidget() { etwindowtitle("drawing using qpainter") setgeometry(100,100,500,500) label1 = new qlabel(win1) { setgeometry(10,10,400,400) settext("") } new qpushbutton(win1) { setgeometry(200,450,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } new qpainter() { begin(p1) setpen(pen)   order = 3 side = pow(3,order) for y = 0 to side-1 for x = 0 to side-1 if carpet(self,x,y) drawpoint(x*16,y*16+15) drawpoint(x*16+1,y*16+16) drawpoint(x*16+2,y*16+17) ok next next   endpaint() } label1 { setpicture(p1) show() }   func carpet myObj,x,y myObj{while x!=0 and y!=0 if x % 3 = 1 if y % 3 = 1 return false ok ok x = floor(x/3) y = floor(y/3) end return true}  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#jq
jq
  # Produce a stream def report: split("\n") as $list # construct the dictionary: | (reduce $list[] as $entry ({}; . + {($entry): 1})) as $dict # construct the list of semordnilaps: | $list[] | select( (explode|reverse|implode) as $rev | (. < $rev and $dict[$rev]) );   [report] | (.[0:5][], "length = \(length)")
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
raw = readdlm("unixdict.txt",String)[:] inter = intersect(raw,map(reverse,raw)) #find the matching strings/revstrings res = String[b == 1 && a != reverse(a) && a < reverse(a) ? a : reverse(a) for a in inter, b in 1:2] #create pairs res = res[res[:,1] .!= res[:,2],:] #get rid of duplicates, palindromes
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Oforth
Oforth
func: semiprime(n) | i | 0 2 n sqrt asInteger for: i [ while(n i /mod swap 0 &=) [ ->n 1+ ] drop ] n 1 > ifTrue: [ 1+ ] 2 == ;
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#PARI.2FGP
PARI/GP
issemi(n)=bigomega(n)==2
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Excel
Excel
SEDOLCHECKSUM =LAMBDA(s, IF(6 = LEN(s), LET( cs, MID(s, SEQUENCE(1, 6, 1, 1), 1), isVowel, LAMBDA(c, ELEM(c)({"A","E","I","O","U"}) ), sedolValue, LAMBDA(c, LET( ic, CODE(c), IF(65 > ic, ic - 48, (ic + 10) - 65 ) ) ), IF(OR(isVowel(cs)), " -> Invalid vowel in SEDOL string", MOD( 10 - MOD( SUM( MUL({1,3,1,7,3,9})( sedolValue(cs) ) ), 10 ), 10 ) ) ), "Expected a 6-character SEDOL" ) )
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Nim
Nim
import algorithm, sequtils, std/monotimes, times   type Digit = 0..9   var digits = newSeqOfCap[Digit](10)   proc getDigits(n: Positive) = digits.setLen(0) var n = n.int while n != 0: digits.add n mod 10 n = n div 10 digits.reverse()   proc isSelfDescribing(n: Natural): bool = n.getDigits() for i, d in digits: if digits.count(i) != d: return false result = true   let t0 = getMonoTime() for n in 1 .. 1_000_000_000: if n.isSelfDescribing: echo n, " in ", getMonoTime() - t0   echo "\nTotal time: ", getMonoTime() - t0
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#ooRexx
ooRexx
  -- REXX program to check if a number (base 10) is self-describing. parse arg x y . if x=='' then exit if y=='' then y=x -- 10 digits is the maximum size number that works here, so cap it numeric digits 10 y=min(y, 9999999999)   loop number = x to y loop i = 1 to number~length digit = number~subchar(i) -- return on first failure if digit \= number~countstr(i - 1) then iterate number end say number "is a self describing number" end  
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#Phix
Phix
function is_prime_by_trial_division(integer n) if n<2 then return 0 end if if n=2 then return 1 end if if remainder(n,2)=0 then return 0 end if for i=3 to floor(sqrt(n)) by 2 do if remainder(n,i)=0 then return 0 end if end for return 1 end function ?filter(tagset(32),is_prime_by_trial_division)
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#PicoLisp
PicoLisp
(de prime? (N) (or (= N 2) (and (> N 1) (bit? 1 N) (let S (sqrt N) (for (D 3 T (+ D 2)) (T (> D S) T) (T (=0 (% N D)) NIL) ) ) ) ) )   (de primeseq (A B) (filter prime? (range A B)) )   (println (primeseq 50 99))
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#IDL
IDL
n = lindgen(1000000)+1 ; Take a million numbers f = n+floor(.5+sqrt(n)) ; Apply formula print,f[0:21] ; Output first 22 print,where(sqrt(f) eq fix(sqrt(f))) ; Test for squares
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#J
J
rf=: + 0.5 <.@+ %: NB. Remarkable formula   rf 1+i.22 NB. Results from 1 to 22 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27   +/ (rf e. *:) 1+i.1e6 NB. Number of square RFs <= 1e6 0
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#FutureBasic
FutureBasic
include "NSLog.incl"   local fn DoIt // create CFSetRef s1 = fn SetWithArray( @[@"a",@"b",@"c",@"d",@"e"] ) CFSetRef s2 = fn SetWithArray( @[@"b",@"c",@"d",@"e",@"f",@"h"] ) CFSetRef s3 = fn SetWithArray( @[@"b",@"c",@"d"] ) CFSetRef s4 = fn SetWithArray( @[@"b",@"c",@"d"] ) NSLog(@"s1: %@",s1) NSLog(@"s2: %@",s2) NSLog(@"s3: %@",s3) NSLog(@"s4: %@\n",s4)   // membership NSLog(@"\"b\" in s1: %d", fn SetContainsObject( s1, @"b" )) NSLog(@"\"f\" in s1: %d\n", fn SetContainsObject( s1, @"f" ))   // union CFMutableSetRef s12 = fn MutableSetWithSet( s1 ) MutableSetUnionSet( s12, s2 ) NSLog(@"s1 union s2: %@\n", s12)   // intersection CFMutableSetRef s1i2 = fn MutableSetWithSet( s1 ) MutableSetIntersectSet( s1i2, s2 ) NSLog(@"s1 intersect s2: %@\n", s1i2)   // difference CFMutableSetRef s1d2 = fn MutableSetWithSet( s1 ) MutableSetMinusSet( s1d2, s2 ) NSLog(@"s1 - s2: %@\n", s1d2)   // subsetof NSLog(@"s3 subset of s1: %d\n", fn SetIsSubsetOfSet( s3, s1 ))   // equality NSLog(@"s3 == s4: %d\n", fn SetIsEqual( s3, s4 ))   // cardinality NSLog(@"size of s1: %lu\n", fn SetCount(s1))   // has intersection (not disjoint) NSLog(@"s1 intersects s2: %d\n", fn SetIntersectsSet( s1, s2 ))   // adding and removing elements from mutable set CFMutableSetRef s1mut = fn MutableSetWithSet( s1 ) MutableSetAddObject( s1mut, @"g" ) NSLog(@"s1mut after adding \"g\": %@\n", s1mut) MutableSetAddObject( s1mut, @"b" ) NSLog(@"s1mut after adding \"b\" again: %@\n", s1mut) MutableSetRemoveObject( s1mut, @"c" ) NSLog(@"s1mut after removing \"c\": %@\n", s1mut) end fn   fn DoIt   HandleEvents
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Chapel
Chapel
// yield prime and remove all multiples of it from children sieves iter sieve(prime):int {   yield prime;   var last = prime; label candidates for candidate in sieve(prime+1) do { for composite in last..candidate by prime do {   // candidate is a multiple of this prime if composite == candidate { // remember size of last composite last = composite; // and try the next candidate continue candidates; } }   // candidate cannot need to be removed by this sieve // yield to parent sieve for checking yield candidate; } }
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Scala
Scala
object AsciiTable extends App { val (strtCharVal, lastCharVal, nColumns) = (' '.toByte, '\u007F'.toByte, 6) require(nColumns % 2 == 0, "Number of columns must be even.")   val nChars = lastCharVal - strtCharVal + 1 val step = nChars / nColumns val threshold = strtCharVal + (nColumns - 1) * step   def indexGen(start: Byte): LazyList[Byte] = start #:: indexGen( (if (start >= threshold) strtCharVal + start % threshold + 1 else start + step).toByte )   def k(j: Byte): Char = j match { case `strtCharVal` => '\u2420' case 0x7F => '\u2421' case _ => j.toChar }   indexGen(strtCharVal) .take(nChars) .sliding(nColumns, nColumns) .map(_.map(byte => f"$byte%3d : ${k(byte)}")) .foreach(line => println(line.mkString(" "))) }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#X86_Assembly
X86 Assembly
.model tiny .code .486 org 100h start: xor ebx, ebx ;S1:= 0 mov edx, 8000h ;S2:= $8000 mov cx, 16 ;for I:= Size downto 1 tri10: mov ebx, edx ; S1:= S2 tri15: test edx, edx ; while S2#0 je tri20 mov al, '*' ; ChOut test dl, 01h ; if S2&1 then '*' else ' ' jne tri18 mov al, ' ' tri18: int 29h shr edx, 1 ; S2>>1 jmp tri15 tri20: mov al, 0Dh ;new line int 29h mov al, 0Ah int 29h shl ebx, 1 ;S2:= S2 xor S1<<1 xor edx, ebx shr ebx, 2 ;S2:= S2 xor S1>>1 xor edx, ebx loop tri10 ;next I ret end start
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Ruby
Ruby
def sierpinski_carpet(n) carpet = ["#"] n.times do carpet = carpet.collect {|x| x + x + x} + carpet.collect {|x| x + x.tr("#"," ") + x} + carpet.collect {|x| x + x + x} end carpet end   4.times{|i| puts "\nN=#{i}", sierpinski_carpet(i)}
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Kotlin
Kotlin
// version 1.2.0   import java.io.File   fun main(args: Array<String>) { val words = File("unixdict.txt").readLines().toSet() val pairs = words.map { Pair(it, it.reversed()) } .filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches println("Found ${pairs.size} semordnilap pairs") println(pairs.take(5)) }
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Pascal
Pascal
program SemiPrime; {$IFDEF FPC} {$Mode objfpc}// compiler switch to use result {$ELSE} {$APPTYPE CONSOLE} // for Delphi {$ENDIF} uses primTrial;   function isSemiprime(n: longWord;doWrite:boolean): boolean; var fac1 : LongWord; begin //a simple isAlmostPrime(n,2) would do without output; fac1 := SmallFactor(n); IF fac1 < n then Begin n := n div fac1; result := SmallFactor(n) = n; if result AND doWrite then write(fac1:10,'*',n:11) end else result := false; end; var i,k : longWord; BEGIN For i := 2 to 97 do IF isSemiPrime(i,false) then write(i:3); writeln; //test for big numbers k := 4000*1000*1000; i := k-100; repeat IF isSemiPrime(i,true) then writeln(' = ',i:10); inc(i); until i> k; END.
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#F.23
F#
open System let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL" "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"]   let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U'] let Weights = [1; 3; 1; 7; 3; 9; 1]   let inline isVowel c = Vowels.Contains (Char.ToUpper c)   let char2value c = if Char.IsDigit c then int c - 0x30 else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10   let sedolCheckDigit (input: string) = if input.Length <> 6 || input |> Seq.exists isVowel then failwithf "Input must be six characters long and not contain vowels: %s" input   let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum (10 - sum%10)%10   let addCheckDigit inputs = inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString())   let processDigits() = try addCheckDigit Inputs |> List.iter (printfn "%s") with ex -> printfn "ERROR: %s" ex.Message
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#PARI.2FGP
PARI/GP
S=[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000]; isself(n)=vecsearch(S,n)
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Pascal
Pascal
Program SelfDescribingNumber;   uses SysUtils;   function check(number: longint): boolean; var i, d: integer; a: string; count, w : array [0..9] of integer;   begin a := intToStr(number); for i := 0 to 9 do begin count[i] := 0; w[i] := 0; end; for i := 1 to length(a) do begin d := ord(a[i]) - ord('0'); inc(count[d]); w[i - 1] := d; end; check := true; i := 0; while check and (i <= 9) do begin check := count[i] = w[i]; inc(i); end; end;   var x: longint;   begin writeln ('Autodescriptive numbers from 1 to 100000000:'); for x := 1 to 100000000 do if check(x) then writeln (' ', x); writeln('Job done.'); end.
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already). Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#PowerShell
PowerShell
  function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function sieve-start-end ($start,$end) { (eratosthenes $end) | where{$_ -ge $start}   } "$(sieve-start-end 100 200)"  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Java
Java
public class SeqNonSquares { public static int nonsqr(int n) { return n + (int)Math.round(Math.sqrt(n)); }   public static void main(String[] args) { // first 22 values (as a list) has no squares: for (int i = 1; i < 23; i++) System.out.print(nonsqr(i) + " "); System.out.println();   // The following check shows no squares up to one million: for (int i = 1; i < 1000000; i++) { double j = Math.sqrt(nonsqr(i)); assert j != Math.floor(j); } } }
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Go
Go
package main   import "fmt"   // Define set as a type to hold a set of complex numbers. A type // could be defined similarly to hold other types of elements. A common // variation is to make a map of interface{} to represent a set of // mixed types. Also here the map value is a bool. By always storing // true, the code is nicely readable. A variation to use less memory // is to make the map value an empty struct. The relative advantages // can be debated. type set map[complex128]bool   func main() { // task: set creation s0 := make(set) // create empty set s1 := set{3: true} // create set with one element s2 := set{3: true, 1: true} // create set with two elements   // option: another way to create a set s3 := newSet(3, 1, 4, 1, 5, 9)   // option: output! fmt.Println("s0:", s0) fmt.Println("s1:", s1) fmt.Println("s2:", s2) fmt.Println("s3:", s3)   // task: element predicate fmt.Printf("%v ∈ s0: %t\n", 3, s0.hasElement(3)) fmt.Printf("%v ∈ s3: %t\n", 3, s3.hasElement(3)) fmt.Printf("%v ∈ s3: %t\n", 2, s3.hasElement(2))   // task: union b := set{4: true, 2: true} fmt.Printf("s3 ∪ %v: %v\n", b, union(s3, b))   // task: intersection fmt.Printf("s3 ∩ %v: %v\n", b, intersection(s3, b))   // task: difference fmt.Printf("s3 \\ %v: %v\n", b, difference(s3, b))   // task: subset predicate fmt.Printf("%v ⊆ s3: %t\n", b, subset(b, s3)) fmt.Printf("%v ⊆ s3: %t\n", s2, subset(s2, s3)) fmt.Printf("%v ⊆ s3: %t\n", s0, subset(s0, s3))   // task: equality s2Same := set{1: true, 3: true} fmt.Printf("%v = s2: %t\n", s2Same, equal(s2Same, s2))   // option: proper subset fmt.Printf("%v ⊂ s2: %t\n", s2Same, properSubset(s2Same, s2)) fmt.Printf("%v ⊂ s3: %t\n", s2Same, properSubset(s2Same, s3))   // option: delete. it's built in. delete(s3, 3) fmt.Println("s3, 3 deleted:", s3) }   func newSet(ms ...complex128) set { s := make(set) for _, m := range ms { s[m] = true } return s }   func (s set) String() string { if len(s) == 0 { return "∅" } r := "{" for e := range s { r = fmt.Sprintf("%s%v, ", r, e) } return r[:len(r)-2] + "}" }   func (s set) hasElement(m complex128) bool { return s[m] }   func union(a, b set) set { s := make(set) for e := range a { s[e] = true } for e := range b { s[e] = true } return s }   func intersection(a, b set) set { s := make(set) for e := range a { if b[e] { s[e] = true } } return s }   func difference(a, b set) set { s := make(set) for e := range a { if !b[e] { s[e] = true } } return s }   func subset(a, b set) bool { for e := range a { if !b[e] { return false } } return true }   func equal(a, b set) bool { return len(a) == len(b) && subset(a, b) }   func properSubset(a, b set) bool { return len(a) < len(b) && subset(a, b) }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Clojure
Clojure
(defn primes< [n] (remove (set (mapcat #(range (* % %) n %) (range 2 (Math/sqrt n)))) (range 2 n)))
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: row is 0; var integer: column is 0; var integer: number is 0; begin for row range 0 to 15 do for column range 0 to 5 do number := 32 + 16 * column + row; write(number lpad 3 <& " : "); case number of when {32}: write("Spc "); when {127}: write("Del "); otherwise: write(chr(number) <& " "); end case; end for; writeln; end for; end func;
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#XPL0
XPL0
code ChOut=8, CrLf=9; def Order=4, Size=1<<Order; int S1, S2, I; [S1:= 0; S2:= $8000; for I:= 0 to Size-1 do [S1:= S2; while S2 do [ChOut(0, if S2&1 then ^* else ^ ); S2:= S2>>1]; CrLf(0); S2:= S2 xor S1<<1; S2:= S2 xor S1>>1; ]; ]
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Rust
Rust
fn main() { for i in 0..4 { println!("\nN={}", i); println!("{}", sierpinski_carpet(i)); } }   fn sierpinski_carpet(n: u32) -> String { let mut carpet = vec!["#".to_string()]; for _ in 0..n { let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect(); let middle: Vec<_> = carpet .iter() .map(|x| x.to_string() + &x.replace("#", " ") + x) .collect(); let bottom = top.clone();   top.extend(middle); top.extend(bottom); carpet = top; } carpet.join("\n") }    
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ksh
Ksh
  #!/bin/ksh   # Semordnilap   # # Variables: # integer MIN_WORD_LEN=1 TRUE=1 FALSE=0 dict='/home/ostrande/prj/roscode/unixdict.txt'   integer i j=0 k=0 typeset -A word   # # Functions: #   # # Function _flipit(string) - return flipped string # function _flipit { typeset _buf ; _buf="$1" typeset _tmp ; unset _tmp   for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do _tmp="${_tmp}${_buf:${_i}:1}" done   echo "${_tmp}" }   # # Function _isword(word, wordlist) - return 1 if word in wordlist # function _isword { typeset _word ; _word="$1" typeset _wordlist ; nameref _wordlist="$2"   [[ ${_word} == @(${_wordlist}) ]] && return $TRUE return $FALSE }   ###### # main # ###### # # Due to the large number of words in unixdist.txt subgroup by 1st letter and length # # only accept words containing alpha chars and > 1 chars # while read; do [[ $REPLY != *+(\W)* ]] && [[ $REPLY != *+(\d)* ]] && \ (( ${#REPLY} > MIN_WORD_LEN )) && word[${REPLY:0:1}][${#REPLY}]+=( $REPLY ) done < ${dict}   print Examples: for fl in ${!word[*]}; do # Over $fl first letter for len in ${!word[${fl}][*]}; do # Over $len word length for ((i=0; i<${#word[${fl}][${len}][*]}; i++)); do Word=${word[${fl}][${len}][i]} # dummy Try=$(_flipit ${Word}) if [[ ${Try} != ${Word} ]]; then # no palindromes unset words oldIFS="$IFS" ; IFS='|' ; words=${word[${Try:0:1}][${#Try}][*]} ; IFS="${oldIFS}" _isword "${Try}" words if (( $? )); then if [[ ${Try} != @(${uniq%\|*}) ]]; then ((++j)) (( ${#Word} >= 5 )) && (( k<=5 )) && print $((++k)). ${Word} ${Try} uniq+="${Try}|${Word}|" fi fi fi done done done echo ; print ${j} pairs found.
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Lasso
Lasso
local( words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'), semordnilaps = array, found_size, example, haveexamples = false, examples = array )   #words -> removeall('')   with word in #words do { local(reversed = string(#word) -> reverse&) if(not(#word == #reversed) and not(#semordnilaps >> #word) and not(#semordnilaps >> #reversed) and #words >> #reversed) => { #semordnilaps -> insert(#word = #reversed) } }   #found_size = #semordnilaps -> size   while(not(#haveexamples)) => { #example = #semordnilaps -> get(integer_random(#found_size, 1)) not(#examples >> #example -> name) ? #examples -> insert(#example) #examples -> size >= 5 ? #haveexamples = true } 'Total found: ' #found_size '<br />' #examples
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Perl
Perl
use ntheory "is_semiprime"; for ([1..100], [1675..1681], [2,4,99,100,1679,5030,32768,1234567,9876543,900660121]) { print join(" ",grep { is_semiprime($_) } @$_),"\n"; }
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecibo message). Task Write a function determining whether a given number is semiprime. See also The Wikipedia article:  semiprime. The Wikipedia article:  almost prime. The OEIS sequence:  A001358: semiprimes  which has a shorter definition: the product of two primes.
#Phix
Phix
function semiprime(integer n) return length(prime_factors(n,true))==2 end function pp(filter(tagset(100)&tagset(1680,1675),semiprime),{pp_IntCh,false})
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Factor
Factor
USING: combinators combinators.short-circuit formatting io kernel math math.parser regexp sequences unicode ; IN: rosetta-code.sedols   <PRIVATE   CONSTANT: input { "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA" "123" "" "B_7K90" }   CONSTANT: weights B{ 1 3 1 7 3 9 1 }   : sedol-error ( seq -- err-str ) { { [ dup empty? ] [ drop "no data" ] } { [ dup length 6 = not ] [ drop "invalid length" ] } [ drop "invalid char(s)" ] } cond "*error* " prepend ;   : sedol-valid? ( seq -- ? ) { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ;   : sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ;   : sedol-checksum ( seq -- n ) [ sedol-value ] { } map-as weights [ * ] 2map sum ;   : (sedol-check-digit) ( seq -- str ) sedol-checksum 10 mod 10 swap - 10 mod number>string ;   PRIVATE>   : sedol-check-digit ( seq -- str ) dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ;   : sedol-demo ( -- ) "SEDOL Check digit\n====== ===========" print input [ dup sedol-check-digit "%-6s  %s\n" printf ] each ;   MAIN: sedol-demo
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Perl
Perl
sub is_selfdesc { local $_ = shift; my @b = (0) x length; $b[$_]++ for my @a = split //; return "@a" eq "@b"; }   # check all numbers from 0 to 100k plus two 'big' ones for (0 .. 100000, 3211000, 42101000) { print "$_\n" if is_selfdesc($_); }
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example,   2020   is a four-digit self describing number:   position   0   has value   2   and there are two 0s in the number;   position   1   has value   0   and there are no 1s in the number;   position   2   has value   2   and there are two 2s;   position   3   has value   0   and there are zero 3s. Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000. Task Description Write a function/routine/method/... that will check whether a given positive integer is self-describing. As an optional stretch goal - generate and display the set of self-describing numbers. Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-referential sequence   Spelling of ordinal numbers
#Phix
Phix
with javascript_semantics function self_desc(integer i) sequence digits = repeat(0,10), counts = repeat(0,10) integer n = 0, digit while 1 do digit := mod(i,10) digits[10-n] := digit digit += 1 counts[digit] += 1 i = floor(i/10) if i=0 then exit end if n += 1 end while return digits[10-n..10] = counts[1..n+1] end function atom t0 = time() for i=10 to 100_000_000 by 10 do if self_desc(i) then ?i end if end for printf(1,"done (%s)\n",{elapsed(time()-t0)})