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/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... | #Prolog | Prolog |
wheel235(L) :-
W = [6, 4, 2, 4, 2, 4, 6, 2 | W],
lazy_list(accumulate, 1/W, L).
accumulate(M/[A|As], N/As, N) :- N is M + A.
roll235wheel(Limit, A) :-
wheel235(W),
append(A, [N|_], W),
N > Limit, !.
prime235(N) :- % N is prime excepting multiples of 2, 3, 5.
wheel235(W),
wheel_prime... |
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.
| #JavaScript | JavaScript | var a = [];
for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i));
console.log(a);
for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) {
console.log("The ",i,"th element of the sequence is a square");
} |
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.
| #jq | jq | def A000037: . + (0.5 + sqrt | floor);
def is_square: sqrt | . == floor;
"For n up to and including 22:",
(range(1;23) | A000037),
"Check for squares for n up to 1e6:",
(range(1;1e6+1) | A000037 | select( is_square )) |
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... | #Groovy | Groovy | def s1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set
def m1 = 6
def m2 = 7
def s2 = [0, 2, 4, 6, 8] as Set
assert m1 in s1 : 'member'
assert ! (m2 in s2) : 'not a member'
def su = s1 + s2
assert su == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set : 'union... |
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... | #CLU | CLU | % Sieve of Eratosthenes
eratosthenes = proc (n: int) returns (array[bool])
prime: array[bool] := array[bool]$fill(1, n, true)
prime[1] := false
for p: int in int$from_to(2, n/2) do
if prime[p] then
for c: int in int$from_to_by(p*p, n, p) do
prime[c] := false
... |
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
Bioin... | #Spin | Spin | con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial"
pub main | i, j
ser.start(31, 30, 0, 115200)
repeat i from 0 to 15
repeat j from i + 32 to 127 step 16
if j < 100
ser.tx(32)
ser.dec(j)
ser.str(string(": "))
case j
32:
... |
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
Bioin... | #Standard_ML | Standard ML | fun Table n 127 = " 127: 'DEL'\n"
| Table 0 x = "\n" ^ (Table 10 x)
| Table n x = (StringCvt.padLeft #" " 4 (Int.toString x)) ^ ": '" ^ (str (chr x)) ^ "' " ^ ( Table (n-1) (x+1)) ;
print (Table 10 32) ; |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Yabasic | Yabasic | sub rep$(n, c$)
local i, s$
for i = 1 to n
s$ = s$ + c$
next
return s$
end sub
sub sierpinski(n)
local lim, y, x
lim = 2**n - 1
for y = lim to 0 step -1
print rep$(y, " ");
for x = 0 to lim-y
if and(x, y) then print " "; else print "* "; end if
ne... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Scala | Scala | def nextCarpet(carpet: List[String]): List[String] = (
carpet.map(x => x + x + x) :::
carpet.map(x => x + x.replace('#', ' ') + x) :::
carpet.map(x => x + x + x))
def sierpinskiCarpets(n: Int) = (Iterator.iterate(List("#"))(nextCarpet) drop n next) foreach println |
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 ... | #Liberty_BASIC | Liberty BASIC |
print "Loading dictionary."
open "unixdict.txt" for input as #1
while not(eof(#1))
line input #1, a$
dict$=dict$+" "+a$
wend
close #1
print "Dictionary loaded."
print "Seaching for semordnilaps."
semo$=" " 'string to hold words with semordnilaps
do
i=i+1
w$=word$(dict$,i)
p$=reverseString$(w... |
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 Arecib... | #PicoLisp | PicoLisp | (de factor (N)
(make
(let
(D 2
L (1 2 2 . (4 2 4 2 4 6 2 6 .))
M (sqrt N) )
(while (>= M D)
(if (=0 (% N D))
(setq M
(sqrt (setq N (/ N (link D)))) )
(inc 'D (pop 'L)) ) )
(link N) ) ) )
(println ... |
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 Arecib... | #PL.2FI | PL/I | *process source attributes xref nest or(!);
/*--------------------------------------------------------------------
* 22.02.2014 Walter Pachl using the is_prime code from
* PL/I 'prime decomposition'
* 23.02. WP start test for second prime with 2 or first prime found
*----------------------... |
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
... | #Forth | Forth | create weight 1 , 3 , 1 , 7 , 3 , 9 ,
: char>num ( '0-9A-Z' -- 0..35 )
dup [char] 9 > 7 and - [char] 0 - ;
: check+ ( sedol -- sedol' )
6 <> abort" wrong SEDOL length"
0 ( sum )
6 0 do
over I + c@ char>num
weight I cells + @ *
+
loop
10 mod 10 swap - 10 mod [char] 0 +
over 6 + c! 7 ;
... |
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 ... | #PHP | PHP | <?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EO... |
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... | #PureBasic | PureBasic | EnableExplicit
#SPC=Chr(32)
#TB=~"\t"
#TBLF=~"\t\n"
Define.i a,b,l,n,count=0
Define *count.Integer=@count
Procedure.i AddCount(*c.Integer) ; *counter: by Ref
*c\i+1
ProcedureReturn *c\i
EndProcedure
Procedure.s FormatStr(tx$,l.i)
Shared *count
If AddCount(*count)%10=0
ProcedureReturn RSet(tx$,l,#SPC)... |
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.
| #Julia | Julia | nonsquare(n::Real) = n + floor(typeof(n), 0.5 + sqrt(n))
@show nonsquare.(1:1_000_000) ∩ collect(1:1000) .^ 2 |
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.
| #K | K | nonsquare:{x+_.5+%x}
nonsquare[1_!23] |
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... | #Haskell | Haskell | Prelude> import Data.Set
Prelude Data.Set> empty :: Set Integer -- Empty set
fromList []
Prelude Data.Set> let s1 = fromList [1,2,3,4,3] -- Convert list into set
Prelude Data.Set> s1
fromList [1,2,3,4]
Prelude Data.Set> let s2 = fromList [3,4,5,6]
Prelude Data.Set> union s1 s2 -- Union
fromList [1,2,3,4,5,6]
Prelude D... |
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... | #CMake | CMake | function(eratosthenes var limit)
# Check for integer overflow. With CMake using 32-bit signed integer,
# this check fails when limit > 46340.
if(NOT limit EQUAL 0) # Avoid division by zero.
math(EXPR i "(${limit} * ${limit}) / ${limit}")
if(NOT limit EQUAL ${i})
message(FATAL_ERROR "limit is... |
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
Bioin... | #Tcl | Tcl |
for {set i 0} {$i < 16} {incr i} {
for {set j $i} {$j < 128} {incr j 16} {
if {$j <= 31} {
continue ;# don't show values 0 - 31
} elseif {$j == 32} { set x "SP"
} elseif {$j == 127} { set x "DEL"
} else { set x [format %c $j] }
puts -nonewlin... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #zkl | zkl | level,d := 3,T("*");
foreach n in (level + 1){
sp:=" "*(2).pow(n);
d=d.apply('wrap(a){ String(sp,a,sp) }).extend(
d.apply(fcn(a){ String(a," ",a) }));
}
d.concat("\n").println(); |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Scheme | Scheme | (define (carpet n)
(define (in-carpet? x y)
(cond ((or (zero? x) (zero? y))
#t)
((and (= 1 (remainder x 3)) (= 1 (remainder y 3)))
#f)
(else
(in-carpet? (quotient x 3) (quotient y 3)))))
(do ((i 0 (+ i 1))) ((not (< i (expt 3 n))))
(do ((j 0 (+... |
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 ... | #Lua | Lua | #!/usr/bin/env lua
-- allow dictionary file and sample size to be specified on command line
local dictfile = arg[1] or "unixdict.txt"
local sample_size = arg[2] or 5;
-- read dictionary
local f = assert(io.open(dictfile, "r"))
local dict = {}
for line in f:lines() do
dict[line] = line:reverse()
end
f:close()
-- f... |
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 Arecib... | #PowerShell | PowerShell |
function isPrime ($n) {
if ($n -le 1) {$false}
elseif (($n -eq 2) -or ($n -eq 3)) {$true}
else{
$m = [Math]::Floor([Math]::Sqrt($n))
(@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0)
}
}
function semiprime ($n) {
if($n -gt 3) {
$lim = [Math]::Floor($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
... | #Fortran | Fortran | MODULE SEDOL_CHECK
IMPLICIT NONE
CONTAINS
FUNCTION Checkdigit(c)
CHARACTER :: Checkdigit
CHARACTER(6), INTENT(IN) :: c
CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp
INTEGER :: i, n
DO i = 1, 6
temp(... |
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 ... | #Picat | Picat | self_desc(Num,L) =>
L = [ I.to_integer() : I in Num.to_string()],
Len = L.len,
if sum(L) != Len then fail end,
foreach(J in L)
% cannot be a digit larger than the length of Num
if J >= Len then fail end
end,
foreach(I in 0..Len-1)
if sum([1 : J in L, I==J]) != L[I+1] then
fail
end
en... |
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 ... | #PicoLisp | PicoLisp | (de selfDescribing (N)
(fully '((D I) (= D (cnt = N (circ I))))
(setq N (mapcar format (chop N)))
(range 0 (length N)) ) ) |
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... | #Python | Python |
def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
def primes_below(n):
return [i for i in range(n) if prime(i)]
|
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... | #Quackery | Quackery | [ [] swap times
[ i^ isprime if
[ i^ join ] ] ] is primes< ( n --> [ )
100 primes< echo |
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.
| #Kotlin | Kotlin | // version 1.1
fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt()
fun main(args: Array<String>) {
println(" n f")
val squares = mutableListOf<Int>()
for (n in 1 until 1000000) {
val v1 = f(n)
val v2 = Math.sqrt(v1.toDouble()).toInt()
if (v1 == v2 * v2) square... |
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... | #Icon_and_Unicon | Icon and Unicon |
procedure display_set (s)
writes ("[")
every writes (!s || " ")
write ("]")
end
# fail unless s1 and s2 contain the same elements
procedure set_equals (s1, s2)
return subset(s1, s2) & subset(s2, s1)
end
# fail if every element in s2 is not contained in s1
procedure subset (s1, s2)
every (a := !s2) do {
... |
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... | #COBOL | COBOL | *> Please ignore the asterisks in the first column of the next comments,
*> which are kludges to get syntax highlighting to work.
IDENTIFICATION DIVISION.
PROGRAM-ID. Sieve-Of-Eratosthenes.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Max-Number USAGE UNSIGNED-INT.
01 ... |
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
Bioin... | #VBA | VBA |
Public Sub ascii()
Dim s As String, i As Integer, j As Integer
For i = 0 To 15
For j = 32 + i To 127 Step 16
Select Case j
Case 32: s = "Spc"
Case 127: s = "Del"
Case Else: s = Chr(j)
End Select
Debug.Print Tab(10 * (j... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: inCarpet (in var integer: x, in var integer: y) is func
result
var boolean: result is TRUE;
begin
while result and x <> 0 and y <> 0 do
if x rem 3 = 1 and y rem 3 = 1 then
result := FALSE;
else
x := x div 3;
y := y div 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 ... | #M2000_Interpreter | M2000 Interpreter |
Module semordnilaps {
Document d$
Load.Doc d$, "unixdict.txt"
Inventory MyDict, Result
Function s$(a$) {
m$=a$:k=Len(a$):for i=1 to k {insert i, 1 m$=mid$(a$, k, 1):k--} : =m$
}
L=Doc.Par(d$)
m=Paragraph(d$, 0)
If not Forward(d$,m) then exit
i=1
... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | data = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"];
result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]]
&& # =!= StringReverse[#] &], (# ===StringReverse[#2]) &];
Print[Length[result], Take[result, 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 Arecib... | #Python | Python | from prime_decomposition import decompose
def semiprime(n):
d = decompose(n)
try:
return next(d) * next(d) == n
except StopIteration:
return False |
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 Arecib... | #Quackery | Quackery | [ factors size dup 3 4 clamp = ] is semiprime ( n --> b )
say "Semiprimes less than 100:" cr
100 times [ i^ semiprime if [ i^ echo sp ] ] |
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
... | #FreeBASIC | FreeBASIC | ' version 05-07-2015
' compile with: fbc -s console
Function check_sedol(input_nr As String) As Integer
input_nr = Trim(input_nr)
Dim As Integer i, j, x, nr_begin, sum
Dim As String ch, legal = "AEIOU0123456789BCDFGHJKLMNPQRSTVWXYZ"
Dim As Integer weight(0 To ...) = { 1, 3, 1, 7, 3, 9, 1}
x = Le... |
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 ... | #PowerShell | PowerShell |
function Test-SelfDescribing ([int]$Number)
{
[int[]]$digits = $Number.ToString().ToCharArray() | ForEach-Object {[Char]::GetNumericValue($_)}
[int]$sum = 0
for ($i = 0; $i -lt $digits.Count; $i++)
{
$sum += $i * $digits[$i]
}
$sum -eq $digits.Count
}
|
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 ... | #Prolog | Prolog | :- use_module(library(clpfd)).
self_describling :-
forall(between(1, 10, I),
(findall(N, self_describling(I,N), L),
format('Len ~w, Numbers ~w~n', [I, L]))).
% search of the self_describling numbers of a given len
self_describling(Len, N) :-
length(L, Len),
Len1 is Len - 1,
L = [H|T],
% the first f... |
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... | #Racket | Racket | #lang lazy
(define nats (cons 1 (map add1 nats)))
(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l))
(define (sieve l) (cons (first l) (sieve (sift (first l) (rest l)))))
(define primes (sieve (rest nats)))
(!! (take 25 primes)) |
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... | #Raku | Raku | constant @primes = 2, 3, { first * %% none(@_), (@_[* - 1], * + 2 ... *) } ... *;
say @primes[^100]; |
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.
| #Lambdatalk | Lambdatalk |
{def nosquare {lambda {:n} {+ :n {floor {+ 0.5 {sqrt :n}}}}}}
-> nosquare
{def issquare {lambda {:n} {= {sqrt :n} {round {sqrt :n}}}}}
-> issquare
{S.map nosquare {S.serie 1 22}}
-> 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
{S.replace false by in
{S.map issquare _
{S.map nosquare
{S.ser... |
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... | #J | J | union=: ~.@,
intersection=: [ -. -.
difference=: -.
subset=: *./@e.
equality=: -:&(/:~) |
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... | #Comal | Comal | // Sieve of Eratosthenes
input "Limit? ": limit
dim sieve(1:limit)
sqrlimit:=sqr(limit)
sieve(1):=1
p:=2
while p<=sqrlimit do
while sieve(p) and p<sqrlimit do
p:=p+1
endwhile
if p>sqrlimit then goto done
for i:=p*p to limit step p do
sieve(i):=1
endfor i
p:=p+1
endwhile
done:
print 2,
for i:=3 to limit do
if... |
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
Bioin... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Console
Imports System.Linq.Enumerable
Module Program
Sub Main()
Dim Text = Function(index As Integer) If(index = 32, "Sp", If(index = 127, "Del", ChrW(index) & ""))
Dim start = 32
Do
WriteLine(String.Concat(Range(0, 6).Select(Function(i) $"{start + 16 * i, -3}... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Sidef | Sidef | var c = ['##']
3.times {
c = (c.map{|x| x * 3 } +
c.map{|x| x + ' '*x.len + x } +
c.map{|x| x * 3 })
}
say c.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 ... | #Nanoquery | Nanoquery | import Nanoquery.IO
def reverse_str(string)
ret = ""
for char in list(string).reverse()
ret += char
end
return ret
end
lst = split(new(File).open("rosetta-code/unixdict.txt").readAll(), "\n")
seen = list()
count = 0
for w in lst
w = lower(w)
r = re... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
/* REXX ***************************************************************
* 07.09.2012 Walter Pachl
**********************************************************************/
fid = 'unixdict.txt' /* the test dictionary */... |
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 Arecib... | #Racket | Racket | #lang racket
(require math)
(define (pair-factorize n)
"Return all two-number factorizations of a number"
(let ([up-limit (integer-sqrt n)])
(map (λ (x) (list x (/ n x)))
(filter (λ (x) (<= x up-limit)) (divisors n)))))
(define (semiprime n)
"Determine if a number is semiprime i.e. a product of two prim... |
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 Arecib... | #Raku | Raku | sub is-semiprime (Int $n --> Bool) {
not $n.is-prime and
.is-prime given
$n div first $n %% *, flat grep &is-prime, 2 .. *;
}
use Test;
my @primes = flat grep &is-prime, 2 .. 100;
for ^5 {
nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1;
ok is-semiprime([*] my @f2 = @primes.roll(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
... | #Gambas | Gambas | Public Sub Main()
Dim byWeight As Byte[] = [1, 3, 1, 7, 3, 9, 1]
Dim byCount, byCompute As Byte
Dim siTotal As Short
Dim sWork As New String[]
Dim sToProcess As String[] = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
"557910", "B0YBKR", "585284", "B0YBKT", "B00030"]
For b... |
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 ... | #PureBasic | PureBasic | Procedure isSelfDescribing(x.q)
;returns 1 if number is self-describing, otherwise it returns 0
Protected digitCount, digit, i, digitSum
Dim digitTally(10)
Dim digitprediction(10)
If x <= 0
ProcedureReturn 0 ;number must be positive and non-zero
EndIf
While x > 0 And i < 10
digit = x % 10
... |
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... | #REXX | REXX | /*REXX program lists a sequence of primes by testing primality by trial division. */
parse arg n . /*get optional number of primes to find*/
if n=='' | n=="," then n= 26 /*Not specified? Then use the default.*/
tell= (n>0); n= abs(n) ... |
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... | #Ring | Ring |
for i = 1 to 100
if isPrime(i) see "" + i + " " ok
next
see nl
func isPrime n
if n < 2 return false ok
if n < 4 return true ok
if n % 2 = 0 return false ok
for d = 3 to sqrt(n) step 2
if n % d = 0 return false ok
next
return 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.
| #Liberty_BASIC | Liberty BASIC |
for i = 1 to 22
print nonsqr( i); " ";
next i
print
found = 0
for i = 1 to 1000000
j = ( nonsqr( i))^0.5
if j = int( j) then
found = 1
print "Found square: "; i
exit for
end if
next i
if found =0 then print "No squares found"
end
function nonsqr( n)
nonsqr = n +int... |
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.
| #Logo | Logo | repeat 22 [print sum # round sqrt #] |
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... | #Java | Java | import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class Sets {
public static void main(String[] args){
Set<Integer> a = new TreeSet<>();
//TreeSet sorts on natural ordering (or an optional comparator)
//other options: HashSet (has... |
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... | #Common_Lisp | Common Lisp | (defun sieve-of-eratosthenes (maximum)
(loop
with sieve = (make-array (1+ maximum)
:element-type 'bit
:initial-element 0)
for candidate from 2 to maximum
when (zerop (bit sieve candidate))
collect candidate
and do (loop for composite... |
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
Bioin... | #Vlang | Vlang | fn main() {
for i in 0..16{
for j := 32 + i; j < 128; j += 16 {
mut k := u8(j).ascii_str()
match j {
32 {
k = "Spc"
}
127 {
k = "Del"
} else {
}
}
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 LET O=3
20 LET S=3**O
30 FOR I=0 TO S-1
40 FOR J=0 TO S-1
50 LET X=J
60 LET Y=I
70 GOSUB 120
80 IF C THEN PLOT J,I
90 NEXT J
100 NEXT I
110 GOTO 190
120 LET C=0
130 IF X-INT (X/3)*3=1 AND Y-INT (Y/3)*3=1 THEN RETURN
140 LET X=INT (X/3)
150 LET Y=INT (Y/3)
160 IF X>0 OR Y>0 THEN GOTO 130
170 LET C=1
180 RETU... |
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 ... | #NewLisp | NewLisp |
;;; Get the words as a list, splitting at newline
(setq data
(parse (get-url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
"\n"))
;
;;; destructive reverse wrapped into a function
(define (get-reverse x) (reverse x))
;
;;; stack of the results
(setq res '())
;
;;; Find the semordlinap and put them on the s... |
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 Arecib... | #REXX | REXX | /* REXX ---------------------------------------------------------------
* 20.02.2014 Walter Pachl relying on 'prime decomposition'
* 21.02.2014 WP Clarification: I copied the algorithm created by
* Gerard Schildberger under the task referred to above
* 21.02.2014 WP Make sure that factr is not called illega... |
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
... | #Go | Go |
package main
import (
"fmt"
"strings"
"strconv"
)
const input = `710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
B
B0003
B000300
A00030
E00030
I00030
O00030
U00030
β00030
β0003`
var weight = [...]int{1,3,1,7,3,9}
func csd(code string) string {
switch len(code) {
... |
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 ... | #Python | Python | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, Tru... |
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... | #Ruby | Ruby | require "prime"
pg = Prime::TrialDivisionGenerator.new
p pg.take(10) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
p pg.next # => 31 |
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... | #Rust | Rust |
fn is_prime(number: u32) -> bool {
#[allow(clippy::cast_precision_loss)]
let limit = (number as f32).sqrt() as u32 + 1;
// We test if the number is divisible by any number up to the limit
!(number < 2 || (2..limit).any(|x| number % x == 0))
}
fn main() {
println!(
"Primes below 100:\n{... |
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... | #S-BASIC | S-BASIC |
comment
Prime number generator in S-BASIC. Only odd numbers are
checked, and only the prime numbers previously found (up
to the square root of the number currently under examination)
are tested as divisors. Memory is conserved by saving only the
first 50 primes as potential divisors, since that is suff... |
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.
| #Lua | Lua | function nonSquare (n)
return n + math.floor(1/2 + math.sqrt(n))
end
for n = 1, 22 do
io.write(nonSquare(n) .. " ")
end
print()
local sr
for n = 1, 10^6 do
sr = math.sqrt(nonSquare(n))
if sr == math.floor(sr) then
print("Result for n = " .. n .. " is square!")
os.exit()
end
end
pri... |
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.
| #MAD | MAD | NORMAL MODE IS INTEGER
BOOLEAN FOUND
FOUND = 0B
R SEQUENCE OF NON-SQUARES FORMULA
R FLOOR IS AUTOMATIC DUE TO INTEGER MATH
INTERNAL FUNCTION NONSQR.(N) = N+(.5+SQRT.(N))
R PRINT VALUES FOR 1..N..22
THROUGH SHOW, FO... |
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... | #JavaScript | JavaScript |
var set = new Set();
set.add(0);
set.add(1);
set.add('two');
set.add('three');
set.has(0); //=> true
set.has(3); //=> false
set.has('two'); // true
set.has(Math.sqrt(4)); //=> false
set.has('TWO'.toLowerCase()); //=> true
set.size; //=> 4
set.delete('two');
set.has('two'); //==> false
set.size; //=> 3
//ite... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
# To change the maximum prime, change the size of this array
# Everything else is automatically filled in at compile time
var sieve: uint8[5000];
# Make sure all elements of the sieve are set to zero
MemZero(&sieve as [uint8], @bytesof sieve);
# Generate the sieve
var prime: @indexof 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
Bioin... | #Wren | Wren | import "/fmt" for Fmt
for (i in 0...16) {
var j = 32 + i
while (j < 128) {
var k = "%(String.fromByte(j))"
if (j == 32) {
k = "Spc"
} else if (j == 127) {
k = "Del"
}
System.write("%(Fmt.d(3, j)) : %(Fmt.s(-3, k)) ")
j = j + 16
}
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Swift | Swift | import Foundation
func sierpinski_carpet(n:Int) -> String {
func middle(str:String) -> String {
let spacer = str.stringByReplacingOccurrencesOfString("#", withString:" ", options:nil, range:nil)
return str + spacer + str
}
var carpet = ["#"]
for i in 1...n {
let a = carpet.map{... |
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 ... | #Nim | Nim | import strutils, sequtils, sets, algorithm
proc reversed(s: string): string =
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
let
words = readFile("unixdict.txt").strip().splitLines()
wordset = words.toHashSet
revs = words.map(reversed)
var pairs = zip(words, revs).filterIt(it[0] < it[... |
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 ... | #OCaml | OCaml | module StrSet = Set.Make(String)
let str_rev s =
let len = String.length s in
let r = Bytes.create len in
for i = 0 to len - 1 do
Bytes.set r i s.[len - 1 - i]
done;
Bytes.to_string r
let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> close_in ic; None
let () =
let ic = open_... |
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 Arecib... | #Ring | Ring |
prime = 1679
decomp(prime)
func decomp nr
x = ""
sum = 0
for i = 1 to nr
if isPrime(i) and nr % i = 0
sum = sum + 1
x = x + string(i) + " * " ok
if i = nr and sum = 2
x2 = substr(x,1,(len(x)-2))
see string(nr) + " = " + x2 + "is semiprime" + nl
but i = nr and sum != 2 see st... |
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 Arecib... | #Ruby | Ruby | require 'prime'
# 75.prime_division # Returns the factorization.75 divides by 3 once and by 5 twice => [[3, 1], [5, 2]]
class Integer
def semi_prime?
prime_division.sum(&:last) == 2
end
end
p 1679.semi_prime? # true
p ( 1..100 ).select( &:semi_prime? )
# [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38,... |
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
... | #Groovy | Groovy | def checksum(text) {
assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text"
def sum = 0
(0..5).each { index ->
sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index]
}
text + (10 - (sum % 10)) % 10
}
String.metaClass.sedol = { thi... |
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 ... | #Quackery | Quackery | [ tuck over peek
1+ unrot poke ] is item++ ( n [ --> [ )
[ [] 10 times [ 0 join ]
swap
[ 10 /mod rot item++
swap dup 0 = until ]
drop ] is digitcount ( n --> [ )
[ 0 swap witheach + ] is sum ( [ --> n )
[ 0 swap
witheach
[ swap 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 ... | #Racket | Racket | #lang racket
(define (get-digits number (lst null))
(if (zero? number)
lst
(get-digits (quotient number 10) (cons (remainder number 10) lst))))
(define (self-describing? number)
(if (= number 0) #f
(let ((digits (get-digits number)))
(for/fold ((bool #t))
((i (in-range (length ... |
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... | #Scala | Scala | def sieve(nums: Stream[Int]): Stream[Int] =
Stream.cons(nums.head, sieve((nums.tail).filter(_ % nums.head != 0)))
val primes = 2 #:: sieve(Stream.from(3, 2))
println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, ... |
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... | #Sidef | Sidef | func prime_seq(amount, callback) {
var (counter, number) = (0, 0);
while (counter < amount) {
if (is_prime(number)) {
callback(number);
++counter;
}
++number;
}
}
prime_seq(100, {|p| say p}); # prints the first 100 primes |
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.
| #Maple | Maple |
with(NumberTheory):
nonSquareSequence := proc(n::integer)
return n + floor(1 / 2 + sqrt(n));
end proc:
seq(nonSquareSequence(i), i = 1..22);
for number from 1 to 10^6 while not issqr(nonSquareSequence(number)) do end;
number;
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | nonsq = (# + Floor[0.5 + Sqrt[#]]) &;
nonsq@Range[22]
If[! Or @@ (IntegerQ /@ Sqrt /@ nonsq@Range[10^6]),
Print["No squares for n <= ", 10^6]
] |
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... | #jq | jq | {"a":true, "b":true } == {"b":true, "a":true}.
{"a":true} + {"b":true } == { "a":true, "b":true} |
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... | #Crystal | Crystal | # compile with `--release --no-debug` for speed...
require "bit_array"
alias Prime = UInt64
class SoE
include Iterator(Prime)
@bits : BitArray; @bitndx : Int32 = 2
def initialize(range : Prime)
if range < 2
@bits = BitArray.new 0
else
@bits = BitArray.new((range + 1).to_i32)
end
... |
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
Bioin... | #XPL0 | XPL0 | int Hi, Lo;
[SetHexDigits(2);
Text(0, " ");
for Hi:= 2 to 7 do
[HexOut(0, Hi*16); Text(0, " ")];
CrLf(0);
for Lo:= 0 to $F do
[HexOut(0, Lo); Text(0, " ");
for Hi:= 2 to 7 do
[ChOut(0, Hi*16+Lo); Text(0, " ")];
CrLf(0);
];
] |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Tcl | Tcl | package require Tcl 8.5
proc map {lambda list} {
foreach elem $list {
lappend result [apply $lambda $elem]
}
return $result
}
proc sierpinski_carpet n {
set carpet [list "#"]
for {set i 1} {$i <= $n} {incr i} {
set carpet [concat \
[map {x {subst {$x$x$x}}} $carpet] \... |
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 ... | #Octave | Octave | a = strsplit(fileread("unixdict.txt"), "\n");
a = intersect(a, cellfun(@fliplr, a, "UniformOutput", false));
a = a(arrayfun(@(i) ismember(fliplr(a{i}), a(i+1:length(a))), 1:length(a)));
length(a)
arrayfun(@(i) printf("%s %s\n", a{i}, fliplr(a{i})), 1: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 Arecib... | #Rust | Rust | extern crate primal;
fn isqrt(n: usize) -> usize {
(n as f64).sqrt() as usize
}
fn is_semiprime(mut n: usize) -> bool {
let root = isqrt(n) + 1;
let primes1 = primal::Sieve::new(root);
let mut count = 0;
for i in primes1.primes_from(2).take_while(|&x| x < root) {
while n % i == 0 {
... |
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 Arecib... | #Scala | Scala | object Semiprime extends App {
def isSP(n: Int): Boolean = {
var nf: Int = 0
var l = n
for (i <- 2 to l/2) {
while (l % i == 0) {
if (nf == 2) return false
nf +=1
l /= i
}
}
nf == 2
}
(2 to 100) filter {isSP(_) == true} foreach {i => print("%d ".format(... |
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
... | #Haskell | Haskell | import Data.Char (isAsciiUpper, isDigit, ord)
-------------------------- SEDOLS ------------------------
checkSum :: String -> String
checkSum x =
case traverse sedolValue x of
Right xs -> (show . checkSumFromSedolValues) xs
Left annotated -> annotated
checkSumFromSedolValues :: [Int] -> Int
checkSumFro... |
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 ... | #Raku | Raku | my @values = <1210 2020 21200 3211000
42101000 521001000 6210001000 27 115508>;
for @values -> $test {
say "$test is {sdn($test) ?? '' !! 'NOT ' }a self describing number.";
}
sub sdn($n) {
my $s = $n.Str;
my $chars = $s.chars;
my @a = +«$s.comb;
my @b;
for @a -> $i {
return False if... |
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... | #Spin | Spin | con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial"
pub main | d, n
ser.start(31, 30, 0, 115200)
repeat n from 2 to 100
repeat d from 2 to n-1
if n // d == 0
quit
if d == n
ser.dec(n)
ser.tx(32)
waitcnt(_clkfreq + cnt)
ser.stop |
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... | #Swift | Swift | import Foundation
extension SequenceType {
func takeWhile(include: Generator.Element -> Bool) -> AnyGenerator<Generator.Element> {
var g = self.generate()
return anyGenerator { g.next().flatMap{include($0) ? $0 : nil }}
}
}
var pastPrimes = [2]
var primes = anyGenerator {
_ -> Int? in
defer {
... |
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... | #Tailspin | Tailspin |
templates ifPrime
def n: $;
[2..~$n -> $n ~/ $ * $] -> \(<~[<=$n>]> $n ! \)!
end ifPrime
templates primes
[2..$ -> ifPrime] !
end primes
100 -> primes -> '$;
' -> !OUT::write
|
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.
| #MATLAB | MATLAB | function nonSquares(i)
for n = (1:i)
generatedNumber = n + floor(1/2 + sqrt(n));
if mod(sqrt(generatedNumber),1)==0 %Check to see if the sqrt of the generated number is an integer
fprintf('\n%d generates a square number: %d\n', [n,generatedNumber]);
return
else ... |
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.
| #Maxima | Maxima | nonsquare(n) := n + quotient(isqrt(100 * n) + 5, 10);
makelist(nonsquare(n), n, 1, 20);
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]
not_square(n) := isqrt(n)^2 # n$
m: 10^6$
u: makelist(i, i, 1, m)$
is(sublist(u, not_square) = sublist(map(nonsquare, u), lambda([x], x <= m)));
true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.