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_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.
| #Common_Lisp | Common Lisp | (defun non-square-sequence ()
(flet ((non-square (n)
"Compute the N-th number of the non-square sequence"
(+ n (floor (+ 1/2 (sqrt n)))))
(squarep (n)
"Tests, whether N is a square"
(let ((r (floor (sqrt n))))
(= (* r r) n))))
(loop
:for n :upfrom 1 :to 22
:do (format t "~2D ... |
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... | #CoffeeScript | CoffeeScript |
# For ad-hoc set features, it sometimes makes sense to use hashes directly,
# rather than abstract to this level, but I'm showing a somewhat heavy
# solution to show off CoffeeScript class syntax.
class Set
constructor: (elems...) ->
@hash = {}
for elem in elems
@hash[elem] = true
add: (elem)... |
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... | #AutoHotkey | AutoHotkey | MsgBox % "12345678901234567890`n" Sieve(20)
Sieve(n) { ; Sieve of Eratosthenes => string of 0|1 chars, 1 at position k: k is prime
Static zero := 48, one := 49 ; Asc("0"), Asc("1")
VarSetCapacity(S,n,one)
NumPut(zero,S,0,"char")
i := 2
Loop % sqrt(n)-1 {
If (NumGet(S,i-1,"char") = one)
... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Racket | Racket |
#lang racket
(define (consolidate ss)
(define (comb s cs)
(cond [(set-empty? s) cs]
[(empty? cs) (list s)]
[(set-empty? (set-intersect s (first cs)))
(cons (first cs) (comb s (rest cs)))]
[(consolidate (cons (set-union s (first cs)) (rest cs)))]))
(foldl comb '() ss))
... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Raku | Raku | multi consolidate() { () }
multi consolidate(Set \this is copy, *@those) {
gather {
for consolidate |@those -> \that {
if this ∩ that { this = this ∪ that }
else { take that }
}
take this;
}
}
enum Elems <A B C D E F G H I J K>;
say $_, "\n ==> ", c... |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Wren | Wren | import "/crypto" for Sha1
import "/fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"The qui... |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #zkl | zkl | $ zkl // run the REPL
zkl: var MsgHash=Import("zklMsgHash")
MsgHash
zkl: MsgHash.SHA1("Rosetta Code")
48c98f7e5a6e736d790ab740dfc3f51a61abe2b5
zkl: var hash=MsgHash.SHA1("Rosetta Code",1,False) // hash once, return hash as bytes
Data(20)
zkl: hash.bytes()
L(72,201,143,126,90,110,115,109,121,10,183,64,223,195,245,26... |
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... | #PL.2FM | PL/M | 100H: /* SHOW AN ASCII TABLE FROM 32 TO 127 */
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* I/O ROUTINES */
PR$CHA... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Scala | Scala | scala -e "for(y<-0 to 15){println(\" \"*(15-y)++(0 to y).map(x=>if((~y&x)>0)\" \"else\" *\")mkString)}" |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
/r { moveto 0 -1 1 0 0 1 3 { rlineto } repeat closepath fill } def
/serp { gsave
3 1 roll translate
1 3 div dup scale
1 1 r
dup 1 sub dup 0 eq not {
0 0 0 1 0 2 1 0 1 2 2 0 2 1 2 2 17 -1 roll 8 { serp } repeat
} if pop
... |
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 ... | #EchoLisp | EchoLisp |
(lib 'struct)
(lib 'sql)
(lib 'words)
(lib 'dico.fr.no-accent) ;; load dictionary
(string-delimiter "")
;; check reverse r of w is a word
;; take only one pair : r < w
(define (semordnilap? w)
(define r (list->string (reverse (string->list w))))
(and (word? r) (string<? r w)))
;; to get longest first
... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: a (in boolean: aBool) is func
result
var boolean: result is FALSE;
begin
writeln("a");
result := aBool;
end func;
const func boolean: b (in boolean: aBool) is func
result
var boolean: result is FALSE;
begin
writeln("b");
result := aBool... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Sidef | Sidef | func a(bool) { print 'A'; return bool }
func b(bool) { print 'B'; return bool }
# Test-driver
func test() {
for op in ['&&', '||'] {
for x,y in [[1,1],[1,0],[0,1],[0,0]] {
"a(%s) %s b(%s): ".printf(x, op, y)
eval "a(Bool(x)) #{op} b(Bool(y))"
print "\n"
}
}
... |
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 f... | #OCaml | OCaml | let h = Smtp.connect "smtp.gmail.fr";;
Smtp.helo h "hostname";;
Smtp.mail h "<john.smith@example.com>";;
Smtp.rcpt h "<john-doe@example.com>";;
let email_header = "\
From: John Smith <john.smith@example.com>
To: John Doe <john-doe@example.com>
Subject: surprise";;
let email_msg = "Happy Birthday";;
Smtp.data h (email_h... |
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 f... | #Perl | Perl | use Net::SMTP;
use Authen::SASL;
# Net::SMTP's 'auth' method needs Authen::SASL to work, but
# this is undocumented, and if you don't have the latter, the
# method will just silently fail. Hence we explicitly use
# Authen::SASL here.
sub send_email
{my %o =
(from => '', to => [], cc => [],
subject... |
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... | #Elixir | Elixir | defmodule Prime do
def semiprime?(n), do: length(decomposition(n)) == 2
def decomposition(n), do: decomposition(n, 2, [])
defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n])
defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
defp decomposition(... |
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... | #Erlang | Erlang |
-module(factors).
-export([factors/1,kthfactor/2]).
factors(N) ->
factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N rem K == 0 ->
factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
factors(N,K+1,Acc).
% is integer N factorable into M primes?
kthfactor(N,M) ->
case l... |
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
... | #AutoHotkey | AutoHotkey | codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB
Loop, Parse, codes, `,
output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n"
Msgbox %output%
SEDOL(code) {
Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9
If (StrLen(code) != 6... |
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 ... | #Factor | Factor | USING: kernel math.parser prettyprint sequences ;
IN: rosetta-code.self-describing-numbers
: digits ( n -- seq ) number>string string>digits ;
: digit-count ( seq n -- m ) [ = ] curry count ;
: self-describing-number? ( n -- ? )
digits dup [ digit-count = ] with map-index [ t = ] all? ;
100,000,000 <iota> [... |
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 ... | #Forth | Forth | \ where unavailable.
: third ( A b c -- A b c A ) >r over r> swap ;
: (.) ( u -- c-addr u ) 0 <# #s #> ;
\ COUNT is a standard word with a very different meaning, so this
\ would typically be beheaded, or given another name, or otherwise
\ given a short lifespan, so to speak.
: count ( c-addr1 u1 c -- c-addr1 u1 c+... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
sum[g_] := g + Total@IntegerDigits@g
ming[n_] := n - IntegerLength[n]*9
self[n_] := NoneTrue [Range[ming[n], n - 1], sum[#] == n &]
Module[{t = 1, x = 1},
Reap[
While[t <= 50,
If[self[x], Sow[x]; t++]; x++]
][[2, 1]]]
|
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Nim | Nim | import bitops, strutils, std/monotimes, times
const MaxCount = 2 * 1_000_000_000 + 9 * 9
# Bit string used to represent an array of booleans.
type BitString = object
len: Natural # length in bits.
values: seq[byte] # Sequence containing the bits.
proc newBitString(n: Natural): BitString =
## Retu... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Pascal | Pascal | program selfnumb;
{$IFDEF FPC}
{$MODE Delphi}
{$Optimization ON,ALL}
{$IFEND}
{$IFDEF DELPHI} {$APPTYPE CONSOLE} {$IFEND}
uses
sysutils;
const
MAXCOUNT =103*10000*10000+11*9+ 1;
type
tDigitSum9999 = array[0..9999] of Uint8;
tpDigitSum9999 = ^tDigitSum9999;
var
DigitSum9999 : tDigitSum9999;
sieve : array... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Python | Python | class Setr():
def __init__(self, lo, hi, includelo=True, includehi=False):
self.eqn = "(%i<%sX<%s%i)" % (lo,
'=' if includelo else '',
'=' if includehi else '',
hi)
def __contains__(self, ... |
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... | #Factor | Factor | USING: combinators kernel lists lists.lazy math math.functions
math.ranges prettyprint sequences ;
: prime? ( n -- ? )
{
{ [ dup 2 < ] [ drop f ] }
{ [ dup even? ] [ 2 = ] }
[ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
} cond ;
! Create an infinite lazy list of primes.
: 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... | #FileMaker | FileMaker |
#May 10th., 2018.
Set Error Capture [On]
Allow User Abort [Off]
# Set default number of minutes
Set Variable [$maxduration; Value:1]
# Ask user for a desired duration of the test
Show Custom Dialog [ "Setup";
"Enter the number of minutes (0,1-15, 6s increments) you would like this test to run.¶" &
"Hit an... |
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.
| #D | D | import std.stdio, std.math, std.algorithm, std.range;
int nonSquare(in int n) pure nothrow @safe @nogc {
return n + cast(int)(0.5 + real(n).sqrt);
}
void main() {
iota(1, 23).map!nonSquare.writeln;
foreach (immutable i; 1 .. 1_000_000) {
immutable ns = i.nonSquare;
assert(ns != (cast(i... |
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... | #Common_Lisp | Common Lisp | (setf a '(1 2 3 4))
(setf b '(2 3 4 5))
(format t "sets: ~a ~a~%" a b)
;;; element
(loop for x from 1 to 6 do
(format t (if (member x a)
"~d ∈ A~%"
"~d ∉ A~%") x))
(format t "A ∪ B: ~a~%" (union a b))
(format t "A ∩ B: ~a~%" (intersection a b))
(format t "A \\ B: ~a~%" (set-difference a b))
(format t... |
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... | #AutoIt | AutoIt | #include <Array.au3>
$M = InputBox("Integer", "Enter biggest Integer")
Global $a[$M], $r[$M], $c = 1
For $i = 2 To $M -1
If Not $a[$i] Then
$r[$c] = $i
$c += 1
For $k = $i To $M -1 Step $i
$a[$k] = True
Next
EndIf
Next
$r[0] = $c - 1
ReDim $r[$c]
_ArrayDisplay($r) |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #REXX | REXX | /*REXX program demonstrates a method of set consolidating using some sample sets. */
@.=; @.1 = '{A,B} {C,D}'
@.2 = "{A,B} {B,D}"
@.3 = '{A,B} {C,D} {D,B}'
@.4 = '{H,I,K} {A,B} {C,D} {D,B} {F,G,H}'
... |
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... | #Prolog | Prolog | ascii :-
forall(between(32, 47, N), row(N)).
row(N) :- N > 127, nl, !.
row(N) :-
code(N),
ascii(N),
Nn is N + 16,
row(Nn).
code(N) :- N < 100, format(' ~d : ', N).
code(N) :- N >= 100, format(' ~d : ', N).
ascii(32) :- write(' Spc '), !.
ascii(127) :- write(' Del '), !.
ascii(A) :- cha... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Scheme | Scheme | (define (sierpinski n)
(for-each
(lambda (x) (display (list->string x)) (newline))
(let loop ((acc (list (list #\*))) (spaces (list #\ )) (n n))
(if (zero? n)
acc
(loop
(append
(map (lambda (x) (append spaces x spaces)) acc)
(map (lambda (x) (append x (list... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PowerShell | PowerShell | function Draw-SierpinskiCarpet ( [int]$N )
{
$Carpet = @( '#' ) * [math]::Pow( 3, $N )
ForEach ( $i in 1..$N )
{
$S = [math]::Pow( 3, $i - 1 )
ForEach ( $Row in 0..($S-1) )
{
$Carpet[$Row+$S+$S] = $Carpet[$Row] * 3
$Carpet[$Row+$S] = $Carpet[$Ro... |
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 ... | #Eiffel | Eiffel |
class
SEMORDNILAP
create
make
feature
make
--Semordnilaps in 'solution'.
local
count, i, middle, upper, lower: INTEGER
reverse: STRING
do
read_wordlist
create solution.make_empty
from
i := 1
until
i > word_array.count
loop
word_array [i].mirror
reverse := word_arra... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Simula | Simula | BEGIN
BOOLEAN PROCEDURE A(BOOL); BOOLEAN BOOL;
BEGIN OUTCHAR('A'); A := BOOL;
END A;
BOOLEAN PROCEDURE B(BOOL); BOOLEAN BOOL;
BEGIN OUTCHAR('B'); B := BOOL;
END B;
PROCEDURE OUTBOOL(BOOL); BOOLEAN BOOL;
OUTCHAR(IF BOOL THEN 'T' ELSE 'F');
PROCEDURE TEST;
BEGIN
... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Smalltalk | Smalltalk | Smalltalk at: #a put: nil.
Smalltalk at: #b put: nil.
a := [:x| 'executing a' displayNl. x].
b := [:x| 'executing b' displayNl. x].
('false and false = %1' %
{ (a value: false) and: [ b value: false ] })
displayNl.
('true or false = %1' %
{ (a value: true) or: [ b value: false ] })
displayNl.
('fa... |
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 f... | #Phix | Phix | without js -- (libcurl)
include builtins\libcurl.e
constant USER = "you@gmail.com",
PWD = "secret",
URL = "smtps://smtp.gmail.com:465",
FROM = "sender@gmail.com",
TO = "addressee@email.com",
CC = "info@example.org",
FMT = "Date: Mon, 13 Jun 2018 11:30:00 +0100\r\... |
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... | #ERRE | ERRE |
PROGRAM SEMIPRIME_NUMBER
!VAR I%
PROCEDURE SEMIPRIME(N%->RESULT%)
LOCAL F%,P%
P%=2
LOOP
EXIT IF NOT(F%<2 AND P%*P%<=N%)
WHILE (N% MOD P%)=0 DO
N%=N% DIV P%
F%+=1
END WHILE
P%+=1
END LOOP
RESULT%=F%-(N%>1)=2
END PROCEDURE
BEGIN
PRINT(CHR$(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 Arecib... | #F.23 | F# | let isSemiprime (n: int) =
let rec loop currentN candidateFactor numberOfFactors =
if numberOfFactors > 2 then numberOfFactors
elif currentN = candidateFactor then numberOfFactors+1
elif currentN % candidateFactor = 0 then loop (currentN/candidateFactor) candidateFactor (numberOfFactors+1)
... |
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
... | #AWK | AWK | function ord(a)
{
return amap[a]
}
function sedol_checksum(sed)
{
sw[1] = 1; sw[2] = 3; sw[3] = 1
sw[4] = 7; sw[5] = 3; sw[6] = 9
sum = 0
for(i=1; i <= 6; i++) {
c = substr(toupper(sed), i, 1)
if ( c ~ /[[:digit:]]/ ) {
sum += c*sw[i]
} else {
sum += (ord(c)-ord("A")+10)*sw[i]
}
... |
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 ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function selfDescribing (n As UInteger) As Boolean
If n = 0 Then Return False
Dim ns As String = Str(n)
Dim count(0 To 9) As Integer '' all elements zero by default
While n > 0
count(n Mod 10) += 1
n \= 10
Wend
For i As Integer = 0 To Len(ns) - 1
If ns[i] - 48 <> cou... |
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 ... | #Go | Go | package main
import (
"fmt"
"strconv"
"strings"
)
// task 1 requirement
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util qw(max sum);
my ($i, $pow, $digits, $offset, $lastSelf, @selfs)
= ( 1, 10, 1, 9, 0, );
my $final = 50;
while () {
my $isSelf = 1;
my $sum = my $start = sum split //, max(($i-$offset), 0);
for ( my $j = $start; $j < $... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Racket | Racket |
#lang racket
;; Use a macro to allow infix operators
(require (only-in racket [#%app #%%app]))
(define-for-syntax infixes '())
(define-syntax (definfix stx)
(syntax-case stx ()
[(_ (x . xs) body ...) #'(definfix x (λ xs body ...))]
[(_ x body) (begin (set! infixes (cons #'x infixes)) #'(define x body))]))... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Raku | Raku | class Iv {
has $.range handles <min max excludes-min excludes-max minmax ACCEPTS>;
method empty {
$.min after $.max or $.min === $.max && ($.excludes-min || $.excludes-max)
}
multi method Bool() { not self.empty };
method length() { $.max - $.min }
method gist() {
($.excludes-min ?? '(' !! '['... |
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... | #Forth | Forth |
variable p-start \ beginning of prime buffer
variable p-end \ end of prime buffer
: +prime ( n -- )
p-end @ tuck ! cell+ p-end ! ;
: setup-pgen ( addr n -- n )
dup 3 < abort" The buffer must be large enough to store at least three primes."
swap dup p-start ! p-end !
2 +prime 3 +prime 5 +p... |
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... | #Fortran | Fortran |
CONCOCTED BY R.N.MCLEAN, APPLIED MATHS COURSE, AUCKLAND UNIVERSITY, MCMLXXI.
INTEGER ENUFF,PRIME(44)
CALCULATION SHOWS PRIME(43) = 181, AND PRIME(44) = 191.
INTEGER N,F,Q,XP2
INTEGER INC,IP,LP,PP
INTEGER ALINE(20),LL,I
DATA ENUFF/44/
DATA PP/4/
DATA PRIME(1),PRIME(2),PRIME(3)... |
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.
| #Delphi | Delphi |
program Sequence_of_non_squares;
uses
System.SysUtils, System.Math;
function nonsqr(i: Integer): Integer;
begin
Result := Trunc(i + Floor(0.5 + Sqrt(i)));
end;
var
i: Integer;
j: Double;
begin
for i := 1 to 22 do
write(nonsqr(i), ' ');
Writeln;
for i := 1 to 999999 do
begin
j := Sq... |
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... | #D | D | void main() {
import std.stdio, std.algorithm, std.range;
// Not true sets, items can be repeated, but must be sorted.
auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted;
auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8].
auto s3 = [1, 2, 5].assumeSorted;
assert(s1.canFind(4)); // Linear search.
... |
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... | #AWK | AWK | $ awk '{for(i=2;i<=$1;i++) a[i]=1;
> for(i=2;i<=sqrt($1);i++) for(j=2;j<=$1;j++) delete a[i*j];
> for(i in a) printf i" "}'
100
71 53 17 5 73 37 19 83 47 29 7 67 59 11 97 79 89 31 13 41 23 2 61 43 3
|
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Ring | Ring |
# Project : Set consolidation
load "stdlib.ring"
test = ["AB","AB,CD","AB,CD,DB","HIK,AB,CD,DB,FGH"]
for t in test
see consolidate(t) + nl
next
func consolidate(s)
sets = split(s,",")
n = len(sets)
for i = 1 to n
p = i
ts = ""
for j = i to 1 step -1
if ts = ""
p = j
ok
... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Ruby | Ruby | require 'set'
tests = [[[:A,:B], [:C,:D]],
[[:A,:B], [:B,:D]],
[[:A,:B], [:C,:D], [:D,:B]],
[[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]]
tests.map!{|sets| sets.map(&:to_set)}
tests.each do |sets|
until sets.combination(2).none?{|a,b| a.merge(b) && sets.delete(b) if a.intersect?(... |
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... | #PureBasic | PureBasic | If OpenConsole("Show_Ascii_table: rosettacode.org")
Define r.i, c.i
For r=0 To 15
For c=32+r To 112+r Step 16
Print(RSet(Str(c),3)+" : ")
Select c
Case 32
Print("Spc")
Case 127
Print("Del")
Default
Print(LSet(Chr(c),3))
EndSelect
Prin... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func array string: sierpinski (in integer: n) is func
result
var array string: parts is 1 times "*";
local
var integer: i is 0;
var string: space is " ";
var array string: parts2 is 0 times "";
var string: x is "";
begin
for i range 1 to n do
parts2 ... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Processing | Processing | float delta;
void setup() {
size(729, 729);
fill(0);
background(255);
noStroke();
rect(width/3, height/3, width/3, width/3);
rectangles(width/3, height/3, width/3);
}
void rectangles(int x, int y, int s) {
if (s < 1) return;
int xc = x-s;
int yc = y-s;
for (int row = 0; row < 3; row++) {
for... |
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 ... | #Elixir | Elixir | words = File.stream!("unixdict.txt")
|> Enum.map(&String.strip/1)
|> Enum.group_by(&min(&1, String.reverse &1))
|> Map.values
|> Enum.filter(&(length &1) == 2)
IO.puts "Semordnilap pair: #{length(words)}"
IO.inspect Enum.take(words,5) |
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 ... | #Erlang | Erlang | #!/usr/bin/env escript
main([]) -> main(["unixdict.txt"]);
main([DictFile]) ->
Dict = sets:from_list(read_lines(DictFile)),
Semordnilaps =
lists:filter(fun([W,R]) -> W < R end,
lists:map(fun(W) -> [W, lists:reverse(W)] end,
semordnilaps(Dict))),
io:fwrite("There are ~b semordnilaps in ~s~n"... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #SNOBOL4 | SNOBOL4 | define('a(val)') :(a_end)
a out = 'A '
eq(val,1) :s(return)f(freturn)
a_end
define('b(val)') :(b_end)
b out = 'B '
eq(val,1) :s(return)f(freturn)
b_end
* # Test and display
&fullscan = 1
output(.out,1,'-[-r1]') ;* Macro Spitbol
* output(.out,1,... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Standard_ML | Standard ML | fun a r = ( print " > function a called\n"; r )
fun b r = ( print " > function b called\n"; r )
fun test_and b1 b2 = (
print ("# testing (" ^ Bool.toString b1 ^ " andalso " ^ Bool.toString b2 ^ ")\n");
ignore (a b1 andalso b b2) )
fun test_or b1 b2 = (
print ("# testing (" ^ Bool.toString b1 ^ " orelse " ^ Bo... |
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 f... | #PHP | PHP | mail('hello@world.net', 'My Subject', "A Message!", "From: my@address.com"); |
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 f... | #PicoLisp | PicoLisp | (mail "localhost" 25 "me@from.org" "you@to.org" "Subject" NIL "Hello") |
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 f... | #Pike | Pike | int main(){
string to = "some@email.add";
string subject = "Hello There.";
string from = "me@myaddr.ess";
string msg = "Hello there! :)";
Protocols.SMTP.Client()->simple_mail(to,subject,from,msg);
} |
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... | #Factor | Factor | USING: io kernel math.primes.factors prettyprint sequences ;
: semiprime? ( n -- ? ) factors length 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 Arecib... | #Forth | Forth | : semiprime?
0 swap dup 2 do
begin dup i mod 0= while i / swap 1+ swap repeat
over 1 > over i dup * < or if leave then
loop 1 > abs + 2 =
;
: test 100 2 do i semiprime? if i . then loop cr ; |
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
... | #BASIC | BASIC | DECLARE FUNCTION getSedolCheckDigit! (str AS STRING)
DO
INPUT a$
PRINT a$ + STR$(getSedolCheckDigit(a$))
LOOP WHILE a$ <> ""
FUNCTION getSedolCheckDigit (str AS STRING)
IF LEN(str) <> 6 THEN
PRINT "Six chars only please"
EXIT FUNCTION
END IF
str = UCASE$(str)
DIM mult(6... |
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 ... | #Haskell | Haskell | import Data.Char
count :: Int -> [Int] -> Int
count x = length . filter (x ==)
isSelfDescribing :: Integer -> Bool
isSelfDescribing n = nu == f
where
nu = digitToInt <$> show n
f = (`count` nu) <$> [0 .. length nu - 1]
main :: IO ()
main = do
print $
isSelfDescribing <$>
[1210, 2020, 21200, 32... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Phix | Phix | --
-- Base-10 self numbers by index (single or range).
-- Follows an observed sequence pattern whereby, after the initial single-digit odd numbers, self numbers are
-- grouped in runs whose members occur at numeric intervals of 11. Runs after the first one come in blocks of
-- ten: eight runs of ten numbers followe... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #REXX | REXX | /*REXX program demonstrates a way to represent any set of real numbers and usage. */
call quertySet 1, 3, '[1,2)'
call quertySet , , '[0,2) union (1,3)'
call quertySet , , '[0,1) union (2,3]'
call quertySet , , '[0,2] inter (1,3)'
call quertySet , , '(1,2) ∩ (2,3]'
call quertySet ... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n < 2 Then Return False
If n = 2 Then Return True
If n Mod 2 = 0 Then Return False
Dim limit As Integer = Sqr(n)
For i As Integer = 3 To limit Step 2
If n Mod i = 0 Then Return False
Next
Return True
End Function
' Print all primes fr... |
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.
| #EchoLisp | EchoLisp |
(lib 'sequences)
(define (a n) (+ n (floor (+ 0.5 (sqrt n)))))
(define A000037 (iterator/n a 1))
(take A000037 22)
→ (2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
(filter square? (take A000037 1000000))
→ null
|
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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
do
sequence_of_non_squares (22)
io.new_line
sequence_of_non_squares (1000000)
end
sequence_of_non_squares (n: INTEGER)
-- Sequence of non-squares up to the n'th member.
require
n_positive: n >= 1
local
non_sq, part: ... |
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... | #Dart | Dart | void main(){
//Set Creation
Set A = new Set.from([1,2,3]);
Set B = new Set.from([1,2,3,4,5]);
Set C = new Set.from([1,2,4,5]);
print('Set A = $A');
print('Set B = $B');
print('Set C = $C');
print('');
//Test if element is in set
int m = 3;
print('m = 5');
print('m in A = ${A.contains(m)}');
... |
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... | #Bash | Bash | DIM n AS Integer, k AS Integer, limit AS Integer
INPUT "Enter number to search to: "; limit
DIM flags(limit) AS Integer
FOR n = 2 TO SQR(limit)
IF flags(n) = 0 THEN
FOR k = n*n TO limit STEP n
flags(k) = 1
NEXT k
END IF
NEXT n
' Display the primes
FOR n = 2 TO limit
IF flag... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Scala | Scala | object SetConsolidation extends App {
def consolidate[Type](sets: Set[Set[Type]]): Set[Set[Type]] = {
var result = sets // each iteration combines two sets and reiterates, else returns
for (i <- sets; j <- sets - i; k = i.intersect(j);
if result == sets && k.nonEmpty) result = result - i... |
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... | #Python | Python |
for i in range(16):
for j in range(32+i, 127+1, 16):
if j == 32:
k = 'Spc'
elif j == 127:
k = 'Del'
else:
k = chr(j)
print("%3d : %-3s" % (j,k), end="")
print()
|
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:
*
* *
* *
* * * *
* *
* * * *
... | #Sidef | Sidef | func sierpinski_triangle(n) {
var triangle = ['*']
{ |i|
var sp = (' ' * 2**i)
triangle = (triangle.map {|x| sp + x + sp} +
triangle.map {|x| x + ' ' + x})
} * n
triangle.join("\n")
}
say sierpinski_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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Prolog | Prolog | main:-
write_sierpinski_carpet('sierpinski_carpet.svg', 486, 4).
write_sierpinski_carpet(File, Size, Order):-
open(File, write, Stream),
format(Stream,
"<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n",
[Size, Size]),
write(Stream, "<rect width='100%' height='10... |
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 ... | #F.23 | F# | open System
let seen = new System.Collections.Generic.Dictionary<string,bool>()
let lines = System.IO.File.ReadLines("unixdict.txt")
let sems = seq {
for word in lines do
let drow = new String(Array.rev(word.ToCharArray()))
if fst(seen.TryGetValue(drow)) then yield (drow, word)
seen.[d... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Stata | Stata | function a(x) {
printf(" a")
return(x)
}
function b(x) {
printf(" b")
return(x)
}
function call(i, j) {
printf("and:")
x = a(i)
if (x) {
x = b(j)
}
printf("\nor:")
y = a(i)
if (!y) {
y = b(j)
}
printf("\n")
return((x,y))
} |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Swift | Swift | func a(v: Bool) -> Bool {
print("a")
return v
}
func b(v: Bool) -> Bool {
print("b")
return v
}
func test(i: Bool, j: Bool) {
println("Testing a(\(i)) && b(\(j))")
print("Trace: ")
println("\nResult: \(a(i) && b(j))")
println("Testing a(\(i)) || b(\(j))")
print("Trace: ")
println("\nResult: ... |
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 f... | #PowerShell | PowerShell |
[hashtable]$mailMessage = @{
From = "weirdBoy@gmail.com"
To = "anudderBoy@YourDomain.com"
Cc = "daWaghBoss@YourDomain.com"
Attachment = "C:\temp\Waggghhhh!_plan.txt"
Subject = "Waggghhhh!"
Body = "Wagggghhhhhh!"
SMTPServer = "smtp.gmail.com"
SMTPPort = "587"
UseSsl = $true
Erro... |
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 f... | #PureBasic | PureBasic | InitNetwork()
CreateMail(0, "from@mydomain.com", "This is the Subject")
SetMailBody(0, "Hello " + Chr(10) + "This is a mail !")
AddMailRecipient(0, "test@yourdomain.com", #PB_Mail_To)
AddMailRecipient(0, "test2@yourdomain.com", #PB_Mail_Cc)
If SendMail(0, "smtp.mail.com")
MessageRequester("Information",... |
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... | #Frink | Frink | isSemiprime[n] :=
{
factors = factor[n]
sum = 0
for [num, power] = factors
sum = sum + power
return sum == 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 Arecib... | #Go | Go | package main
import "fmt"
func semiprime(n int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == 2 {
return false
}
nf++
n /= i
}
}
return nf == 2
}
func main() {
for v := 1675; v <= 1680; v++ {
... |
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
... | #BBC_BASIC | BBC BASIC | PRINT FNsedol("710889")
PRINT FNsedol("B0YBKJ")
PRINT FNsedol("406566")
PRINT FNsedol("B0YBLH")
PRINT FNsedol("228276")
PRINT FNsedol("B0YBKL")
PRINT FNsedol("557910")
PRINT FNsedol("B0YBKR")
PRINT FNsedol("585284")
PRINT FNsedol("B0YBKT")
PRINT FNsedol(... |
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
... | #C | C | #include <stdio.h>
#include <ctype.h>
#include <string.h>
int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = "AEIOUaeiou";
int sedol_checksum(const char *sedol6)
{
int len = strlen(sedol6);
int sum = 0, i;
if ( len == 7 ) {
fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6);
... |
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 ... | #Icon_and_Unicon | Icon and Unicon |
procedure count (test_item, str)
result := 0
every item := !str do
if test_item == item then result +:= 1
return result
end
procedure is_self_describing (n)
ns := string (n) # convert to a string
every i := 1 to *ns do {
if count (string(i-1), ns) ~= ns[i] then fail
}
return 1 # success
end
... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Python | Python | class DigitSumer :
def __init__(self):
sumdigit = lambda n : sum( map( int,str( n )))
self.t = [sumdigit( i ) for i in xrange( 10000 )]
def __call__ ( self,n ):
r = 0
while n >= 10000 :
n,q = divmod( n,10000 )
r += self.t[q]
return r + self.t[n]
... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Raku | Raku | # 20201127 Raku programming solution
my ( $st, $count, $i, $pow, $digits, $offset, $lastSelf, $done, @selfs) =
now, 0, 1, 10, 1, 9, 0, False;
# while ( $count < 1e8 ) {
until $done {
my $isSelf = True;
my $sum = (my $start = max ($i-$offset), 0).comb.sum;
loop ( my $j = ... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Ruby | Ruby | class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi)
end
def length
hi - lo
end
def to_s
"#{inc_lo ? '[' : '('}#{lo},#{hi}#{inc_hi ? ']' : ')'}"
end
end
def initialize(lo=nil, hi=nil, inc_lo=false... |
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... | #Go | Go | package main
import "fmt"
func NumsFromBy(from int, by int, ch chan<- int) {
for i := from; ; i+=by {
ch <- i
}
}
func Filter(in <-chan int, out chan<- int, prime int) {
for {
i := <-in
if i%prime != 0 { // here is the trial division
out <- i
}
}
}
func Sieve(out chan<- ... |
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.
| #Elixir | Elixir | f = fn n -> n + trunc(0.5 + :math.sqrt(n)) end
IO.inspect for n <- 1..22, do: f.(n)
n = 1_000_000
non_squares = for i <- 1..n, do: f.(i)
m = :math.sqrt(f.(n)) |> Float.ceil |> trunc
squares = for i <- 1..m, do: i*i
case Enum.find_value(squares, fn i -> i in non_squares end) do
nil -> IO.puts "No squares found be... |
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.
| #Erlang | Erlang | % Implemented by Arjun Sunel
-module(non_squares).
-export([main/0]).
main() ->
lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,22)), % First 22 non-squares.
lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,1000000)). % First 1 million non-squares.
non_squar... |
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... | #Delphi | Delphi |
program Set_task;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Generics.Collection;
begin
var s1 := TSet<Integer>.Create([1, 2, 3, 4, 5, 6]);
var s2 := TSet<Integer>.Create([2, 5, 6, 3, 4, 8]);
var s3 := TSet<Integer>.Create([1, 2, 5]);
Writeln('S1 ', s1.ToString);
Writeln('S2 ', s2.ToString);... |
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... | #BASIC | BASIC | DIM n AS Integer, k AS Integer, limit AS Integer
INPUT "Enter number to search to: "; limit
DIM flags(limit) AS Integer
FOR n = 2 TO SQR(limit)
IF flags(n) = 0 THEN
FOR k = n*n TO limit STEP n
flags(k) = 1
NEXT k
END IF
NEXT n
' Display the primes
FOR n = 2 TO limit
IF flag... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Sidef | Sidef | func consolidate() { [] }
func consolidate(this, *those) {
gather {
consolidate(those...).each { |that|
if (this & that) { this |= that }
else { take that }
}
take this;
}
}
enum |A="A", B, C, D, _E, F, G, H, I, _J, K|;
func format(ss) {
ss.map... |
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... | #QB64 | QB64 | DIM s AS STRING
FOR i% = 32 TO 47
FOR j% = i% TO i% + 80 STEP 16
SELECT CASE j%
CASE 32
s$ = "Spc"
CASE 127
s$ = "Del"
CASE ELSE
s$ = CHR$(j%)
END SELECT
PRINT USING "###: \ \"; j%; s$;
NEXT j%
PR... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Swift | Swift | import Foundation
// Easy get/set of charAt
extension String {
subscript(index:Int) -> String {
get {
var array = Array(self)
var charAtIndex = array[index]
return String(charAtIndex)
}
set(newValue) {
var asChar = Character(newValue)
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PureBasic | PureBasic | Procedure in_carpet(x,y)
While x>0 And y>0
If x%3=1 And y%3=1
ProcedureReturn #False
EndIf
y/3: x/3
Wend
ProcedureReturn #True
EndProcedure
Procedure carpet(n)
Define i, j, l=Pow(3,n)-1
For i=0 To l
For j=0 To l
If in_carpet(i,j)
Print("#")
Else
Print(" ")
... |
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 ... | #Factor | Factor | USING: assocs combinators.short-circuit formatting
io.encodings.utf8 io.files kernel literals locals make
prettyprint random sequences ;
IN: rosetta-code.semordnilap
CONSTANT: words $[ "unixdict.txt" utf8 file-lines ]
: semordnilap? ( str1 str2 -- ? )
{ [ = not ] [ nip words member? ] } 2&& ;
[
[let
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.