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/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...
#Action.21
Action!
SET EndProg=*
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
#Bracmat
Bracmat
(task= ( oracle = (predicate="is made of green cheese") (generateTruth=.str$(!arg " " !(its.predicate) ".")) (generateLie=.str$(!arg " " !(its.predicate) "!")) ) & new$oracle:?SourceOfKnowledge & put $ "You may ask the Source of Eternal Wisdom ONE thing. Enter \"Truth\" or \"Lie\" on the next li...
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
#C.23
C#
using System;   class Example { public int foo(int x) { return 42 + x; } }   class Program { static void Main(string[] args) { var example = new Example(); var method = "foo";   var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 }); ...
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
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class Unknown.Example Extends %RegisteredObject {   Method Foo() { Write "This is foo", ! }   Method Bar() { Write "This is bar", ! }   }
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program cribleEras64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantes...
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...
#FreeBASIC
FreeBASIC
' version 23-10-2016 ' compile with: fbc -s console   #Define max 9999 ' max number for the sieve   #Include Once "gmp.bi"   Dim As mpz_ptr p, p1 p = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(p, 1) p1 = Allocate(Len(__mpz_struct)) : Mpz_init(p1)   Dim As UInteger i, n, x Dim As Byte prime(max)   ' Sieve of Erat...
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
d = Table[ Length[Divisors[n]], {n, 200000}]; t = {}; n = 0; ok = True; While[ok, n++; If[PrimeQ[n], AppendTo[t, Prime[n]^(n - 1)], c = Flatten[Position[d, n, 1, n]]; If[Length[c] >= n, AppendTo[t, c[[n]]], ok = False]]]; t
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Nim
Nim
import math, strformat import bignum   type Record = tuple[num, count: Natural]   template isOdd(n: Natural): bool = (n and 1) != 0   func isPrime(n: int): bool = let bi = newInt(n) result = bi.probablyPrime(25) != 0   proc findPrimes(limit: Natural): seq[int] {.compileTime.} = result = @[2] var isComposite =...
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...
#F.23
F#
let (|SeqNode|SeqEmpty|) s = if Seq.isEmpty s then SeqEmpty else SeqNode ((Seq.head s), Seq.skip 1 s)   let SetDisjunct x y = Set.isEmpty (Set.intersect x y)   let rec consolidate s = seq { match s with | SeqEmpty -> () | SeqNode (this, rest) -> let consolidatedRest = consolidate res...
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...
#J
J
  sieve=: 3 :0 range=. <. + i.@:|@:- tally=. y#0 for_i.#\tally do. j=. }:^:(y<:{:)i * 1 range >: <. y % i tally=. j >:@:{`[`]} tally end. /:~({./.~ {."1) tally,.i.#tally )  
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...
#Java
Java
import java.util.Arrays;   public class OEIS_A005179 {   static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } ...
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
#Oberon-2
Oberon-2
  MODULE SHA256; IMPORT Crypto:SHA256, Crypto:Utils, Strings, Out; VAR h: SHA256.Hash; str: ARRAY 128 OF CHAR;   BEGIN h := SHA256.NewHash(); h.Initialize; str := "Rosetta code"; h.Update(str,0,Strings.Length(str)); h.GetHash(str,0); Out.String("SHA256: ");Utils.PrintHex(str,0,h.size);Out.Ln END...
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
#Objeck
Objeck
  class ShaHash { function : Main(args : String[]) ~ Nil { hash:= Encryption.Hash->SHA256("Rosetta code"->ToByteArray()); str := hash->ToHexString()->ToLower(); str->PrintLine(); str->Equals("764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")->PrintLine(); } }  
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 ...
#Perl
Perl
use strict; use warnings; use ntheory 'divisors';   print "First 15 terms of OEIS: A069654\n"; my $m = 0; for my $n (1..15) { my $l = $m; while (++$l) { print("$l "), $m = $l, last if $n == divisors($l); } }
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 ...
#Phix
Phix
with javascript_semantics constant limit = 15 sequence res = repeat(0,limit) integer next = 1 atom n = 1 while next<=limit do integer k = length(factors(n,1)) if k=next then res[k] = n next += 1 if next>4 and is_prime(next) then n := power(2,next-1)-1 -- (-1 for +=1 next) ...
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...
#Oberon-2
Oberon-2
  MODULE SHA1; IMPORT Crypto:SHA1, Crypto:Utils, Strings, Out; VAR h: SHA1.Hash; str: ARRAY 128 OF CHAR; BEGIN h := SHA1.NewHash(); h.Initialize; str := "Rosetta Code"; h.Update(str,0,Strings.Length(str)); h.GetHash(str,0); Out.String("SHA1: ");Utils.PrintHex(str,0,h.size);Out.Ln END SHA1.  
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Sidef
Sidef
func dice5 { 1 + 5.rand.int }   func dice7 { loop { var d7 = ((5*dice5() + dice5() - 6) % 8); d7 && return d7; } }   var count7 = Hash.new;   var n = 1e6; n.times { count7{dice7()} := 0 ++ } count7.keys.sort.each { |k| printf("%s: %5.2f%%\n", k, 100*(count7{k}/n * 7 - 1)); }
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Tcl
Tcl
proc D5 {} {expr {1 + int(5 * rand())}}   proc D7 {} { while 1 { set d55 [expr {5 * [D5] + [D5] - 6}] if {$d55 < 21} { return [expr {$d55 % 7 + 1}] } } }
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#JavaScript
JavaScript
(() => {   "use strict";   // ------------------- ASCII TABLE -------------------   // asciiTable :: String const asciiTable = () => transpose( chunksOf(16)( enumFromTo(32)(127) .map(asciiEntry) ) ) .map( xs => x...
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: * * * * * * * * * * * * * * * ...
#Pop11
Pop11
define triangle(n); lvars k = 2**n, j, l, oline, nline; initv(2*k+3) -> oline; initv(2*k+3) -> nline; for l from 1 to 2*k+3 do 0 -> oline(l) ; endfor; 1 -> oline(k+2); 0 -> nline(1); 0 -> nline(2*k+3); for j from 1 to k do for l from 1 to 2*k+3 do printf(if oline(l) =...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Nascom_BASIC
Nascom BASIC
  10 REM Sierpinski carpet 20 CLS 30 LET RDR=3 40 LET S=3^RDR 50 FOR I=0 TO S-1 60 FOR J=0 TO S-1 70 LET X=J 80 LET Y=I 90 GOSUB 300 100 IF C THEN SET(J,I) 110 NEXT J 120 NEXT I 130 REM ** Set up machine code INKEY$ command 140 IF PEEK(1)<>0 THEN RESTORE 410 150 DOKE 4100,3328:FOR A=3328 TO 3342 STEP 2 160 READ B:DOKE ...
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...
#PARI.2FGP
PARI/GP
a(n)={ print(a"("n")"); a }; b(n)={ print("b("n")"); n }; or(A,B)={ a(A) || b(B) }; and(A,B)={ a(A) && b(B) };
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...
#AutoHotkey
AutoHotkey
sSubject:= "greeting" sText := "hello" sFrom := "ahk@rosettacode" sTo := "whomitmayconcern"   sServer := "smtp.gmail.com" ; specify your SMTP server nPort := 465 ; 25 bTLS := True ; False inputbox, sUsername, Username inputbox, sPassword, password   COM_Init() pmsg := COM_CreateObject("CDO.Message")...
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 | ...
#D
D
struct Set(T) { const pure nothrow bool delegate(in T) contains;   bool opIn_r(in T x) const pure nothrow { return contains(x); }   Set opBinary(string op)(in Set set) const pure nothrow if (op == "+" || op == "-") { static if (op == "+") return Set(x => contains(x) || se...
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...
#11l
11l
F prime(a) R !(a < 2 | any((2 .. Int(a ^ 0.5)).map(x -> @a % x == 0)))   F primes_below(n) R (0 .< n).filter(i -> prime(i))   print(primes_below(100))
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#11l
11l
F non_square(Int n) R n + Int(floor(1/2 + sqrt(n)))   print_elements((1..22).map(non_square))   F is_square(n) R fract(sqrt(n)) == 0   L(i) 1 .< 10 ^ 6 I is_square(non_square(i)) print(‘Square found ’i) L.break L.was_no_break print(‘No squares found’)
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...
#Ada
Ada
with ada.containers.ordered_sets, ada.text_io; use ada.text_io;   procedure set_demo is package cs is new ada.containers.ordered_sets (character); use cs;   function "+" (s : string) return set is (if s = "" then empty_set else Union(+ s(s'first..s'last - 1), To_Set (s(s'last))));   function "-" (s : Set) return st...
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
#Clojure
Clojure
  (import '[java.util Date]) (import '[clojure.lang Reflector])   (def date1 (Date.)) (def date2 (Date.)) (def method "equals")   ;; Two ways of invoking method "equals" on object date1 ;; using date2 as argument   ;; Way 1 - Using Reflector class ;; NOTE: The argument date2 is passed inside an array (Reflector/invokeM...
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
#Common_Lisp
Common Lisp
(funcall (intern "SOME-METHOD") my-object a few arguments)
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :object { :add @+ } local :method :add   !. object! method 1 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
#E
E
for name in ["foo", "bar"] { E.call(example, name, []) }
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...
#ABAP
ABAP
  PARAMETERS: p_limit TYPE i OBLIGATORY DEFAULT 100.   AT SELECTION-SCREEN ON p_limit. IF p_limit LE 1. MESSAGE 'Limit must be higher then 1.' TYPE 'E'. ENDIF.   START-OF-SELECTION. FIELD-SYMBOLS: <fs_prime> TYPE flag. DATA: gt_prime TYPE TABLE OF flag, gv_prime TYPE flag, gv_i TYPE i, ...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { one := big.NewInt(1) pm := big.NewInt(1) // primorial var px, nx int var pb big.Int // a scratch value primes(4000, func(p int64) bool { pm.Mul(pm, pb.SetInt64(p)) px++ if pb.Add(pm, one).ProbablyPrime(0) || ...
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Perl
Perl
use strict; use warnings; use bigint; use ntheory <nth_prime is_prime divisors>;   my $limit = 20;   print "First $limit terms of OEIS:A073916\n";   for my $n (1..$limit) { if ($n > 4 and is_prime($n)) { print nth_prime($n)**($n-1) . ' '; } else { my $i = my $x = 0; while (1) { ...
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Phix
Phix
with javascript_semantics constant LIMIT = 24 include mpfr.e mpz z = mpz_init() sequence fn = repeat(0,LIMIT) fn[1] = 1 integer k = 1 printf(1,"The first %d terms in the sequence are:\n",LIMIT) for i=1 to LIMIT do if is_prime(i) then mpz_ui_pow_ui(z,get_prime(i),i-1) printf(1,"%2d : %s\n",{i,mpz_...
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...
#Factor
Factor
USING: arrays kernel sequences sets ;   : comb ( x x -- x ) over empty? [ nip 1array ] [ dup pick first intersects? [ [ unclip ] dip union comb ] [ [ 1 cut ] dip comb append ] if ] if ;   : consolidate ( x -- x ) { } [ comb ] reduce ;
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...
#Go
Go
package main   import "fmt"   type set map[string]bool   var testCase = []set{ set{"H": true, "I": true, "K": true}, set{"A": true, "B": true}, set{"C": true, "D": true}, set{"D": true, "B": true}, set{"F": true, "G": true, "H": true}, }   func main() { fmt.Println(consolidate(testCase)) }   fun...
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...
#jq
jq
# divisors as an unsorted stream (without calling sqrt) def divisors: if . == 1 then 1 else . as $n | label $out | range(1; $n) as $i | ($i * $i) as $i2 | if $i2 > $n then break $out else if $i2 == $n then $i elif ($n % $i) == 0 then $i, ($n/$i) else empty end e...
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...
#Julia
Julia
using Primes   numfactors(n) = reduce(*, e+1 for (_,e) in factor(n); init=1)   A005179(n) = findfirst(k -> numfactors(k) == n, 1:typemax(Int))   println("The first 15 terms of the sequence are:") println(map(A005179, 1:15))  
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
#Objective-C
Objective-C
clang -o rosetta_sha256 rosetta_sha256.m /System/Library/Frameworks/Cocoa.framework/Cocoa
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
#OCaml
OCaml
let () = let s = "Rosetta code" in let digest = Sha256.string s in print_endline (Sha256.to_hex digest)
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 ...
#PL.2FI
PL/I
100H: /* FIND THE SMALLEST NUMBER > THE PREVIOUS ONE WITH EXACTLY N DIVISORS */   /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; /* CONSOLE OUTPUT ROUTINES */ PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PR$STRING: PROCEDURE( S...
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...
#OCaml
OCaml
$ ocaml -I +sha sha1.cma Objective Caml version 3.12.1   # Sha1.to_hex (Sha1.string "Rosetta Code") ;; - : string = "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
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...
#Octave
Octave
sprintf("%02x", SHA1(+"Rosetta Code"(:)))
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#VBA
VBA
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean 'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level. Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, Degr...
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#VBScript
VBScript
Option Explicit   function dice5 dice5 = int(rnd*5) + 1 end function   function dice7 dim j do j = 5 * dice5 + dice5 - 6 loop until j < 21 dice7 = j mod 7 + 1 end function
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...
#Jsish
Jsish
#!/usr/bin/env jsish   /* Show ASCII table, -showAll true to include control codes */ function showASCIITable(args:array|string=void, conf:object=void) { var options = { // Rosetta Code, Show ASCII table rootdir :'', // Root directory. showAll : false // include control cod...
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: * * * * * * * * * * * * * * * ...
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox 0 0 300 300   /F { 1 0 rlineto } def /+ { 120 rotate } def /- {-120 rotate } def /v {.5 .5 scale } def /^ { 2 2 scale } def /!0{ dup 1 sub dup -1 eq not } def   /X { !0 { v X + F - X - F + X ^ } { F } ifelse pop } def   0 1 8 { 300 300 scale 0 1 12 div moveto X + F + F fill showpag...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 1000 runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) public static DARK_SHADE = '\u2593' parse arg ordr filr . if ordr = '' | ordr = '.' then...
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...
#Pascal
Pascal
program shortcircuit(output);   function a(value: boolean): boolean; begin writeln('a(', value, ')'); a := value end;   function b(value:boolean): boolean; begin writeln('b(', value, ')'); b := value end;   procedure scandor(value1, value2: boolean); var result: boolean; begin {and} if a(value1) ...
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...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SOCKLIB"   Server$ = "smtp.gmail.com" From$ = "sender@somewhere" To$ = "recipient@elsewhere" CC$ = "another@nowhere" Subject$ = "Rosetta Code" Message$ = "This is a test of sending email."   PROCsendmail(Server$, From$, To$, CC$, "", Subject$, "",...
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...
#C
C
    #include <curl/curl.h> #include <string.h> #include <stdio.h>   #define from "<sender@duniya.com>" #define to "<addressee@gmail.com>" #define cc "<info@example.org>"   static const char *payload_text[] = { "Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n", "To: " to "\r\n", "From: " from " (Example Use...
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...
#11l
11l
F is_semiprime(=c) V a = 2 V b = 0 L b < 3 & c != 1 I c % a == 0 c /= a b++ E a++ R b == 2   print((1..100).filter(n -> is_semiprime(n)))
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 | ...
#Delphi
Delphi
  program Set_of_real_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TSet = TFunc<Double, boolean>;   function Union(a, b: TSet): TSet; begin Result := function(x: double): boolean begin Result := a(x) or b(x); end; end;   function Inter(a, b: TSet): TSet; begin Result := fun...
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...
#Action.21
Action!
BYTE FUNC IsPrime(CARD a) CARD i   IF a<=1 THEN RETURN (0) FI   FOR i=2 TO a/2 DO IF a MOD i=0 THEN RETURN (0) FI OD RETURN (1)   PROC PrintPrimes(CARD begin,end) BYTE notFirst CARD i   notFirst=0 FOR i=begin TO end DO IF IsPrime(i) THEN IF notFirst THEN Print("...
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...
#Ada
Ada
with Prime_Numbers, Ada.Text_IO, Ada.Command_Line;   procedure Sequence_Of_Primes is   package Integer_Numbers is new Prime_Numbers (Natural, 0, 1, 2); use Integer_Numbers;   Start: Natural := Natural'Value(Ada.Command_Line.Argument(1)); Stop: Natural := Natural'Value(Ada.Command_Line.Argument(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.
#Ada
Ada
with Ada.Numerics.Long_Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO;   procedure Sequence_Of_Non_Squares_Test is use Ada.Numerics.Long_Elementary_Functions;   function Non_Square (N : Positive) return Positive is begin return N + Positive (Long_Float'Rounding (Sqrt (Long_Float (N)))); end ...
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Aime
Aime
record union(record a, record b) { record c; r_copy(c, a); r_wcall(b, r_add, 1, 2, c); return c; }   record intersection(record a, record b) { record c; text s; for (s in a) { if (r_key(b, s)) { c[s] = 0; } } return c; }   record difference(record a, recor...
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
#Elena
Elena
import extensions;   class Example { foo(x) = x + 42; }   public program() { var example := new Example(); var methodSignature := "foo";   var invoker := new MessageName(methodSignature); var result := invoker(example,5);   console.printLine(methodSignature,"(",5,") = ",result) }
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
#Factor
Factor
USING: accessors kernel math prettyprint sequences words ; IN: rosetta-code.unknown-method-call   TUPLE: foo num ; C: <foo> foo GENERIC: add5 ( x -- y ) M: foo add5 num>> 5 + ;   42 <foo>  ! construct a foo "add" "5" append  ! construct a word name  ! must specify vocab to look up 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
#Forth
Forth
include FMS-SI.f include FMS-SILib.f   var x \ instantiate a class var object named x   \ Use a standard Forth string and evaluate it. \ This is equivalent to sending the !: message to object x 42 x s" !:" evaluate   x p: 42 \ send the print message ( p: ) to x to verify the contents    
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
#Go
Go
package main   import ( "fmt" "reflect" )   type example struct{}   // the method must be exported to be accessed through reflection. func (example) Foo() int { return 42 }   func main() { // create an object with a method var e example // get the method by name m := reflect.ValueOf(e).Metho...
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...
#ACL2
ACL2
(defun nats-to-from (n i) (declare (xargs :measure (nfix (- n i)))) (if (zp (- n i)) nil (cons i (nats-to-from n (+ i 1)))))   (defun remove-multiples-up-to-r (factor limit xs i) (declare (xargs :measure (nfix (- limit i)))) (if (or (> i limit) (zp (- limit i)) (zp factor...
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...
#Haskell
Haskell
import Data.List (scanl1, elemIndices, nub)   primes :: [Integer] primes = 2 : filter isPrime [3,5 ..]   isPrime :: Integer -> Bool isPrime = isPrime_ primes where isPrime_ :: [Integer] -> Integer -> Bool isPrime_ (p:ps) n | p * p > n = True | n `mod` p == 0 = False | otherwise = isPrime_ ps...
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Python
Python
  def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs))     def is_prime(n): return len(divisors(n)) == 2     def primes(): ii = 1 while True: i...
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...
#Haskell
Haskell
import Data.List (intersperse, intercalate) import qualified Data.Set as S   consolidate :: Ord a => [S.Set a] -> [S.Set a] consolidate = foldr comb [] where comb s_ [] = [s_] comb s_ (s:ss) | S.null (s `S.intersection` s_) = s : comb s_ ss | otherwise = comb (s `S.union` s_) ss   -- TESTS ---...
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...
#Kotlin
Kotlin
// Version 1.3.21   const val MAX = 15   fun countDivisors(n: Int): Int { var count = 0 var i = 1 while (i * i <= n) { if (n % i == 0) { count += if (i == n / i) 1 else 2 } i++ } return count }   fun main() { var seq = IntArray(MAX) println("The first $MAX...
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
#OS_X_sha256sum
OS X sha256sum
echo -n 'Rosetta code' | sha256sum
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
#PARI.2FGP
PARI/GP
sha256(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha256sum|cut -d' ' -f1`)\"")
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 ...
#PL.2FM
PL/M
100H: /* FIND THE SMALLEST NUMBER > THE PREVIOUS ONE WITH EXACTLY N DIVISORS */   /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; /* CONSOLE OUTPUT ROUTINES */ PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PR$STRING: PROCEDURE( S...
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...
#PARI.2FGP
PARI/GP
sha1(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha1sum|cut -d' ' -f1`)\"")
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...
#Pascal
Pascal
program RosettaSha1; uses sha1; var d: TSHA1Digest; begin d:=SHA1String('Rosetta Code'); WriteLn(SHA1Print(d)); end.
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Verilog
Verilog
    /////////////////////////////////////////////////////////////////////////////// /// seven_sided_dice_tb : (testbench) /// /// Check the distribution of the output of a seven sided dice circuit /// ////////////////////////////////////////////////////////////////////////////...
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...
#jq
jq
  # Pretty printing def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def nwise($n): def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end; n;   def table($ncols; $colwidth): nwise($ncols) | map(lpad($colwidth)) | join(" ");   # transposed table def ttable($rows): [nwise($rows)] ...
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: * * * * * * * * * * * * * * * ...
#PowerShell
PowerShell
function triangle($o) { $n = [Math]::Pow(2, $o) $line = ,' '*(2*$n+1) $line[$n] = '█' $OFS = '' for ($i = 0; $i -lt $n; $i++) { Write-Host $line $u = '█' for ($j = $n - $i; $j -lt $n + $i + 1; $j++) { if ($line[$j-1] -eq $line[$j+1]) { $t = ' ' ...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Nim
Nim
import math   proc inCarpet(x, y: int): bool = var x = x var y = y while true: if x == 0 or y == 0: return true if x mod 3 == 1 and y mod 3 == 1: return false x = x div 3 y = y div 3   proc carpet(n: int) = for i in 0 ..< 3^n: for j in 0 ..< 3^n: stdout.write if inCarpet(i,...
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...
#Perl
Perl
sub a { print 'A'; return $_[0] } sub b { print 'B'; return $_[0] }   # Test-driver sub test { for my $op ('&&','||') { for (qw(1,1 1,0 0,1 0,0)) { my ($x,$y) = /(.),(.)/; print my $str = "a($x) $op b($y)", ': '; eval $str; print "\n"; } } }   # Test and display test();
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...
#C.23
C#
  static void Main(string[] args) { //First of all construct the SMTP client   SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details SMTP.EnableSsl = true; //Required for gmail, may not for your provider, if your provi...
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...
#C.2B.2B
C++
// on Ubuntu: sudo apt-get install libpoco-dev // or see http://pocoproject.org/ // compile with: g++ -Wall -O3 send-mail-cxx.C -lPocoNet -lPocoFoundation   #include <cstdlib> #include <iostream> #include <Poco/Net/SMTPClientSession.h> #include <Poco/Net/MailMessage.h>   using namespace Poco::Net;   int main (int argc,...
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...
#360_Assembly
360 Assembly
* Semiprime 14/03/2017 SEMIPRIM CSECT USING SEMIPRIM,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Action.21
Action!
BYTE FUNC IsSemiPrime(INT n) INT a,b   a=2 b=0 WHILE b<3 AND n#1 DO IF n MOD a=0 THEN n==/a b==+1 ELSE a==+1 FI OD IF b=2 THEN RETURN(1) FI RETURN(0)   PROC Main() INT i   PrintE("Semiprimes:") FOR i=1 TO 500 DO IF IsSemiPrime(i) THEN PrintI(i) Put(32) FI ...
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 | ...
#EchoLisp
EchoLisp
  (lib 'match) ;; reader-infix macros   (reader-infix '∈ ) (reader-infix '∩ ) (reader-infix '∪ ) (reader-infix '⊖ ) ;; set difference   (define-syntax-rule (∈ x a) (a x)) (define-syntax-rule (∩ a b) (lambda(x) (and ( a x) (b x)))) (define-syntax-rule (∪ a b) (lambda(x) (or ( a x) (b x)))) (define-syntax-rule (⊖ a b) (l...
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...
#ALGOL_68
ALGOL 68
# is prime PROC from the primality by trial division task # MODE ISPRIMEINT = INT; PROC is prime = ( ISPRIMEINT p )BOOL: IF p <= 1 OR ( NOT ODD p AND p/= 2) THEN FALSE ELSE BOOL prime := TRUE; FOR i FROM 3 BY 2 TO ENTIER sqrt(p) WHILE prime := p MOD i /= 0 DO SKIP OD; prime FI; # end of code...
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.
#ALGOL_68
ALGOL 68
PROC non square = (INT n)INT: n + ENTIER(0.5 + sqrt(n));   main: (   # first 22 values (as a list) has no squares: # FOR i TO 22 DO print((whole(non square(i),-3),space)) OD; print(new line);   # The following check shows no squares up to one million: # FOR i TO 1 000 000 DO REA...
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.
#ALGOL_W
ALGOL W
begin  % check values of the function: f(n) = n + floor(1/2 + sqrt(n))  %  % are not squares  %   integer procedure f ( integer value n ) ; begin n + entier( 0.5 + sqrt( n ) ) end f ;   logical noSquares;    % first 22 values...
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...
#ALGOL_68
ALGOL 68
# sets using associative arrays # # include the associative array code for string keys and values # PR read "aArray.a68" PR   # adds the elements of s to the set a, # # the elements will have empty strings for values ...
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
#Groovy
Groovy
class Example { def foo(value) { "Invoked with '$value'" } }   def example = new Example() def method = "foo" def arg = "test value"   assert "Invoked with 'test value'" == example."$method"(arg)
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
#Icon_and_Unicon
Icon and Unicon
procedure main() x := foo() # create object x.m1() # static call of m1 method # two examples where the method string can be dynamically constructed ... "foo_m1"(x) # ... need to know class name and method name to construct name x.__m["m1"] # ... general method (better) end   class foo(a,b,...
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
#Io
Io
Example := Object clone Example foo := method(x, 42+x)   name := "foo" Example clone perform(name,5) println // prints "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
#J
J
sum =: +/ prod =: */ count =: #   nameToDispatch =: 'sum' NB. pick a name already defined   ". nameToDispatch,' 1 2 3' 6 nameToDispatch~ 1 2 3 6 nameToDispatch (128!:2) 1 2 3 6   nameToDispatch =: 'count' NB. pick another name   ". nameToDispatch,' 1 2 3' 3 nameToDispatch~ 1 2 3 3 n...
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...
#Action.21
Action!
DEFINE MAX="1000"   PROC Main() BYTE ARRAY t(MAX+1) INT i,j,k,first   FOR i=0 TO MAX DO t(i)=1 OD   t(0)=0 t(1)=0   i=2 first=1 WHILE i<=MAX DO IF t(i)=1 THEN IF first=0 THEN Print(", ") FI PrintI(i) FOR j=2*i TO MAX STEP i DO t(j)=0 OD ...
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...
#J
J
primoprim=: [: I. [: +./ 1 p: (1,_1) +/ */\@:p:@i.
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...
#Java
Java
import java.math.BigInteger;   public class PrimorialPrimes {   final static int sieveLimit = 1550_000; static boolean[] notPrime = sieve(sieveLimit);   public static void main(String[] args) {   int count = 0; for (int i = 1; i < 1000_000 && count < 20; i++) { BigInteger b = pri...
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#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 = 20;   my @primes = grep { .is-prime }, 1..*; @primes[$limit]; # prime the array. SCNR   put "First $limit terms of OEIS:A073916"; put (1..$lim...
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...
#J
J
consolidate=:4 :0/ b=. y 1&e.@e.&> x (1,-.b)#(~.;x,b#y);y )
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...
#Java
Java
import java.util.*;   public class SetConsolidation {   public static void main(String[] args) { List<Set<Character>> h1 = hashSetList("AB", "CD"); System.out.println(consolidate(h1));   List<Set<Character>> h2 = hashSetList("AB", "BD"); System.out.println(consolidateR(h2));   ...
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...
#Maple
Maple
  with(NumberTheory):   countDivisors := proc(x::integer) return numelems(Divisors(x)); end proc:   sequenceValue := proc(x::integer) local count: for count from 1 to infinity while not countDivisors(count) = x do end: return count; end proc:   seq(sequenceValue(number), number = 1..15);    
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Take[SplitBy[SortBy[{DivisorSigma[0, #], #} & /@ Range[100000], First], First][[All, 1]], 15] // Grid
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
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ; use Digest::SHA qw( sha256_hex ) ;   my $digest = sha256_hex my $phrase = "Rosetta code" ; print "SHA-256('$phrase'): $digest\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
#Phix
Phix
include builtins\sha256.e function asHex(string s) string res = "" for i=1 to length(s) do res &= sprintf("%02X",s[i]) end for return res end function ?asHex(sha256("Rosetta code"))