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.
#Bc
Bc
#! /usr/bin/bc   scale = 20   define ceil(x) { auto intx intx=int(x) if (intx<x) intx+=1 return intx }   define floor(x) { return -ceil(-x) }   define int(x) { auto old_scale, ret old_scale=scale scale=0 ret=x/1 scale=old_scale return ret }   define round(x) { if (x<0) x-...
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...
#BBC_BASIC
BBC BASIC
DIM list$(6) list$() = "apple", "banana", "cherry", "date", "elderberry", "fig", "grape"   setA% = %1010101 PRINT "Set A: " FNlistset(list$(), setA%) setB% = %0111110 PRINT "Set B: " FNlistset(list$(), setB%) elementM% = %0000010 PRINT "Element M: " FNlistset(list$(), ele...
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Python
Python
class Example(object): def foo(self, x): return 42 + x   name = "foo" getattr(Example(), name)(5) # => 47
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Qi
Qi
  (define foo -> 5)   (define execute-function Name -> (eval [(INTERN Name)]))   (execute-function "foo")  
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Racket
Racket
  #lang racket (define greeter (new (class object% (super-new) (define/public (hello name) (displayln (~a "Hello " name "."))))))   ; normal method call (send greeter hello "World")   ; sending an unknown method (define unknown 'hello) (dynamic-send greeter unknown "World")  
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Raku
Raku
my $object = 42 but role { method add-me($x) { self + $x } } my $name = 'add-me'; say $object."$name"(5); # 47
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...
#ALGOL_68
ALGOL 68
BOOL prime = TRUE, non prime = FALSE; PROC eratosthenes = (INT n)[]BOOL: ( [n]BOOL sieve; FOR i TO UPB sieve DO sieve[i] := prime OD; INT m = ENTIER sqrt(n); sieve[1] := non prime; FOR i FROM 2 TO m DO IF sieve[i] = prime THEN FOR j FROM i*i BY i TO n DO sieve[j] := non prime OD FI...
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Raku
Raku
constant @primes = |grep *.is-prime, 2..*; constant @primorials = [\*] 1, @primes;   my @pp_indexes := |@primorials.pairs.map: { .key if ( .value + any(1, -1) ).is-prime };   say ~ @pp_indexes[ 0 ^.. 20 ]; # Skipping bogus first element.
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Ring
Ring
  # Project : Sequence of primorial primes   max = 9999 primes = [] for n = 1 to max if isprime(n) = 1 add(primes, n) ok next for n = 1 to len(primes) sum = 1 for m = 1 to n sum = sum * primes[m] next if (isprime(sum+1) or isprime(sum-1)) = 1 see "" + n + " " ...
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...
#OCaml
OCaml
let join a b = List.fold_left (fun acc v -> if List.mem v acc then acc else v::acc ) b a   let share a b = List.exists (fun x -> List.mem x b) a   let extract p lst = let rec aux acc = function | x::xs -> if p x then Some (x, List.rev_append acc xs) else aux (x::acc) xs | [] -> None in aux [] lst   le...
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Raku
Raku
sub div-count (\x) { return 2 if x.is-prime; +flat (1 .. x.sqrt.floor).map: -> \d { unless x % d { my \y = x div d; y == d ?? y !! (y, d) } } }   my $limit = 15;   put "First $limit terms of OEIS:A005179"; put (1..$limit).map: -> $n { first { $n == .&div-count }, 1..Inf };    
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#REXX
REXX
/*REXX program finds and displays the smallest number with exactly N divisors.*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/ say '──divisors── ──smallest number with N div...
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Ring
Ring
  # Project: SHA-256   load "stdlib.ring" str = "Rosetta code" see "String: " + str + nl see "SHA-256: " see sha256(str) + nl  
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Ruby
Ruby
require 'digest/sha2' puts Digest::SHA256.hexdigest('Rosetta code')
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#XPL0
XPL0
func Divs(N); \Count divisors of N int N, D, C; [C:= 0; if N > 1 then [D:= 1; repeat if rem(N/D) = 0 then C:= C+1; D:= D+1; until D >= N; ]; return C; ];   int An, N; [An:= 1; N:= 0; loop [if Divs(An) = N then [IntOut(0, An); ChOut(0, ^ ); N:= N+1; if N >= 15 ...
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#zkl
zkl
fcn countDivisors(n) { [1..(n).toFloat().sqrt()] .reduce('wrap(s,i){ s + (if(0==n%i) 1 + (i!=n/i)) },0) }
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...
#Ring
Ring
  # Project : SHA-1   load "stdlib.ring" str = "Rosetta Code" see "String: " + str + nl see "SHA-1: " see sha1(str) + nl  
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...
#Ruby
Ruby
require 'digest' puts Digest::SHA1.hexdigest('Rosetta Code')
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...
#MiniScript
MiniScript
// Prints ASCII table // Note changing the values of startChar and endChar will print // a flexible table in that range   startChar = 32 endChar = 127 characters = []   for i in range(startChar, endChar) addString = char(i) + " " if i == 32 then addString = "SPC" if i == 127 then addString = "DEL" char...
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: * * * * * * * * * * * * * * * ...
#Racket
Racket
  #lang racket (define (sierpinski n) (if (zero? n) '("*") (let ([spaces (make-string (expt 2 (sub1 n)) #\space)] [prev (sierpinski (sub1 n))]) (append (map (λ(x) (~a spaces x spaces)) prev) (map (λ(x) (~a x " " x)) prev))))) (for-each displayln (sierpinski 5))  
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Pascal
Pascal
program SierpinskiCarpet;   uses Math;   function In_carpet(a, b: longint): boolean; var x, y: longint; begin x := a; y := b; while true do begin if (x = 0) or (y = 0) then begin In_carpet := true; break; end else if ((x mod 3) = 1) and ((y mod 3) = 1) then begin In_car...
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 ...
#Bracmat
Bracmat
( get'("unixdict.txt",STR):?dict & new$hash:?H & 0:?p & ( @( !dict  :  ? ( [!p ?w \n [?p ? & (H..insert)$(!w.rev$!w) & ~ ) ) | 0:?N & (H..forall) $ ( = .  !arg:(?a.?b) & !a:<!b & (H..find)$!b & !...
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 ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <alloca.h> /* stdlib.h might not have obliged. */ #include <string.h>   static void reverse(char *s, int len) { int i, j; char tmp;   for (i = 0, j = len - 1; i < len / 2; ++i, --j) tmp = s[i], s[i] = s[j], s[j] = tmp; }   /* Wrap strcmp() for qsort()....
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...
#Python
Python
>>> def a(answer): print(" # Called function a(%r) -> %r" % (answer, answer)) return answer   >>> def b(answer): print(" # Called function b(%r) -> %r" % (answer, answer)) return answer   >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ...
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...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   module Main (main) where   import Network.Mail.SMTP ( Address(..) , htmlPart , plainTextPart , sendMailWithLogin' , simpleMail )   main :: IO () main = ...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) mail := open("mailto:"||args[1], "m", "Subject : "||args[2], "X-Note: automatically send by Unicon") | stop("Cannot send mail to ",args[1]) every write(mail , !&input) close (mail) end
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#C.23
C#
  static void Main(string[] args) { //test some numbers for (int i = 0; i < 50; i++) { Console.WriteLine("{0}\t{1} ", i,isSemiPrime(i)); } Console.ReadLine(); }   //returns true or false depending if input was considered semiprime private static bool isSemiPrime(int c) { int a = 2, b = 0...
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 ...
#Action.21
Action!
INT FUNC SedolChecksum(CHAR ARRAY sedol) BYTE ARRAY weights=[1 3 1 7 3 9] INT i,sum CHAR c   IF sedol(0)#6 THEN RETURN (-1) FI   sum=0 FOR i=1 TO sedol(0) DO c=sedol(i) IF c>='0 AND c<='9 THEN sum==+(c-'0)*weights(i-1) ELSE IF c>='a AND c<='z THEN c==-'a-'A FI ...
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 ...
#AWK
AWK
# syntax: GAWK -f SELF-DESCRIBING_NUMBERS.AWK BEGIN { for (n=1; n<=100000000; n++) { if (is_self_describing(n)) { print(n) } } exit(0) } function is_self_describing(n, i) { for (i=1; i<=length(n); i++) { if (substr(n,i,1) != gsub(i-1,"&",n)) { return(0) } } ...
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 ...
#BASIC
BASIC
DIM x, r, b, c, n, m AS INTEGER DIM a, d AS STRING DIM v(10), w(10) AS INTEGER CLS FOR x = 1 TO 5000000 a$ = LTRIM$(STR$(x)) b = LEN(a$) FOR c = 1 TO b d$ = MID$(a$, c, 1) v(VAL(d$)) = v(VAL(d$)) + 1 w(c - 1) = VAL(d$) NEXT c r = 0 FOR n = 0 TO 10 IF v(n) = w(n) THEN r = r + 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...
#C.23
C#
using System; using static System.Console;   class Program {   const int mc = 103 * 1000 * 10000 + 11 * 9 + 1;   static bool[] sv = new bool[mc + 1];   static void sieve() { int[] dS = new int[10000]; for (int a = 9, i = 9999; a >= 0; a--) for (int b = 9; b >= 0; b--) for (int c = 9, s = a + b; ...
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 | ...
#JavaScript
JavaScript
  function realSet(set1, set2, op, values) { const makeSet=(set0)=>{ let res = [] if(set0.rangeType===0){ for(let i=set0.low;i<=set0.high;i++) res.push(i); } else if (set0.rangeType===1) { for(let i=set0.low+1;i<set0.high;i++) res.push(...
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...
#Clojure
Clojure
(ns test-p.core (:require [clojure.math.numeric-tower :as math]))   (defn prime? [a] " Uses trial division to determine if number is prime " (or (= a 2) (and (> a 2) (> (mod a 2) 0) (not (some #(= 0 (mod a %)) (range 3 (inc (int (Math/ceil (math/sqrt a)))) 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.
#Burlesque
Burlesque
  1 22r@{?s0.5?+av?+}[m  
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...
#BQN
BQN
Union ← ⍷∾ Inter ← ∊/⊣ Diff ← ¬∘∊/⊣ Subset ← ∧´∊ Eq ← ≡○∧ CreateSet ← ⍷   •Show 2‿4‿6‿8 Union 2‿3‿5‿7 •Show 2‿4‿6‿8 Inter 2‿3‿5‿7 •Show 2‿4‿6‿8 Diff 2‿3‿5‿7 •Show 2‿4‿6‿8 Subset 2‿3‿5‿7 •Show 2‿4‿6‿8 Eq 2‿3‿5‿7 •Show CreateSet 2‿2‿3‿5‿7‿2
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Ruby
Ruby
class Example def foo 42 end def bar(arg1, arg2, &block) block.call arg1, arg2 end end   symbol = :foo Example.new.send symbol # => 42 Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3 args = [1, 2] Example.new.send( "bar", *args ) { |x,y| x+y } # => 3
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Scala
Scala
class Example { def foo(x: Int): Int = 42 + x }   object Main extends App { val example = new Example   val meth = example.getClass.getMethod("foo", classOf[Int])   assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.") println(s"Successfully completed with...
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Sidef
Sidef
class Example { method foo(x) { 42 + x } }   var name = 'foo' var obj = Example()   say obj.(name)(5) # prints: 47 say obj.method(name)(5) # =//=
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...
#ALGOL_W
ALGOL W
begin    % implements the sieve of Eratosthenes  %  % s(i) is set to true if i is prime, false otherwise  %  % algol W doesn't have a upb operator, so we pass the size of the  %  % array in n ...
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Ruby
Ruby
    # Sequence of primorial primes   require 'prime' # for creating prime_array require 'openssl' # for using fast Miller–Rabin primality test (just need 10.14 seconds to complete)   i, urutan, primorial_number = 1, 1, OpenSSL::BN.new(1) start = Time.now prime_array = Prime.first (500)   until urutan > 20 primorial_n...
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Sidef
Sidef
func primorial_primes(n) {   var k = 1 var p = 2 var P = 2   var seq = [] for (var i = 0; i < n; ++k) {   if (is_prime(P-1) || is_prime(P+1)) { seq << k ++i }   p.next_prime! P *= p }   return seq }   say primorial_primes(20)
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...
#ooRexx
ooRexx
/* REXX *************************************************************** * 04.08.2013 Walter Pachl using ooRexx features * (maybe not in the best way -improvements welcome!) * but trying to demonstrate the algorithm *********************************************************************...
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl see "the first 15 terms of the sequence are:" + nl   for n = 1 to 15 for m = 1 to 4100 pnum = 0 for p = 1 to 4100 if (m % p = 0) pnum = pnum + 1 ok next if pnum = n see "" + m + " " ...
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Ruby
Ruby
require 'prime'   def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end   def first_with_num_divs(n) (1..).detect{|i| num_divisors(i) == n } end   p (1..15).map{|n| first_with_num_divs(n) }  
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Rust
Rust
use sha2::{Digest, Sha256};   fn hex_string(input: &[u8]) -> String { input.as_ref().iter().map(|b| format!("{:x}", b)).collect() }   fn main() { // create a Sha256 object let mut hasher = Sha256::new();   // write input message hasher.update(b"Rosetta code");   // read hash digest and consume h...
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Scala
Scala
object RosettaSHA256 extends App {   def MD5(s: String): String = { // Besides "MD5", "SHA-256", and other hashes are available val m = java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8")) m.map("%02x".format(_)).mkString }   assert(MD5("Rosetta code") == "764faf5c61ac315f149...
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...
#Rust
Rust
use sha1::Sha1;   fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }  
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...
#S-lang
S-lang
require("chksum"); print(sha1sum("Rosetta Code"));
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...
#Nanoquery
Nanoquery
k = "" for i in range(0, 15) for j in range(32 + i, 127, 16) if j = 32 k = "Spc" else if j = 127 k = "Del" else k = chr(j) end print format("%3d : %-3s ", j, k) end println 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...
#Nim
Nim
import strformat   for i in 0..15: for j in countup(32 + i, 127, step = 16): let k = case j of 32: "Spc" of 127: "Del" else: $chr(j) write(stdout, fmt"{j:3d} : {k:<6s}") write(stdout, "\n")
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: * * * * * * * * * * * * * * * ...
#Raku
Raku
sub sierpinski ($n) { my @down = '*'; my $space = ' '; for ^$n { @down = |("$space$_$space" for @down), |("$_ $_" for @down); $space x= 2; } return @down; }   .say for sierpinski 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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Perl
Perl
my @c = '##'; @c = (map($_ x 3, @c), map($_.(' ' x length).$_, @c), map($_ x 3, @c)) for 1 .. 3; print join("\n", @c), "\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 ...
#C.23
C#
using System; using System.Net; using System.Collections.Generic; using System.Linq; using System.IO;   public class Semordnilap { public static void Main() { var results = FindSemordnilaps("http://www.puzzlers.org/pub/wordlists/unixdict.txt").ToList(); Console.WriteLine(results.Count); var ...
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...
#R
R
a <- function(x) {cat("a called\n"); x} b <- function(x) {cat("b called\n"); x}   tests <- expand.grid(op=list(quote(`||`), quote(`&&`)), x=c(1,0), y=c(1,0))   invisible(apply(tests, 1, function(row) { call <- substitute(op(a(x),b(y)), row) cat(deparse(call), "->", eval(call), "\n\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...
#Racket
Racket
#lang racket (define (a x) (display (~a "a:" x " ")) x)   (define (b x) (display (~a "b:" x " ")) x)   (for* ([x '(#t #f)] [y '(#t #f)]) (displayln `(and (a ,x) (b ,y))) (and (a x) (b y)) (newline)   (displayln `(or (a ,x) (b ,y))) (or (a x) (b y)) (newline))
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...
#Java
Java
import java.util.Properties;   import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;   /** * Mail */ public class Mail { /** * Session */ protected...
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...
#C.2B.2B
C++
  #include <iostream>   bool isSemiPrime( int c ) { int a = 2, b = 0; while( b < 3 && c != 1 ) { if( !( c % a ) ) { c /= a; b++; } else a++; } return b == 2; } int main( int argc, char* argv[] ) { for( int x = 2; x < 100; x++ ) if( isSemiPrime( x ) ) std::cout << x << " ";   return...
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 ...
#ActionScript
ActionScript
//Return the code corresponding to a given character. //ActionScript does not have a character type, so 1-digit strings //are used instead function toSEDOLCode(char:String):uint { //Make sure only a single character was sent. if(char.length != 1) throw new Error("toSEDOL expected string length of 1, got " + char.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 ...
#BBC_BASIC
BBC BASIC
FOR N = 1 TO 5E7 IF FNselfdescribing(N) PRINT N NEXT END   DEF FNselfdescribing(N%) LOCAL D%(), I%, L%, O% DIM D%(9) O% = N% L% = LOG(N%) WHILE N% I% = N% MOD 10 D%(I%) += 10^(L%-I%) N% DIV=10 ENDWHILE = O% = SUM(D%())
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 ...
#Befunge
Befunge
>1+9:0>\#06#:p#-:#1_$v ?v6:%+55:\+1\<<<\0:::< #>g1+\6p55+/:#^_001p\v ^_@#!`<<v\+g6g10*+55\< >:*:*:*^>>:01g1+:01p`| ^_\#\:#+.#5\#5,#$:<-$<
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...
#Elixir
Elixir
  defmodule SelfNums do   def digAndSum(number) when is_number(number) do Integer.digits(number) |> Enum.reduce( 0, fn(num, acc) -> num + acc end ) |> (fn(x) -> x + number end).() end   def selfFilter(list, firstNth) do numRange = Enum.to_list 1..firstNth numRange -- list end   end   defmod...
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...
#F.23
F#
  // Self numbers. Nigel Galloway: October 6th., 2020 let fN g=let rec fG n g=match n/10 with 0->n+g |i->fG i (g+(n%10)) in fG g g let Self=let rec Self n i g=seq{let g=g@([n..i]|>List.map fN) in yield! List.except g [n..i]; yield! Self (n+100) (i+100) (List.filter(fun n->n>i) g)} in Self 0 99 []   Self |> Seq.take 5...
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 | ...
#Julia
Julia
  """ struct ConvexRealSet Convex real set (similar to a line segment). Parameters: lower bound, upper bound: floating point numbers includelower, includeupper: boolean true or false to indicate whether the set has a closed boundary (set to true) or open (set to false). """ mutable struct Co...
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 | ...
#Kotlin
Kotlin
// version 1.1.4-3   typealias RealPredicate = (Double) -> Boolean   enum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }   class RealSet(val low: Double, val high: Double, val predicate: RealPredicate) {   constructor (start: Double, end: Double, rangeType: RangeType): this(start, end, when (r...
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...
#Common_Lisp
Common Lisp
(defun primes-up-to (max-number) "Compute all primes up to MAX-NUMBER using trial division" (loop for n from 2 upto max-number when (notany (evenly-divides n) primes) collect n into primes finally (return primes)))   (defun evenly-divides (n) "Create a function that checks whet...
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...
#Crystal
Crystal
See https://rosettacode.org/wiki/Primality_by_trial_division#Crystal
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.
#C
C
#include <math.h> #include <stdio.h> #include <assert.h>   int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); /* return n + (int)round(sqrt(n)); in C99 */ }   int main() { int i;   /* first 22 values (as a list) has no squares: */ for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); prin...
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...
#C
C
#include <stdio.h>   typedef unsigned int set_t; /* probably 32 bits; change according to need */   void show_set(set_t x, const char *name) { int i; printf("%s is:", name); for (i = 0; (1U << i) <= x; i++) if (x & (1U << i)) printf(" %d", i); putchar('\n'); }   int main(void) { int i; set_t a, b, c;   a = ...
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Smalltalk
Smalltalk
Object subclass: #Example.   Example extend [ foo: x [ ^ 42 + x ] ].   symbol := 'foo:' asSymbol. " same as symbol := #foo: "   Example new perform: symbol with: 5. " returns 47 "
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Swift
Swift
import Foundation   class MyUglyClass: NSObject { @objc func myUglyFunction() { print("called myUglyFunction") } }   let someObject: NSObject = MyUglyClass()   someObject.perform(NSSelectorFromString("myUglyFunction"))
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Tcl
Tcl
package require Tcl 8.6 oo::class create Example { method foo {} {return 42} method 1 {s} {puts "fee$s"} method 2 {s} {puts "fie$s"} method 3 {s} {puts "foe$s"} method 4 {s} {puts "fum$s"} } set eg [Example new] set mthd [format "%c%c%c" 102 111 111]; # A "foo" by any other means would smell as s...
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#ALGOL-M
ALGOL-M
  BEGIN   COMMENT FIND PRIMES UP TO THE SPECIFIED LIMIT (HERE 1,000) USING CLASSIC SIEVE OF ERATOSTHENES;   % CALCULATE INTEGER SQUARE ROOT % INTEGER FUNCTION ISQRT(N); INTEGER N; BEGIN INTEGER R1, R2; R1 := N; R2 := 1; WHILE R1 > R2 DO BEGIN R1 := (R1+R2) / 2; R2 :=...
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Swift
Swift
import BigInt import Foundation   extension BinaryInteger { @inlinable public var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true }   let max = Self(ceil((Double(self).squareRoot())))   for i in stride(from: 2, through: max, by: 1) where se...
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Wren
Wren
import "/big" for BigInt import "/math" for Int import "io" for Stdout   var primes = Int.primeSieve(4000) // more than enough for this task System.print("The indices of the first 15 primorial numbers, p, where p + 1 or p - 1 is prime are:") var count = 0 var prod = BigInt.two for (i in 1...primes.count) { if ((pro...
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...
#PARI.2FGP
PARI/GP
cons(V)={ my(v,u,s); for(i=1,#V, v=V[i]; for(j=i+1,#V, u=V[j]; if(#setintersect(u,v),V[i]=v=vecsort(setunion(u,v));V[j]=[];s++) ) ); V=select(v->#v,V); if(s,cons(V),V) };
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Rust
Rust
  use itertools::Itertools;   const PRIMES: [u64; 15] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]; const MAX_DIVISOR: usize = 64;   struct DivisorSeq { max_number_of_divisors: u64, index: u64, }   impl DivisorSeq { fn new(max_number_of_divisors: u64) -> DivisorSeq { DivisorSeq { ...
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Sidef
Sidef
func n_divisors(n) { 1..Inf -> first_by { .sigma0 == n } }   say 15.of { n_divisors(_+1) }
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Seed7
Seed7
$ include "seed7_05.s7i"; include "msgdigest.s7i";   const proc: main is func begin writeln(hex(sha256("Rosetta code"))); end func;
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Sidef
Sidef
var sha = frequire('Digest::SHA'); say sha.sha256_hex('Rosetta code');
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...
#Scala
Scala
  import java.nio._   case class Hash(message: List[Byte]) { val defaultHashes = List(0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0)   val hash = { val padded = generatePadding(message) val chunks: List[List[Byte]] = messageToChunks(padded) toHashForm(hashesFromChunks(chunks)) }   def g...
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...
#Objeck
Objeck
class AsciiTable { function : Main(args : String[]) ~ Nil { for(i := 32; i <= 127 ; i += 1;) { if(i = 32 | i = 127) { s := i = 32 ? "Spc" : "Del"; "{$i}:\t{$s}\t"->Print(); } else { c := i->ToChar(); "{$i}:\t{$c}\t"->Print(); }; if((i-1) % 6 = 0 ) { ...
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: * * * * * * * * * * * * * * * ...
#REXX
REXX
/*REXX program constructs and displays a Sierpinski triangle of up to around order 10k.*/ parse arg n mark . /*get the order of Sierpinski triangle.*/ if n=='' | n=="," then n=4 /*Not specified? Then use the default.*/ if mark=='' then mark= "*" ...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Phix
Phix
constant order = 4 function InCarpet(atom x, atom y) while x!=0 and y!=0 do if floor(mod(x,3))=1 and floor(mod(y,3))=1 then return ' ' end if x /= 3 y /= 3 end while return '#' end function for i=0 to power(3,order)-1 do for j=0 to power(3,order)-1 do ...
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 ...
#C.2B.2B
C++
#include <fstream> #include <iostream> #include <set> #include <string>   int main() { std::ifstream input("unixdict.txt"); if (input) { std::set<std::string> words; // previous words std::string word; // current word size_t count = 0; // pair count   while (input >> word) { ...
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...
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   sub a ($p) { print 'a'; $p } sub b ($p) { print 'b'; $p }   for 1, 0 X 1, 0 -> ($p, $q) { for '&&', '||' -> $op { my $s = "a($p) $op b($q)"; print "$s: "; EVAL $s; print "\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...
#REXX
REXX
/*REXX programs demonstrates short─circuit evaluation testing (in an IF statement).*/ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= -2 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 2 ...
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...
#Julia
Julia
  using SMTPClient   addbrackets(s) = replace(s, r"^\s*([^\<\>]+)\s*$", s"<\1>")   function wrapRFC5322(from, to, subject, msg) timestr = Libc.strftime("%a, %d %b %Y %H:%M:%S %z", time()) IOBuffer("Date: $timestr\nTo: $to\nFrom: $from\nSubject: $subject\n\n$msg") end   function sendemail(from, to, subject, mess...
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...
#Kotlin
Kotlin
// version 1.1.4-3   import java.util.Properties import javax.mail.Authenticator import javax.mail.PasswordAuthentication import javax.mail.Session import javax.mail.internet.MimeMessage import javax.mail.internet.InternetAddress import javax.mail.Message.RecipientType import javax.mail.Transport   fun sendEmail(user: ...
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...
#Clojure
Clojure
  (ns example (:gen-class))   (defn semi-prime? [n] (loop [a 2 b 0 c n] (cond (> b 2) false (<= c 1) (= b 2) (= 0 (rem c a)) (recur a (inc b) (int (/ c a))) :else (recur (inc a) b c))))   (println (filter semi-prime? (range 1 100)))  
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_SEDOL is   subtype SEDOL_String is String (1..6); type SEDOL_Sum is range 0..9;   function Check (SEDOL : SEDOL_String) return SEDOL_Sum is Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9); Sum  : Integer := 0; Ite...
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 ...
#C
C
#include <stdio.h>   inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0};   for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++;   for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++;   while(d-- && dig[x++] == cnt[d]);   return d == -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...
#FreeBASIC
FreeBASIC
Print "The first 50 self numbers are:" Dim As Boolean flag Dim As Ulong m, p, sum, number(), sum2 Dim As Ulong n = 0 Dim As Ulong num = 0 Dim As Ulong limit = 51 Dim As Ulong limit2 = 100000000 Dim As String strnum   Do n += 1 For m = 1 To n flag = True sum = 0 strnum = Str(m) Fo...
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 | ...
#Lua
Lua
function createSet(low,high,rt) local l,h = tonumber(low), tonumber(high) if l and h then local t = {low=l, high=h}   if type(rt) == "string" then if rt == "open" then t.contains = function(d) return low< d and d< high end elseif rt == "closed" then ...
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...
#D
D
import std.stdio, std.range, std.algorithm, std.traits, std.numeric, std.concurrency;   Generator!(ForeachType!R) nubBy(alias pred, R)(R items) { return new typeof(return)({ ForeachType!R[] seen;   OUTER: foreach (x; items) { foreach (y; seen) if (pred(x, y)) ...
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.
#C.23
C#
using System; using System.Diagnostics;   namespace sons { class Program { static void Main(string[] args) { for (int i = 1; i < 23; i++) Console.WriteLine(nonsqr(i));   for (int i = 1; i < 1000000; 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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   class Program { static void PrintCollection(IEnumerable<int> x) { Console.WriteLine(string.Join(" ", x)); } static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; Consol...
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Wren
Wren
import "meta" for Meta   class Test { construct new() {}   foo() { System.print("Foo called.") }   bar() { System.print("Bar called.") } }   var test = Test.new() for (method in ["foo", "bar"]) { Meta.eval("test.%(method)()") }
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#zkl
zkl
name:="len"; "this is a test".resolve(name)() //-->14
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...
#APL
APL
sieve2←{ b←⍵⍴1 b[⍳2⌊⍵]←0 2≥⍵:b p←{⍵/⍳⍴⍵}∇⌈⍵*0.5 m←1+⌊(⍵-1+p×p)÷p b ⊣ p {b[⍺×⍺+⍳⍵]←0}¨ m }   primes2←{⍵/⍳⍴⍵}∘sieve2
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#zkl
zkl
var [const] BN=Import("zklBigNum"); // libGMP p,s,i,n:=BN(1),BN(1), 0,0; do{ n+=1; s.nextPrime(); // in place, probabilistic p.mul(s); // in place if((p+1).probablyPrime() or (p-1).probablyPrime()){ println("%3d  %5d digits".fmt(n,p.len())); i+=1; } }while(i<20);