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/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
| #MATLAB_.2F_Octave | MATLAB / Octave |
funName = 'foo'; % generate function name
feval (funNAME, ...) % evaluation function with optional parameters
funName = 'a=atan(pi)'; % generate function name
eval (funName, 'printf(''Error\n'')')
|
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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface Example : NSObject
- (NSNumber *)foo;
@end
@implementation Example
- (NSNumber *)foo {
return @42;
}
@end
int main (int argc, const char *argv[]) {
@autoreleasepool {
id example = [[Example alloc] init];
SEL selector = @selector(foo); // or = NSSelectorFr... |
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... | #Agda | Agda |
-- imports
open import Data.Nat as ℕ using (ℕ; suc; zero; _+_; _∸_)
open import Data.Vec as Vec using (Vec; _∷_; []; tabulate; foldr)
open import Data.Fin as Fin using (Fin; suc; zero)
open import Function using (_∘_; const; id)
open import Data.List as List using (List; _∷_; [])
open import Data.May... |
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... | #PARI.2FGP | PARI/GP | n=0; P=1; forprime(p=2,, P*=p; n++; if(ispseudoprime(P+1) || ispseudoprime(P-1), print1(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... | #Perl | Perl | use ntheory ":all";
my $i = 0;
for (1..1e6) {
my $n = pn_primorial($_);
if (is_prime($n-1) || is_prime($n+1)) {
print "$_\n";
last if ++$i >= 20;
}
} |
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 | #Sidef | Sidef | func f(n {.is_prime}) {
n.prime**(n-1)
}
func f(n) {
n.th { .sigma0 == n }
}
say 20.of { f(_+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 | #Wren | Wren | import "/math" for Int
import "/big" for BigInt
import "/fmt" for Fmt
var MAX = 33
var primes = Int.primeSieve(MAX * 5)
System.print("The first %(MAX) terms in the sequence are:")
for (i in 1..MAX) {
if (Int.isPrime(i)) {
var z = BigInt.new(primes[i-1]).pow(i-1)
Fmt.print("$2d : $i", i, z)
} e... |
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... | #Kotlin | Kotlin | // version 1.0.6
fun<T : Comparable<T>> consolidateSets(sets: Array<Set<T>>): Set<Set<T>> {
val size = sets.size
val consolidated = BooleanArray(size) // all false by default
var i = 0
while (i < size - 1) {
if (!consolidated[i]) {
while (true) {
var intersects = 0
... |
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... | #Perl | Perl | use strict;
use warnings;
use ntheory 'divisors';
print "First 15 terms of OEIS: A005179\n";
for my $n (1..15) {
my $l = 0;
while (++$l) {
print "$l " and last if $n == divisors($l);
}
} |
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... | #Phix | Phix | with javascript_semantics
constant limit = 15
sequence res = repeat(0,limit)
integer found = 0, n = 1
while found<limit do
integer k = length(factors(n,1))
if k<=limit and res[k]=0 then
res[k] = n
found += 1
end if
n += 1
end while
printf(1,"The first %d terms are: %V\n",{limit,res})
|
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
| #PureBasic | PureBasic | a$="Rosetta code"
bit.i= 256
UseSHA2Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_SHA2, bit)
OpenConsole()
Print("[SHA2 "+Str(bit)+" bit] Text: "+a$+" ==> "+b$)
Input() |
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 ... | #REXX | REXX | /*REXX program finds and displays N numbers of the "anti─primes plus" sequence. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
idx= 1 ... |
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... | #PureBasic | PureBasic | a$="Rosetta Code"
UseSHA1Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_SHA1)
OpenConsole()
Print("[SHA1] Text: "+a$+" ==> "+b$)
Input() |
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... | #Python | Python | import hashlib
h = hashlib.sha1()
h.update(bytes("Ars longa, vita brevis", encoding="ASCII"))
h.hexdigest()
# "e640d285242886eb96ab80cbf858389b3df52f43" |
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... | #Lua | Lua |
-- map of character values to desired representation
local chars = setmetatable({[32] = "Spc", [127] = "Del"}, {__index = function(_, k) return string.char(k) end})
-- row iterator
local function iter(s,a)
a = (a or s) + 16
if a <= 127 then return a, chars[a] end
end
-- print loop
for i = 0, 15 do
for j... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Python | Python | def sierpinski(n):
d = ["*"]
for i in xrange(n):
sp = " " * (2 ** i)
d = [sp+x+sp for x in d] + [x+" "+x for x in d]
return d
print "\n".join(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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Order | Order | #include <order/interpreter.h>
#define ORDER_PP_DEF_8in_carpet ORDER_PP_FN( \
8fn(8X, 8Y, \
8if(8or(8is_0(8X), 8is_0(8Y)), \
8true, \
8let((8Q, 8quotient(8X, 3)) \
(8R, 8remainder(8X, 3)) \
(8S, 8quotient(8Y, 3)) \
(8T, 8remainder(8Y, 3)), \
8and... |
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 ... | #Arturo | Arturo | words: read.lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
pairs: []
loop words 'wrd [
if and? contains? words reverse wrd
wrd <> reverse wrd [
'pairs ++ @[@[wrd reverse wrd]]
print [wrd "-" reverse wrd]
]
]
unique 'pairs
print map 1..5 => [sample pairs] |
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 ... | #AutoHotkey | AutoHotkey | S := [], M := []
FileRead, dict, unixdict.txt
Loop, Parse, dict, `n, `r`n
{
r := Reverse(A_LoopField)
if (S[r])
M.Insert(r " / " A_LoopField)
else
S[A_LoopField] := 1
}
Loop, 5
Out .= "`t" M[A_Index] "`n"
MsgBox, % "5 Examples:`n" Out "`nTotal Pairs:`n`t" M.MaxIndex()
Reverse(s) {
Loop, Parse, s
r :=... |
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... | #PowerShell | PowerShell | # Simulated fast function
function a ( [boolean]$J ) { return $J }
# Simulated slow function
function b ( [boolean]$J ) { Sleep -Seconds 2; return $J }
# These all short-circuit and do not evaluate the right hand function
( a $True ) -or ( b $False )
( a $True ) -or ( b $True )
( a $False ) -and ( b $False ... |
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #Phix | Phix | with javascript_semantics
function replace_nth(string s, r)
string res = s
for i=1 to length(r) by 3 do
res[find_all(r[i],s)[r[i+1]-'0']] = r[i+2]
end for
return res
end function
?replace_nth("abracadabra","a1Aa2Ba4Ca5Db1Er2F")
-- Alternative version
function replace_nths(string s, sequence r)
... |
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #Python | Python | from collections import defaultdict
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
def trstring(oldstring, repdict):
seen, newchars = defaultdict(lambda:1, {}), []
for c in oldstring:
i = seen[c]
newchars.append(repdict[c][i] if c in repdict and i in rep... |
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... | #Factor | Factor |
USING: accessors io.sockets locals namespaces smtp ;
IN: scratchpad
:: send-mail ( f t c s b -- )
default-smtp-config "smtp.gmail.com" 587 <inet> >>server
t >>tls?
"my.gmail.address@gmail.com" "qwertyuiasdfghjk" <plain-auth>
>>auth \ smtp-config set-global <email> f >>from t >>to
c >>cc s >>subjec... |
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... | #Fantom | Fantom |
using email
class Mail
{
// create a client for sending email - add your own host/username/password
static SmtpClient makeClient ()
{
client := SmtpClient
{
host = "yourhost"
username = "yourusername"
password = "yourpassword"
}
return client
}
public static Void ma... |
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... | #AWK | AWK |
# syntax: GAWK -f SEMIPRIME.AWK
BEGIN {
main(0,100)
main(1675,1680)
exit(0)
}
function main(lo,hi, i) {
printf("%d-%d:",lo,hi)
for (i=lo; i<=hi; i++) {
if (is_semiprime(i)) {
printf(" %d",i)
}
}
printf("\n")
}
function is_semiprime(n, i,nf) {
nf = 0
for (i=2; ... |
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 ... | #ALGOL_68 | ALGOL 68 | BEGIN
# return TRUE if number is self describing, FALSE otherwise #
OP SELFDESCRIBING = ( INT number )BOOL:
BEGIN
[10]INT counts := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
INT n := number;
INT digits := 0;
# count the occurances of each digit #
... |
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... | #AWK | AWK |
# syntax: GAWK -f SELF_NUMBERS.AWK
# converted from Go (low memory example)
BEGIN {
print("HH:MM:SS INDEX SELF")
print("-------- ---------- ----------")
count = 0
digits = 1
i = 1
last_self = 0
offset = 9
pow = 10
while (count < 1E8) {
is_self = 1
start = max... |
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 | ... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
s1 := RealSet("(0,1]").union(RealSet("[0,2)"))
s2 := RealSet("[0,2)").intersect(RealSet("(1,2)"))
s3 := RealSet("[0,3)").difference(RealSet("(0,1)"))
s4 := RealSet("[0,3)").difference(RealSet("[0,1]"))
every s := s1|s2|s3|s4 do {
every n := 0 to 2 do
write(s.toS... |
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... | #BASIC256 | BASIC256 | function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function
for i = 101 to 999
if isPrime(i) then print string(i); " ";
next i
end |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Batch_File | Batch File |
@echo off
::Prime list using trial division
:: Unbounded (well, up to 2^31-1, but you'll kill it before :)
:: skips factors of 2 and 3 in candidates and in divisors
:: uses integer square root to find max divisor to test
:: outputs numbers in rows of 10 right aligned primes
setlocal enabledelayedexpansion
cls
ech... |
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.
| #BASIC | BASIC | DIM i AS Integer
DIM j AS Double
DIM found AS Integer
FUNCTION nonsqr (n AS Integer) AS Integer
nonsqr = n + INT(0.5 + SQR(n))
END FUNCTION
' Display first 22 values
FOR i = 1 TO 22
PRINT nonsqr(i); " ";
NEXT i
PRINT
' Check for squares up to one million
found = 0
FOR i = 1 TO 1000000
j = ... |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #ATS | ATS | (*------------------------------------------------------------------*)
#define ATS_DYNLOADFLAG 0
#include "share/atspre_staload.hats"
(*------------------------------------------------------------------*)
(* String hashing using XXH3_64bits from the xxHash suite. *)
#define ATS_EXTERN_PREFIX "hashsets_... |
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
| #Oforth | Oforth | 16 "sqrt" asMethod perform |
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
| #PARI.2FGP | PARI/GP | foo()=5;
eval(Str("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
| #Perl | Perl | package Example;
sub new {
bless {}
}
sub foo {
my ($self, $x) = @_;
return 42 + $x;
}
package main;
my $name = "foo";
print Example->new->$name(5), "\n"; # 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
| #Phix | Phix | with javascript_semantics
procedure Hello()
?"Hello"
end procedure
string erm = "Hemmm"
for i=3 to 5 do
erm[i]+=-1+(i=5)*3
end for
call_proc(routine_id(erm),{})
|
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... | #Agena | Agena | # Sieve of Eratosthenes
# generate and return a sequence containing the primes up to sieveSize
sieve := proc( sieveSize :: number ) :: sequence is
local sieve, result;
result := seq(); # sequence of primes - initially empty
create register sieve( sieveSize ); # "vector" to be sieved
sieve[ 1 ] := ... |
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... | #Phix | Phix | with javascript_semantics
include mpfr.e
constant limit = 9999,
flimit = iff(platform()=JS?15:20)
mpz {p,p1} = mpz_inits(2,1)
atom t0 = time()
integer found = 0, i
for n=1 to limit do
mpz_mul_si(p, p, get_prime(n))
for i=-1 to +1 do
mpz_add_si(p1, p, i)
if mpz_prime(p1) then
... |
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 | #zkl | zkl | var [const] BI=Import("zklBigNum"), pmax=25; // libGMP
p:=BI(1);
primes:=pmax.pump(List(0), p.nextPrime, "copy"); //-->(0,3,5,7,11,13,17,19,...)
fcn countDivisors(n){
count:=1;
while(n%2==0){ n/=2; count+=1; }
foreach d in ([3..*,2]){
q,r := n/d, n%d;
if(r==0){
dc:=0;
while(r==0){
dc+=... |
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... | #Lua | Lua | -- SUPPORT:
function T(t) return setmetatable(t, {__index=table}) end
function S(t) local s=T{} for k,v in ipairs(t) do s[v]=v end return s end
table.each = function(t,f,...) for _,v in pairs(t) do f(v,...) end end
table.copy = function(t) local s=T{} for k,v in pairs(t) do s[k]=v end return s end
table.keys = function... |
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... | #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 sequence(max_n=None):
n = 0
while True:
n += 1
ii = 0
if max_n is not ... |
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
| #Python | Python | >>> import hashlib
>>> hashlib.sha256( "Rosetta code".encode() ).hexdigest()
'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'
>>> |
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
| #R | R |
library(digest)
input <- "Rosetta code"
cat(digest(input, algo = "sha256", serialize = FALSE), "\n")
|
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 ... | #Ring | Ring |
# Project : ANti-primes
see "working..." + nl
see "wait for done..." + nl + nl
see "the first 15 Anti-primes Plus are:" + nl + nl
num = 1
n = 0
result = list(15)
while num < 16
n = n + 1
div = factors(n)
if div = num
result[num] = n
num = num + 1
ok
end
see "["
for n = 1 to... |
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 ... | #Ruby | Ruby | require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
seq = Enumerator.new do |y|
cur = 0
(1..).each do |i|
if num_divisors(i) == cur + 1 then
y << i
cur += 1
end
end
end
p seq.take(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 ... | #Sidef | Sidef | func n_divisors(n, from=1) {
from..Inf -> first_by { .sigma0 == n }
}
with (1) { |from|
say 15.of { from = n_divisors(_+1, from) }
} |
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... | #R | R |
library(digest)
input <- "Rosetta Code"
cat(digest(input, algo = "sha1", serialize = FALSE), "\n")
|
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... | #Racket | Racket |
#lang racket
(require file/sha1)
(sha1 (open-input-string "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... | #M2000_Interpreter | M2000 Interpreter |
Function ProduceAscii$ {
Document Ascii$="\"
DelUnicode$=ChrCode$(0x2421)
j=2
Print Ascii$;
For i=0 to 15
Print Hex$(i, .5);
Ascii$=Hex$(i, .5)
Next
For i=32 to 126
If pos>16 then
Ascii$={
}+Hex$(j, .5)
Print : Print Hex$(j, .5);: j++
End if
Print Chr$(i);
Ascii$=Chr$(i)
Next
Print DelUnic... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Quackery | Quackery | [ [ dup 1 &
iff char * else space
emit
1 >> dup while
sp again ]
drop ] is stars ( mask --> )
[ bit
1 over times
[ cr over i^ - times sp
dup stars
dup 1 << ^ ]
2drop ] is triangle ( order --> )
4 triangle |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Oz | Oz | declare
%% A carpet is a list of lines.
fun {NextCarpet Carpet}
{Flatten
[{Map Carpet XXX}
{Map Carpet X_X}
{Map Carpet XXX}
]}
end
fun {XXX X} X#X#X end
fun {X_X X} X#{Spaces {VirtualString.length X}}#X end
fun {Spaces N} if N == 0 then nil else & |{Spaces N-1} end end
... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #AWK | AWK |
# syntax: GAWK -f SEMORDNILAP.AWK unixdict.txt
{ arr[$0]++ }
END {
PROCINFO["sorted_in"] = "@ind_str_asc"
for (word in arr) {
rword = ""
for (j=length(word); j>0; j--) {
rword = rword substr(word,j,1)
}
if (word == rword) { continue } # palindrome
if (rword in arr) {
... |
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... | #Prolog | Prolog | short_circuit :-
( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(false, false)-> writeln('==> true'); writeln('==> false')) , n... |
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #Raku | Raku | sub mangle ($str is copy) {
$str.match(:ex, 'a')».from.map: { $str.substr-rw($_, 1) = 'ABaCD'.comb[$++] };
$str.=subst('b', 'E');
$str.substr-rw($_, 1) = 'F' given $str.match(:ex, 'r')».from[1];
$str
}
say $_, ' -> ', .&mangle given 'abracadabra';
say $_, ' -> ', .&mangle given 'abracadabra'.comb.pi... |
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #Vlang | Vlang | fn selectively_replace_chars(s string, char_map map[string]string) string {
mut bytes := s.bytes()
mut counts := {
'a': 0
'b': 0
'r': 0
}
for i := s.len - 1; i >= 0; i-- {
c := s[i].ascii_str()
if c in ['a', 'b', 'r'] {
bytes[i] = char_map[c][counts[c]... |
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... | #Fortran | Fortran | program sendmail
use ifcom
use msoutl
implicit none
integer(4) :: app, status, msg
call cominitialize(status)
call comcreateobject("Outlook.Application", app, status)
msg = $Application_CreateItem(app, olMailItem, status)
call $MailItem_SetTo(msg, "somebody@somewhere", status)
call... |
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... | #Go | Go | package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/smtp"
"os"
"strings"
)
type Message struct {
From string
To []string
Cc []string
Subject string
Content string
}
func (m Message) Bytes() (r []byte) {
to := strings.Join(m.To, ",")
cc := strings.Join(m.Cc, ",... |
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... | #BASIC | BASIC |
REM Semiprime
PRINT "Enter an integer ";
INPUT N
N = ABS(N)
Count = 0
IF N >= 2 THEN
FOR Factor = 2 TO N
NModFactor = N MOD Factor
WHILE NModFactor = 0
Count = Count + 1
N = N / Factor
NModFactor = N MOD Factor
WEND
NEXT Factor
ENDIF
IF Count = 2 THEN
PRINT "It is a semipri... |
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... | #Bracmat | Bracmat | semiprime=
m n a b
. 2^-64:?m
& 2*!m:?n
& !arg^!m
: (#%?a^!m*#%?b^!m|#%?a^!n&!a:?b)
& (!a.!b); |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- selfDescribes :: Int -> Bool
on selfDescribes(x)
set s to str(x)
set descripn to my str(|λ|(my groupBy(my eq, my sort(characters of s))) of my ¬
described(characters of "0123456789"))
1 = (offset of descripn in s... |
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 | C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef unsigned char bool;
#define TRUE 1
#define FALSE 0
#define MILLION 1000000
#define BILLION 1000 * MILLION
#define MAX_COUNT 2*BILLION + 9*9 + 1
void sieve(bool *sv) {
int n = 0, s[8], a, b, c, d, e, f, g, h, i, j;
for (a = 0; a < 2; ++a) {
... |
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 | ... | #J | J | has=: 1 :'(interval m)`:6'
ing=: `''
interval=: 3 :0
if.0<L.y do.y return.end.
assert. 5=#words=. ;:y
assert. (0 { words) e. ;:'[('
assert. (2 { words) e. ;:','
assert. (4 { words) e. ;:'])'
'lo hi'=.(1 3{0".L:0 words)
'cL cH'=.0 4{words e.;:'[]'
(lo&(<`<:@.cL) *. hi&(>`>:@.cH))ing
)
union=: 4 :'(x ... |
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... | #Befunge | Befunge | 2>:::"}"8*:*>`#@_48*:**2v
v_v#`\*:%*:*84\/*:*84::+<
v#>::48*:*/\48*:*%%!#v_1^
<^+1$_.#<5#<5#<+#<,#<<0:\ |
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... | #C | C |
#include<stdio.h>
int isPrime(unsigned int n)
{
unsigned int num;
if ( n < 2||!(n & 1))
return n == 2;
for (num = 3; num <= n/num; num += 2)
if (!(n % num))
return 0;
return 1;
}
int main()
{
unsigned int l,u,i,sum=0;
printf("Enter lower and upper bounds: ");
scanf("%ld%ld",&l,&u);
for(i=... |
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.
| #BASIC256 | BASIC256 | # Display first 22 values
print "The first 22 numbers generated by the sequence are : "
for i = 1 to 22
print nonSquare(i); " ";
next i
print
# Check for squares up to one million
found = false
for i = 1 to 1e6
j = sqrt(nonSquare(i))
if j = int(j) then
found = true
print i, " square number... |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #BBC_BASIC | BBC BASIC | FOR N% = 1 TO 22
S% = N% + SQR(N%) + 0.5
PRINT S%
NEXT
PRINT '"Checking...."
FOR N% = 1 TO 999999
S% = N% + SQR(N%) + 0.5
R% = SQR(S%)
IF S%/R% = R% STOP
NEXT
PRINT "No squares occur for n < 1000000" |
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... | #AutoHotkey | AutoHotkey | test(Set,element){
for i, val in Set
if (val=element)
return true
return false
}
Union(SetA,SetB){
SetC:=[], Temp:=[]
for i, val in SetA
SetC.Insert(val), Temp[val] := true
for i, val in SetB
if !Temp[val]
SetC.Insert(val)
return SetC
}
intersection(SetA,SetB){
SetC:=[], Temp:=[]
for i, val in S... |
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
| #PHP | PHP | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
// alternately:
echo call_user_func(array($example, $name), 5), "\n";
?> |
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
| #Picat | Picat | go =>
println("Function: Use apply/n"),
Fun = "fib",
A = 10,
% Convert F to an atom
println(apply(to_atom(Fun),A)),
nl,
println("Predicate: use call/n"),
Pred = "pyth",
call(Pred.to_atom,3,4,Z),
println(z=Z),
% Pred2 is an atom so it can be used directly with call/n.
Pred2 = pyth,
call(Pr... |
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
| #PicoLisp | PicoLisp | (send (expression) Obj arg1 arg2) |
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
| #Pike | Pike | string unknown = "format_nice";
object now = Calendar.now();
now[unknown](); |
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
| #PowerShell | PowerShell |
$method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name
$number = (1..9 | Get-Random) / 10
$result = [Math]::$method($number)
$output = [PSCustomObject]@{
Method = $method
Number = $number
Result = $result
}
$output | Format-List... |
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_60 | ALGOL 60 | comment Sieve of Eratosthenes;
begin
integer array t[0:1000];
integer i,j,k;
for i:=0 step 1 until 1000 do t[i]:=1;
t[0]:=0; t[1]:=0; i:=0;
for i:=i while i<1000 do
begin
for i:=i while i<1000 and t[i]=0 do i:=i+1;
if i<1000 then
begin
j:=2;
k:=j*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... | #Python | Python | import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
# Turn off warning on use of probabil... |
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... | #Racket | Racket | #lang racket
(require math/number-theory
racket/generator)
(define-syntax-rule (define/cache (name arg) body ...)
(begin
(define cache (make-hash))
(define (name arg)
(hash-ref! cache arg (lambda () body ...)))))
(define/cache (primorial n)
(if (zero? n)
1
(* (nth-prime (sub1 ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | reduce[x_] :=
Block[{pairs, unique},
pairs =
DeleteCases[
Subsets[Range@
Length@x, {2}], _?(Intersection @@ x[[#]] == {} &)];
unique = Complement[Range@Length@x, Flatten@pairs];
Join[Union[Flatten[x[[#]]]] & /@ pairs, x[[unique]]]]
consolidate[x__] := FixedPoint[reduce, {x}] |
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... | #Nim | Nim | proc consolidate(sets: varargs[set[char]]): seq[set[char]] =
if len(sets) < 2:
return @sets
var (r, b) = (@[sets[0]], consolidate(sets[1..^1]))
for x in b:
if len(r[0] * x) != 0:
r[0] = r[0] + x
else:
r.add(x)
r
echo consolidate({'A', 'B'}, {'C', 'D'})
echo consolidate({'A', 'B'}, {'B'... |
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... | #Quackery | Quackery | [ 0
[ 1+ 2dup
factors size =
until ]
nip ] is nfactors ( n --> n )
15 times [ i^ 1+ nfactors echo sp ] |
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... | #R | R | #Need to add 1 to account for skipping n. Not the most efficient way to count divisors, but quite clear.
divisorCount <- function(n) length(Filter(function(x) n %% x == 0, seq_len(n %/% 2))) + 1
smallestWithNDivisors <- function(n)
{
i <- 1
while(divisorCount(i) != n) i <- i + 1
i
}
print(sapply(1:15, smallestWit... |
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
| #Racket | Racket |
#lang racket/base
;; define a quick SH256 FFI interface, similar to the Racket's default
;; SHA1 interface
(require ffi/unsafe ffi/unsafe/define openssl/libcrypto
(only-in openssl/sha1 bytes->hex-string))
(define-ffi-definer defcrypto libcrypto)
(defcrypto SHA256_Init (_fun _pointer -> _int))
(defcrypto ... |
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
| #Raku | Raku | say sha256 "Rosetta code";
sub init(&f) {
map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int },
state @ = grep *.is-prime, 2 .. *;
}
sub infix:<m+> { ($^a + $^b) % 2**32 }
sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }
proto sha256($) returns Blob {*}
multi sha256(Str $str where all($str.ords) < 128) {
... |
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 ... | #Swift | Swift | // See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
// Deal with powers of 2 first
while n % 2 == 0 {
total += 1
n /= 2
}
// Odd prime factors up to the square root
var p = 3
while p * p <= n {
... |
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 ... | #Wren | Wren | import "/math" for Int
var limit = 24
var res = List.filled(limit, 0)
var next = 1
var n = 1
while (next <= limit) {
var k = Int.divisors(n).count
if (k == next) {
res[k-1] = n
next = next + 1
if (next > 4 && Int.isPrime(next)) n = 2.pow(next-1) - 1
}
n = n + 1
}
Syste... |
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... | #Raku | Raku | sub postfix:<mod2³²> { $^x % 2**32 }
sub infix:<⊕> { ($^x + $^y)mod2³² }
sub S { ($^x +< $^n)mod2³² +| ($x +> (32-$n)) }
my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D) },
-> \B,\C,\D { B +^ C +^ D },
-> \B,\C,\D { (B +& C) +| (B +& D) +| (C +& D) },
... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | StringRiffle[StringJoin@@@Transpose[Partition[ToString[#]<>": "<>Switch[#,32,"Spc ",127,"Del ",_,FromCharacterCode[#]<>" "]&/@Range[32,127],16]],"\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:
*
* *
* *
* * * *
* *
* * * *
... | #R | R | sierpinski.triangle = function(n) {
len <- 2^(n+1)
b <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2))
for (i in 1:(len/2))
{
cat(paste(ifelse(b,"*"," "),collapse=""),"\n")
n <- rep(FALSE,len+1)
n[which(b)-1]<-TRUE
n[which(b)+1]<-xor(n[which(b)+1],TRUE)
b <- n
}
}
sierpinski.triangle(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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PARI.2FGP | PARI/GP |
\\ Improved simple plotting using matrix mat (color and scaling added).
\\ Matrix should be filled with 0/1. 7/6/16 aev
iPlotmat(mat,clr)={
my(xz=#mat[1,],yz=#mat[,1],vx=List(),vy=vx,xmin,xmax,ymin,ymax,c=0.625);
for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, listput(vx,i); listput(vy,j))));
xmin=listmin(vx); x... |
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 ... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
DIM dict$(26000*2)
REM Load the dictionary, eliminating palindromes:
dict% = OPENIN("C:\unixdict.txt")
IF dict%=0 ERROR 100, "No dictionary file"
index% = 0
REPEAT
A$ = GET$#dict%
B$ = FNreverse(A$)
... |
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... | #PureBasic | PureBasic | Procedure a(arg)
PrintN(" # Called function a("+Str(arg)+")")
ProcedureReturn arg
EndProcedure
Procedure b(arg)
PrintN(" # Called function b("+Str(arg)+")")
ProcedureReturn arg
EndProcedure
OpenConsole()
For a=#False To #True
For b=#False To #True
PrintN(#CRLF$+"Calculating: x = a("+Str(a)+") And ... |
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #Wren | Wren | import "./seq" for Lst
import "./str" for Str
var s = "abracadabra"
var sl = s.toList
var ixs = Lst.indicesOf(sl, "a")[2]
var repl = "ABaCD"
for (i in 0..4) sl[ixs[i]] = repl[i]
s = sl.join()
s = Str.replace(s, "b", "E", 1)
s = Str.replace(s, "r", "F", 2, 1)
System.print(s) |
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #XPL0 | XPL0 | string 0;
proc Mangle(S);
char S, A, B, R;
[A:= "ABaCD"; B:= "Eb"; R:= "rF";
while S(0) do
[case S(0) of
^a: [S(0):= A(0); A:= A+1];
^b: [S(0):= B(0); B:= B+1];
^r: [S(0):= R(0); R:= R+1]
other [];
S:= S+1;
];
];
char S;
[S:= "abracadabra";
Text(0, S); Text(0, " -> "); Mangle... |
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... | #Groovy | Groovy |
import javax.mail.*
import javax.mail.internet.*
public static void simpleMail(String from, String password, String to,
String subject, String body) throws Exception {
String host = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable",true);
/* mai... |
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 | C | #include <stdio.h>
int semiprime(int n)
{
int p, f = 0;
for (p = 2; f < 2 && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == 2;
}
int main(void)
{
int i;
for (i = 2; i < 100; i++)
if (semiprime(i)) printf(" %d", i);
putchar('\n');
return 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
... | #11l | 11l | F char2value(c)
assert(c !C ‘AEIOU’, ‘No vowels’)
R Int(c, radix' 36)
V sedolweight = [1, 3, 1, 7, 3, 9]
F checksum(sedol)
V tmp = sum(zip(sedol, :sedolweight).map((ch, weight) -> char2value(ch) * weight))
R String((10 - (tmp % 10)) % 10)
V sedols =
|‘710889
B0YBKJ
406566
B0YBLH
228276
B0YBK... |
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 ... | #Arturo | Arturo | selfDescribing?: function [x][
digs: digits x
loop.with:'i digs 'd [
if d <> size select digs 'z [z=i]
-> return false
]
return true
]
print select 1..22000 => selfDescribing? |
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 ... | #AutoHotkey | AutoHotkey | ; The following directives and commands speed up execution:
#NoEnv
SetBatchlines -1
ListLines Off
Process, Priority,, high
MsgBox % 2020 ": " IsSelfDescribing(2020) "`n" 1337 ": " IsSelfDescribing(1337) "`n" 1210 ": " IsSelfDescribing(1210)
Loop 100000000
If IsSelfDescribing(A_Index)
list .= A_Index "`n"
Msg... |
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.2B.2B | C++ | #include <array>
#include <iomanip>
#include <iostream>
const int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
std::array<bool, MC + 1> SV;
void sieve() {
std::array<int, 10000> dS;
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
for (int c = 9, s = a + b; c >= 0; c--) {... |
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 | ... | #Java | Java | import java.util.Objects;
import java.util.function.Predicate;
public class RealNumberSet {
public enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN,
}
public static class RealSet {
private Double low;
private Double high;
private Predicate... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static void Main() {
Console.WriteLine(string.Join(" ", Primes(100)));
}
static IEnumerable<int> Primes(int limit) => Enumerable.Range(2, limit-1).Where(IsPrime);
static bool IsPrime(int n) => Enumerabl... |
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... | #C.2B.2B | C++ |
#include <math.h>
#include <iostream>
#include <iomanip>
bool isPrime( unsigned u ) {
if( u < 4 ) return u > 1;
if( /*!( u % 2 ) ||*/ !( u % 3 ) ) return false;
unsigned q = static_cast<unsigned>( sqrt( static_cast<long double>( u ) ) ),
c = 5;
while( c <= q ) {
if( !( u % c )... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.