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_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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #Ada | Ada | generic
type Element is (<>);
with function Image(E: Element) return String;
package Set_Cons is
Β
type Set is private;
Β
-- constructor and manipulation functions for type Set
function "+"(E: Element) return Set;
function "+"(Left, Right: Element) return Set;
function "+"(Left: Set; Right: Element) return Set;
function "-"(Left: Set; Right: Element) return Set;
Β
-- compare, unite or output a Set
function Nonempty_Intersection(Left, Right: Set) return Boolean;
function Union(Left, Right: Set) return Set;
function Image(S: Set) return String;
Β
type Set_Vec is array(Positive range <>) of Set;
Β
-- output a Set_Vec
function Image(V: Set_Vec) return String;
Β
private
type Set is array(Element) of Boolean;
Β
end Set_Cons; |
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 n divisorsββ
See also
OEIS:A005179
| #APL | APL | ((0+.=β³|β’)Β¨β(β³2Γ·β¨2β*)β³β³)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 n divisorsββ
See also
OEIS:A005179
| #Arturo | Arturo | firstNumWithDivisors: function [n][
i: 0
while ΓΈ [
if n = size factors i -> return i
i: i+1
]
]
Β
print map 1..15 => firstNumWithDivisors |
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
| #Groovy | Groovy | def sha256Hash = { text ->
java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes)
.collect { String.format("%02x", it) }.join('')
} |
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 number with exactly n divisorsββ
| #AutoHotkey | AutoHotkey | MAX := 15
next := 1, i := 1
while (next <= MAX)
if (next = countDivisors(A_Index))
Res.= A_Index ", ", next++
MsgBoxΒ % "The first " MAX " terms of the sequence are:`n" Trim(res, ", ")
return
Β
countDivisors(n){
while (A_Index**2 <= n)
ifΒ !Mod(n, A_Index)
count += (A_Index = n/A_Index)Β ? 1Β : 2
return count
} |
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 number with exactly n divisorsββ
| #AWK | AWK | Β
# syntax: GAWK -f SEQUENCE_SMALLEST_NUMBER_GREATER_THAN_PREVIOUS_TERM_WITH_EXACTLY_N_DIVISORS.AWK
# converted from Kotlin
BEGIN {
limit = 15
printf("firstΒ %d terms:",limit)
n = 1
while (n <= limit) {
if (n == count_divisors(++i)) {
printf("Β %d",i)
n++
}
}
printf("\n")
exit(0)
}
function count_divisors(n, count,i) {
for (i=1; i*i<=n; i++) {
if (n % i == 0) {
count += (i == n / i) ? 1 : 2
}
}
return(count)
}
Β |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Haxe | Haxe | import haxe.crypto.Sha1;
Β
class Main {
static function main() {
var sha1 = Sha1.encode("Rosetta Code");
Sys.println(sha1);
}
} |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #J | J | require '~addons/ide/qt/qt.ijs'
getsha1=: 'sha1'&gethash_jqtide_
getsha1 'Rosetta Code'
48c98f7e5a6e736d790ab740dfc3f51a61abe2b5 |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Liberty_BASIC | Liberty BASIC | Β
n=1000000 '1000000 would take several minutes
print "Testing ";n;" times"
if not(check(n, 0.05)) then print "Test failed" else print "Test passed"
end
Β
'function check(n, delta) is defined at
'http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive#Liberty_BASIC
Β
function GENERATOR()
'GENERATOR = int(rnd(0)*10) '0..9
'GENERATOR = 1+int(rnd(0)*5) '1..5: dice5
Β
'dice7()
do
temp =dice5() *5 +dice5() -6
loop until temp <21
GENERATOR =( temp mod 7) +1
Β
end function
Β
function dice5()
dice5=1+int(rnd(0)*5) '1..5: dice5
end function
Β |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Lua | Lua | dice5 = function() return math.random(5) end
Β
function dice7()
x = dice5() * 5 + dice5() - 6
if x > 20 then return dice7() end
return x%7 + 1
end |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #REXX | REXX | /*REXX program finds and displays various kinds of sexy and unsexy primes less than N.*/
parse arg N endU end2 end3 end4 end5 . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 1000035 - 1 /*Not specified? Then use the default.*/
if endU=='' | endU=="," then endU= 10 /* " " " " " " */
if end2=='' | end2=="," then end2= 5 /* " " " " " " */
if end3=='' | end3=="," then end3= 5 /* " " " " " " */
if end4=='' | end4=="," then end4= 5 /* " " " " " " */
if end5=='' | end5=="," then end4= 5 /* " " " " " " */
call genSq /*gen some squares for the DO k=7 UNTIL*/
call genPx /* " prime (@.) & sexy prime (X.) array*/
call genXU /*gen lists, types of sexy Ps, unsexy P*/
call getXs /*gen lists, last # of types of sexy Ps*/
@sexy= ' sexy prime' /*a handy literal for some of the SAYs.*/
w2= words( translate(x2,, '~') ); y2= words(x2) /*count #primes in the sexy pairs. */
w3= words( translate(x3,, '~') ); y3= words(x3) /* " " " " " " triplets. */
w4= words( translate(x4,, '~') ); y4= words(x4) /* " " " " " " quadruplets*/
w5= words( translate(x5,, '~') ); y5= words(x5) /* " " " " " " quintuplets*/
say 'There are ' commas(w2%2) @sexy "pairs less than " Nc
say 'The last ' commas(end2) @sexy "pairs are:"; say subword(x2, max(1,y2-end2+1))
say
say 'There are ' commas(w3%3) @sexy "triplets less than " Nc
say 'The last ' commas(end3) @sexy "triplets are:"; say subword(x3, max(1,y3-end3+1))
say
say 'There are ' commas(w4%4) @sexy "quadruplets less than " Nc
say 'The last ' commas(end4) @sexy "quadruplets are:"; say subword(x4, max(1,y4-end4+1))
say
say 'There is ' commas(w5%5) @sexy "quintuplet less than " Nc
say 'The last ' commas(end4) @sexy "quintuplet are:"; say subword(x5, max(1,y5-end4+1))
say
say 'There are ' commas(s1) " sexy primes less than " Nc
say 'There are ' commas(u1) " unsexy primes less than " Nc
say 'The last ' commas(endU) " unsexy primes are: " subword(u, max(1,u1-endU+1))
exit /*stick a fork in it, we're all done. */
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
commas: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, "M")
e= verify(n, #'0', , verify(n, #"0.", 'M') ) - 4
do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
genSQ: do i=17 by 2 until i**2 > N+7; s.i= i**2; end; return /*S used for square roots*/
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
genPx: @.=; #= 0; Β !.= 0. /*P array; P count; sexy P array*/
if N>1 then do; #= 1; @.1= 2; Β !.2= 1; end /*count of primes found (so far)*/
x.=!.; LPs=3 5 7 11 13 17 /*sexy prime array; low P list.*/
do j=3 by 2 to N+6 /*start in the cellar & work up.*/
if j<19 then if wordpos(j, LPs)==0 then iterate
else do; #= #+1; @.#= j; Β !.j= 1; b= j - 6
ifΒ !.b then x.b= 1; iterate
end
if j// 3 ==0 then iterate /* Β·Β·Β· and eliminate multiples of 3.*/
parse var j '' -1 _ /* get the rightmost digit of J. */
if _ ==5 then iterate /* Β·Β·Β· and eliminate multiples of 5.*/
if j// 7 ==0 then iterate /* Β·Β·Β· " " " " 7.*/
if j//11 ==0 then iterate /* Β·Β·Β· " " " " 11.*/
if j//13 ==0 then iterate /* Β·Β·Β· " " " " 13.*/
do k=7 until s._ > j; _= @.k /*Γ· by primes starting at 7th prime. */
if j // _ == 0 then iterate j /*get the remainder of jΓ·@.k ___ */
end /*k*/ /*divide up through & including β J */
if j<=N then do; #= #+1; @.#= j; end /*bump P counter; assign prime to @.*/
Β !.j= 1 /*define Jth number as being prime.*/
b= j - 6 /*B: lower part of a sexy prime pair?*/
ifΒ !.b then do; x.b=1; if j<=N then x.j=1; end /*assign (both partsΒ ?) sexy Ps.*/
end /*j*/; return
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
genXU: u= 2; Nc=commas(N+1); s= /*1st unsexy prime; add commas to N+1*/
say 'There are ' commas(#) " primes less than " Nc; say
do k=2 for #-1; p= @.k; if x.p then s=s p /*if sexy prime, add it to list*/
else u= u p /* " unsexy " " " " " */
end /*k*/ /* [β] traispe through odd Ps. */
s1= words(s); u1= words(u); return /*# of sexy primes; # unsexy primes.*/
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
getXs: x2=; do k=2 for #-1; [email protected]; if \x.p then iterate /*build sexy prime list. */
b=p- 6; if \x.b then iterate; x2=x2 b'~'p
end /*k*/
x3=; do k=2 for #-1; [email protected]; if \x.p then iterate /*build sexy P triplets. */
b=p- 6; if \x.b then iterate
t=p-12; if \x.t then iterate; x3=x3 t'~' || b"~"p
end /*k*/
x4=; do k=2 for #-1; [email protected]; if \x.p then iterate /*build sexy P quads. */
b=p- 6; if \x.b then iterate
t=p-12; if \x.t then iterate
q=p-18; if \x.q then iterate; x4=x4 q'~'t"~" || b'~'p
end /*k*/
x5=; do k=2 for #-1; [email protected]; if \x.p then iterate /*build sexy P quints. */
b=p- 6; if \x.b then iterate
t=p-12; if \x.t then iterate
q=p-18; if \x.q then iterate
v=p-24; if \x.v then iterate; x5=x5 v'~'q"~"t'~' || b"~"p
end /*k*/; return |
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
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Free_Pascal | Free Pascal | // The FPC (FreePascal compiler) discards the program header
// (except in ISO-compliant βcompiler modesβ).
program showAsciiTable(output);
Β
const
columnsTotal = 6;
Β
type
// The hash indicates a char-data type.
asciiCharacter = #32..#127;
asciiCharacters = set of asciiCharacter;
Β
var
character: asciiCharacter;
characters: asciiCharacters;
column, line: integer;
begin
// characters needs to be initialized,
// because the next `include` below
// will _read_ the value `characters`.
// Reading _unintialized_ values, however,
// is considered bad practice in Pascal.
characters := [];
// `div` denotes integer division in Pascal,
// that means the result will be an _integer_-value.
line := (ord(high(asciiCharacter)) - ord(low(asciiCharacter)))
div columnsTotal + 1;
// Note: In Pascal for-loop limits are _inclusive_.
for column := 0 to columnsTotal do
begin
// This is equivalent to
// charactersΒ := characters + [β¦];
// i.e. the union of two sets.
include(characters, chr(ord(low(asciiCharacter)) + column * line));
end;
Β
for line := line downto 1 do
begin
// the for..in..do statement is an Extended Pascal extension
for character in characters do
begin
// `:6` specifies minimum width of argument
// [only works for write/writeLn/writeStr]
write(ord(character):6, 'Β : ', character);
end;
// emit proper newline character on `output`
writeLn;
Β
// `characters` is evaluated prior entering the loop,
// not every time an iteration finished.
for character in characters do
begin
// These statements are equivalent to
// charactersΒ := characters + [character];
// charactersΒ := characters - [succ(character)];
// respectively, but shorter to write,
// i.e. less susceptible to spelling mistakes.
exclude(characters, character);
include(characters, succ(character));
end;
end;
end. |
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:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #PARI.2FGP | PARI/GP | Sierpinski(n)={
my(s=2^n-1);
forstep(y=s,0,-1,
for(i=1,y,print1(" "));
for(x=0,s-y,
print1(if(bitand(x,y)," ","*"))
);
print()
)
};
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the Β # Β character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Β Sierpinski triangle
| #J | J | N=:3
(a:(<1;1)}3 3$<)^:N' ' |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions Β a Β and Β b Β return boolean values, Β and further, the execution of function Β b Β takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #Lua | Lua | function a(i)
print "Function a(i) called."
return i
end
Β
function b(i)
print "Function b(i) called."
return i
end
Β
i = true
x = a(i) and b(i); print ""
y = a(i) or b(i); print ""
Β
i = false
x = a(i) and b(i); print ""
y = a(i) or b(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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #Maple | Maple | aΒ := proc(bool)
printf("a is called->%s\n", bool):
return bool:
end proc:
bΒ := proc(bool)
printf("b is called->%s\n", bool):
return bool:
end proc:
for i in [true, false] do
for j in [true, false] do
printf("calculating xΒ := a(i) and b(j)\n"):
xΒ := a(i) and b(j):
printf("calculating xΒ := a(i) or b(j)\n"):
yΒ := a(i) or b(j):
od:
od: |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Phix | Phix | with javascript_semantics
function comb(sequence pool, integer needed, sequence res={}, integer done=0, sequence chosen={})
if needed=0 then -- got a full set
sequence {a,b,c} = chosen
if not find_any({3,5,6},flatten(sq_or_bits(sq_or_bits(a,b),c))) then
res = append(res,chosen)
end if
elsif done+needed<=length(pool) then
-- get all combinations with and without the next item:
done += 1
res = comb(pool,needed-1,res,done,append(deep_copy(chosen),pool[done]))
res = comb(pool,needed,res,done,chosen)
end if
return res
end function
constant m124 = {1,2,4}
function card(integer n)
--returns the nth card (n is 1..81, res is length 4 of 1/2/4)
n -= 1
sequence res = repeat(0,4)
for i=1 to 4 do
res[i] = m124[remainder(n,3)+1]
n = floor(n/3)
end for
return res
end function
constant colours = {"red", "green", 0, "purple"},
symbols = {"oval", "squiggle", 0, "diamond"},
numbers = {"one", "two", 0, "three"},
shades = {"solid", "open", 0, "striped"}
procedure print_cards(sequence hand, sequence cards)
for i=1 to length(cards) do
integer {c,m,n,g} = cards[i],
id = find(cards[i],hand)
printf(1,"%3d:Β %-7sΒ %-9sΒ %-6sΒ %s\n",{id,colours[c],symbols[m],numbers[n],shades[g]})
end for
printf(1,"\n")
end procedure
procedure play(integer cards=9, integer sets=4)
integer deals = 1
while 1 do
sequence deck = shuffle(tagset(81))
sequence hand = deck[1..cards]
for i=1 to length(hand) do
hand[i] = card(hand[i])
end for
sequence res = comb(hand,3)
if length(res)=sets then
printf(1,"dealtΒ %d cards (%d deals)\n",{cards,deals})
print_cards(hand,hand)
printf(1,"withΒ %d sets\n",{sets})
for i=1 to sets do
print_cards(hand,res[i])
end for
exit
end if
deals += 1
end while
end procedure
play()
--play(12,6)
--play(9,6)
|
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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #Aime | Aime | display(list l)
{
for (integer i, record r in l) {
text u, v;
Β
o_text(iΒ ? ", {"Β : "{");
for (u in r) {
o_(v, u);
v = ", ";
}
o_text("}");
}
Β
o_text("\n");
}
Β
intersect(record r, record u)
{
trap_q(r_vcall, r, r_put, 1, record().copy(u), 0);
}
Β
consolidate(list l)
{
for (integer i, record r in l) {
integer j;
Β
j = i - ~l;
while (j += 1) {
if (intersect(r, l[j])) {
r.wcall(r_add, 1, 2, l[j]);
l.delete(i);
i -= 1;
break;
}
}
}
Β
l;
}
Β
R(...)
{
ucall.2(r_put, 1, record(), 0);
}
Β
main(void)
{
display(consolidate(list(R("A", "B"), R("C", "D"))));
display(consolidate(list(R("A", "B"), R("B", "D"))));
display(consolidate(list(R("A", "B"), R("C", "D"), R("D", "B"))));
display(consolidate(list(R("H", "I", "K"), R("A", "B"), R("C", "D"),
R("D", "B"), R("F", "G", "K"))));
Β
0;
} |
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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #AutoHotkey | AutoHotkey | SetConsolidation(sets){
arr2 := [] , arr3 := [] , arr4 := [] , arr5 := [], result:=[]
; sort each set individually
for i, obj in sets
{
arr1 := []
for j, v in obj
arr1[v] := true
arr2.push(arr1)
}
Β
; sort by set's first item
for i, obj in arr2
for k, v in obj
{
arr3[k . i] := obj
break
}
Β
; use numerical index
for k, obj in arr3
arr4[A_Index] := obj
Β
j := 1
for i, obj in arr4
{
common := false
for k, v in obj
if arr5[j-1].HasKey(k)
{
common := true
break
}
Β
if common
for k, v in obj
arr5[j-1, k] := true
else
arr5[j] := obj, j++
}
; clean up
for i, obj in arr5
for k , v in obj
result[i, A_Index] := k
return result
} |
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 n divisorsββ
See also
OEIS:A005179
| #AutoHotkey | AutoHotkey | max := 15
seq := [], n := 0
while (n < max)
if ((k := countDivisors(A_Index)) <= max) &&Β !seq[k]
seq[k] := A_Index, n++
for i, v in seq
res .= v ", "
MsgBoxΒ % "The first " . max . " terms of the sequence are:`n" Trim(res, ", ")
return
Β
countDivisors(n){
while (A_Index**2 <= n)
ifΒ !Mod(n, A_Index)
count += A_Index = n/A_IndexΒ ? 1Β : 2
return count
} |
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
| #Halon | Halon | $var = "Rosetta code";
echo sha2($var, 256); |
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
| #Haskell | Haskell | import Data.Char (ord)
import Crypto.Hash.SHA256 (hash)
import Data.ByteString (unpack, pack)
import Text.Printf (printf)
Β
main = putStrLn $ -- output to terminal
concatMap (printf "%02x") $ -- to hex string
unpack $ -- to array of Word8
hash $ -- SHA-256 hash to ByteString
pack $ -- to ByteString
map (fromIntegral.ord) -- to array of Word8
"Rosetta code"
Β |
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors | Sequence: smallest number greater than previous term with exactly n divisors | Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisorsββ
| #C | C | #include <stdio.h>
Β
#define MAX 15
Β
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
Β
int main() {
int i, next = 1;
printf("The firstΒ %d terms of the sequence are:\n", MAX);
for (i = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
printf("%d ", i);
next++;
}
}
printf("\n");
return 0;
} |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Java | Java | /* SHA-1 hash in Jsish */
var str = 'Rosetta code';
puts(Util.hash(str, {type:'sha1'}));
Β
/*
=!EXPECTSTART!=
b18c883f4da750164b5af362ea9b9f27f90904b4
=!EXPECTEND!=
*/ |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Jsish | Jsish | /* SHA-1 hash in Jsish */
var str = 'Rosetta code';
puts(Util.hash(str, {type:'sha1'}));
Β
/*
=!EXPECTSTART!=
b18c883f4da750164b5af362ea9b9f27f90904b4
=!EXPECTEND!=
*/ |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #M2000_Interpreter | M2000 Interpreter | Β
Module CheckIt {
Def long i, calls, max, min
s=stack:=random(1,5),random(1,5), random(1,5), random(1,5), random(1,5), random(1,5), random(1,5)
z=0: for i=1 to 7 { z+=stackitem(s, i)}
dice7=lambda z, s -> {
=((z-1) mod 7)+1Β : stack s {z-=NumberΒ : data random(1,5): z+=Stackitem(7)}
}
Dim count(1 to 7)=0& ' long type
calls=700000
p=0.05
IsUniform=lambda max=calls/7*(1+p), min=calls/7*(1-p) (a)->{
if len(a)=0 then =falseΒ : exit
=false
m=each(a)
while m
if array(m)<min or array(m)>max then break
end while
=true
}
For i=1 to calls {count(dice7())++}
max=count()#max()
expected=calls div 7
min=count()#min()
for i=1 to 7
document doc$=format$("{0}{1::-7}",i,count(i))+{
}
Next i
doc$=format$("min={0} expected={1} max={2}", min, expected, max)+{
}+format$("Verify Uniform:{0}", if$(IsUniform(count())->"uniform", "skewed"))+{
}
Print
report doc$
clipboard doc$
}
CheckIt
Β |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | sevenFrom5DiceΒ := (tmp$ = 5*RandomInteger[{1, 5}] + RandomInteger[{1, 5}] - 6;
If [tmp$ < 21, 1 + Mod[tmp$ , 7], sevenFrom5Dice]) |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Nim | Nim | import random, tables
Β
Β
proc dice5(): int = rand(1..5)
Β
Β
proc dice7(): int =
while true:
let val = 5 * dice5() + dice5() - 6
if val < 21:
return val div 3 + 1
Β
Β
proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =
Β
var counts: CountTable[int]
for _ in 1..repeat:
counts.inc f()
Β
let expected = (repeat / counts.len).toInt # Rounded to nearest.
let allowedDelta = (expected.toFloat * tolerance / 100).toInt
var maxDelta = 0
for val, count in counts.pairs:
let d = abs(count - expected)
if d > maxDelta: maxDelta = d
Β
let status = if maxDelta <= allowedDelta: "passed" else: "failed"
echo "Checking ", repeat, " values with a tolerance of ", tolerance, "%."
echo "Random generator ", status, " the uniformity test."
echo "Max delta encountered = ", maxDelta, " Allowed delta = ", allowedDelta
Β
Β
when isMainModule:
import random
randomize()
checkDist(dice7, 1_000_000, 0.5) |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Ring | Ring | Β
load "stdlib.ring"
Β
primes = []
for n = 1 to 100
if isprime(n)
add(primes,n)
ok
next
Β
see "Sexy prime pairs under 100:" + nl + nl
for n = 1 to len(primes)-1
for m = n + 1 to len(primes)
if primes[m] - primes[n] = 6
see "(" + primes[n] + " " + primes[m] + ")" + nl
ok
next
next
see nl
Β
see "Sexy prime triplets under 100:" + nl +nl
for n = 1 to len(primes)-2
for m = n + 1 to len(primes)-1
for x = m + 1 to len(primes)
bool1 = (primes[m] - primes[n] = 6)
bool2 = (primes[x] - primes[m] = 6)
bool = bool1 and bool2
if bool
see "(" + primes[n] + " " + primes[m] + " " + primes[x] + ")" + nl
ok
next
next
next
see nl
Β
see "Sexy prime quadruplets under 100:" + nl + nl
for n = 1 to len(primes)-3
for m = n + 1 to len(primes)-2
for x = m + 1 to len(primes)-1
for y = m + 1 to len(primes)
bool1 = (primes[m] - primes[n] = 6)
bool2 = (primes[x] - primes[m] = 6)
bool3 = (primes[y] - primes[x] = 6)
bool = bool1 and bool2 and bool3
if bool
see "(" + primes[n] + " " + primes[m] + " " + primes[x] + " " + primes[y] + ")" + nl
ok
next
next
next
next
see nl
Β
see "Sexy prime quintuplets under 100:" + nl + nl
for n = 1 to len(primes)-4
for m = n + 1 to len(primes)-3
for x = m + 1 to len(primes)-2
for y = m + 1 to len(primes)-1
for z = y + 1 to len(primes)
bool1 = (primes[m] - primes[n] = 6)
bool2 = (primes[x] - primes[m] = 6)
bool3 = (primes[y] - primes[x] = 6)
bool4 = (primes[z] - primes[y] = 6)
bool = bool1 and bool2 and bool3 and bool4
if bool
see "(" + primes[n] + " " + primes[m] + " " + primes[x] + " " +
primes[y] + " " + primes[z] + ")" + nl
ok
next
next
next
next
next
Β |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Ruby | Ruby | Β
require 'prime'
Β
prime_array, sppair2, sppair3, sppair4, sppair5 = Array.new(5) {Array.new()} # arrays for prime numbers and index number to array for each pair.
unsexy, i, start = [2], 0, Time.now
Prime.each(1_000_100) {|prime| prime_array.push prime}
Β
while prime_array[i] < 1_000_035
i+=1
unsexy.push(i) if prime_array[(i+1)..(i+2)].include?(prime_array[i]+6) == false && prime_array[(i-2)..(i-1)].include?(prime_array[i]-6) == false && prime_array[i]+6 < 1_000_035
prime_array[(i+1)..(i+4)].include?(prime_array[i]+6) && prime_array[i]+6 < 1_000_035Β ? sppair2.push(i)Β : next
prime_array[(i+2)..(i+5)].include?(prime_array[i]+12) && prime_array[i]+12 < 1_000_035Β ? sppair3.push(i)Β : next
prime_array[(i+3)..(i+6)].include?(prime_array[i]+18) && prime_array[i]+18 < 1_000_035Β ? sppair4.push(i)Β : next
prime_array[(i+4)..(i+7)].include?(prime_array[i]+24) && prime_array[i]+24 < 1_000_035Β ? sppair5.push(i)Β : next
end
Β
puts "\nSexy prime pairs: #{sppair2.size} found:"
sppair2.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6].join(" - "), "\n"}
puts "\nSexy prime triplets: #{sppair3.size} found:"
sppair3.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12].join(" - "), "\n"}
puts "\nSexy prime quadruplets: #{sppair4.size} found:"
sppair4.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18].join(" - "), "\n"}
puts "\nSexy prime quintuplets: #{sppair5.size} found:"
sppair5.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18, prime_array[prime]+24].join(" - "), "\n"}
Β
puts "\nUnSexy prime: #{unsexy.size} found. Last 10 are:"
unsexy.last(10).each {|item| print prime_array[item], " "}
print "\n\n", Time.now - start, " seconds"
Β |
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
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Frink | Frink | a = ["32 Space"]
for i = 33 to 126
a.push["$i " + char[i]]
a.push["127 Delete"]
Β
println[formatTableBoxed[columnize[a,8].transpose[], "left"]] |
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:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Pascal | Pascal | program Sierpinski;
Β
function ipow(b, n : Integer) : Integer;
var
i : Integer;
begin
ipow := 1;
for i := 1 to n do
ipow := ipow * b
end;
Β
function truth(a : Char) : Boolean;
begin
if a = '*' then
truth := true
else
truth := false
end; |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the Β # Β character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Β Sierpinski triangle
| #Java | Java | public static boolean inCarpet(long x, long y) {
while (x!=0 && y!=0) {
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
Β
public static void carpet(final int n) {
final double power = Math.pow(3,n);
for(long i = 0; i < power; i++) {
for(long j = 0; j < power; j++) {
System.out.print(inCarpet(i, j) ? "*" : " ");
}
System.out.println();
}
} |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | a[in_]Β := (Print["a"]; in)
b[in_]Β := (Print["b"]; in)
a[False] && b[True]
a[True] || b[False] |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #MATLAB_.2F_Octave | MATLAB / Octave | function x=a(x)
printf('a:Β %i\n',x);
end;
function x=b(x)
printf('b:Β %i\n',x);
end;
Β
a(1) && b(1)
a(0) && b(1)
a(1) || b(1)
a(0) || b(1) |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Picat | Picat | import util.
import cp.
Β
%
% Solve the task in the description.
%
goΒ ?=>
sets(1,Sets,SetLen,NumSets),
print_cards(Sets),
set_puzzle(Sets,SetLen,NumSets,X),
print_sol(Sets,X),
nl,
fail,Β % check for other solutions
nl.
go => true.
Β
%
% Generate and solve a random instance with NumCards cards,
% giving exactly NumSets sets.
%
go2 =>
_ = random2(),
NumCards = 9, NumSets = 4, SetLen = 3,
generate_and_solve(NumCards,NumSets,SetLen),
fail,Β % prove unicity
nl.
Β
go3 =>
_ = random2(),
NumCards = 12, NumSets = 6, SetLen = 3,
generate_and_solve(NumCards,NumSets,SetLen),
fail,Β % prove unicity)
nl.
Β
%
% Solve a Set Puzzle.
%
set_puzzle(Cards,SetLen,NumWanted, X) =>
Len = Cards.length,
NumFeatures = Cards[1].length,
Β
X = new_list(NumWanted),
foreach(I in 1..NumWanted)
Y = new_array(SetLen),
foreach(J in 1..SetLen)
member(Y[J], 1..Len)
end,
Β % unicity and symmetry breaking of Y
increasing2(Y),
Β % ensure unicity of the selected cards in X
if I > 1 then
foreach(J in 1..I-1) X[J] @< Y end
end,
foreach(F in 1..NumFeatures)
Z = [Cards[Y[J],F]Β : J in 1..SetLen],
(allequal(Z)Β ; alldiff(Z))
end,
X[I] = Y
end.
Β
% (Strictly) increasing
increasing2(List) =>
foreach(I in 1..List.length-1)
List[I] @< List[I+1]
end.
Β
% All elements must be equal
allequal(List) =>
foreach(I in 1..List.length-1)
List[I] = List[I+1]
end.
Β
% All elements must be different
alldiff(List) =>
Len = List.length,
foreach(I in 1..Len, J in 1..I-1)
List[I]Β != List[J]
end.
Β
% Print a solution
print_sol(Sets,X) =>
println("Solution:"),
println(x=X),
foreach(R in X)
println([Sets[R[I]]Β : I in 1..3])
end,
nl.
Β
% Print the cards
print_cards(Cards) =>
println("Cards:"),
foreach({Card,I} in zip(Cards,1..Cards.len))
println([I,Card])
end,
nl.
Β
%
% Generate a problem instance with NumSets sets (a unique solution).
%
% Note: not all random combinations of cards give a unique solution so
% it might generate a number of deals.
%
generate_instance(NumCards,NumSets,SetLen, Cards) =>
println([numCards=NumCards,numWantedSets=NumSets,setLen=SetLen]),
Found = false,
Β % Check that this instance has a unique solution.
while(Found = false)
if Cards = random_deal(NumCards),
count_all(set_puzzle(Cards,SetLen,NumSets,_X)) = 1
then
FoundΒ := true
end
end.
Β
%
% Generate a random problem instance of N cards.
%
random_deal(N) = Deal.sort() =>
all_combinations(Combinations),
Deal = [],
foreach(_I in 1..N)
Len = Combinations.len,
Rand = random(1,Len),
Comb = Combinations[Rand],
DealΒ := Deal ++ [Comb],
CombinationsΒ := delete_all(Combinations, Comb)
end.
Β
%
% Generate a random instance and solve it.
%
generate_and_solve(NumCards,NumSets,SetLen) =>
generate_instance(NumCards,NumSets,SetLen, Cards),
print_cards(Cards),
set_puzzle(Cards,SetLen,NumSets,X),Β % solve it
print_sol(Cards,X),
nl.
Β
Β
%
% All the 81 possible combinations (cards)
%
table
all_combinations(All) =>
Colors = [red, green, purple],
Symbols = [oval, squiggle, diamond],
Numbers = [one, two, three],
Shadings = [solid, open, striped],
All = findall([Color,Symbol,Number,Shading],
(member(Color,Colors),
member(Symbol,Symbols),
member(Number,Numbers),
member(Shading,Shadings))).
Β
%
% From the task description.
%
% Solution: [[1,6,9],[2,3,4],[2,6,8],[5,6,7]]
%
sets(1,Sets,SetLen,Wanted) =>
Sets =
[
[green, one, oval, striped],Β % 1
[green, one, diamond, open],Β % 2
[green, one, diamond, striped],Β % 3
[green, one, diamond, solid],Β % 4
[purple, one, diamond, open],Β % 5
[purple, two, squiggle, open],Β % 6
[purple, three, oval, open],Β % 7
[red, three, oval, open],Β % 8
[red, three, diamond, solid]Β % 9
],
SetLen = 3,
Wanted = 4. |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Prolog | Prolog | do_it(N) :-
card_sets(N, Cards, Sets),
!,
format('Cards: ~n'),
maplist(print_card, Cards),
format('~nSets: ~n'),
maplist(print_set, Sets).
Β
print_card(Card) :- format(' ~p ~p ~p ~p~n', Card).
print_set(Set) :- maplist(print_card, Set), nl.
Β
n(9,4).
n(12,6).
Β
card_sets(N, Cards, Sets) :-
n(N,L),
repeat,
random_deal(N, Cards),
setof(Set, is_card_set(Cards, Set), Sets),
length(Sets, L).
Β
random_card([C,S,N,Sh]) :-
random_member(C, [red, green, purple]),
random_member(S, [oval, squiggle, diamond]),
random_member(N, [one, two, three]),
random_member(Sh, [solid, open, striped]).
Β
random_deal(N, Cards) :-
length(Cards, N),
maplist(random_card, Cards).
Β
is_card_set(Cards, Result) :-
select(C1, Cards, Rest),
select(C2, Rest, Rest2),
select(C3, Rest2, _),
Β
match(C1, C2, C3),
sort([C1,C2,C3], Result).
Β
match([],[],[]).
match([A|T1],[A|T2],[A|T3]) :-
match(T1,T2,T3).
match([A|T1],[B|T2],[C|T3]) :-
dif(A,B), dif(B,C), dif(A,C),
match(T1,T2,T3). |
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 | #C | C | #include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
Β
#define LIMIT 15
int smallPrimes[LIMIT];
Β
static void sieve() {
int i = 2, j;
int p = 5;
Β
smallPrimes[0] = 2;
smallPrimes[1] = 3;
Β
while (i < LIMIT) {
for (j = 0; j < i; j++) {
if (smallPrimes[j] * smallPrimes[j] <= p) {
if (p % smallPrimes[j] == 0) {
p += 2;
break;
}
} else {
smallPrimes[i++] = p;
p += 2;
break;
}
}
}
}
Β
static bool is_prime(uint64_t n) {
uint64_t i;
Β
for (i = 0; i < LIMIT; i++) {
if (n % smallPrimes[i] == 0) {
return n == smallPrimes[i];
}
}
Β
i = smallPrimes[LIMIT - 1] + 2;
for (; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
Β
return true;
}
Β
static uint64_t divisor_count(uint64_t n) {
uint64_t count = 1;
uint64_t d;
Β
while (n % 2 == 0) {
n /= 2;
count++;
}
Β
for (d = 3; d * d <= n; d += 2) {
uint64_t q = n / d;
uint64_t r = n % d;
uint64_t dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
Β
if (n != 1) {
return count *= 2;
}
return count;
}
Β
static uint64_t OEISA073916(size_t n) {
uint64_t count = 0;
uint64_t result = 0;
size_t i;
Β
if (is_prime(n)) {
return (uint64_t)pow(smallPrimes[n - 1], n - 1);
}
Β
for (i = 1; count < n; i++) {
if (n % 2 == 1) {
// The solution for an odd (non-prime) term is always a square number
uint64_t root = (uint64_t)sqrt(i);
if (root * root != i) {
continue;
}
}
if (divisor_count(i) == n) {
count++;
result = i;
}
}
Β
return result;
}
Β
int main() {
size_t n;
Β
sieve();
Β
for (n = 1; n <= LIMIT; n++) {
if (n == 13) {
printf("A073916(%lu) = One more bit needed to represent result.\n", n);
} else {
printf("A073916(%lu) =Β %llu\n", n, OEISA073916(n));
}
}
Β
return 0;
} |
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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #Bracmat | Bracmat | ( ( consolidate
= a m z mm za zm zz
. ( removeNumFactors
= a m z
. Β !arg:?a+#%*?m+?z
&Β !a+!m+removeNumFactors$!z
|Β !arg
)
& Β !arg
Β : Β ?a
Β %?`m
(Β %?z
& Β !m
Β : Β ?
+ (Β %@?mm
&Β !z:?za (?+!mm+?:?zm)Β ?zz
)
+Β ?
)
& consolidate$(!a removeNumFactors$(!m+!zm)Β !zaΒ !zz)
|Β !arg
)
& (test=.out$(!arg "==>" consolidate$!arg))
& test$(A+B C+D)
& test$(A+B B+D)
& test$(A+B C+D D+B)
& test$(H+I+K A+B C+D D+B F+G+H)
); |
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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #C | C | #include <stdio.h>
Β
#define s(x) (1U << ((x) - 'A'))
Β
typedef unsigned int bitset;
Β
int consolidate(bitset *x, int len)
{
int i, j;
for (i = len - 2; i >= 0; i--)
for (j = len - 1; j > i; j--)
if (x[i] & x[j])
x[i] |= x[j], x[j] = x[--len];
return len;
}
Β
void show_sets(bitset *x, int len)
{
bitset b;
while(len--) {
for (b = 'A'; b <= 'Z'; b++)
if (x[len] & s(b)) printf("%c ", b);
putchar('\n');
}
}
Β
int main(void)
{
bitset x[] = { s('A') | s('B'), s('C') | s('D'), s('B') | s('D'),
s('F') | s('G') | s('H'), s('H') | s('I') | s('K') };
Β
int len = sizeof(x) / sizeof(x[0]);
Β
puts("Before:"); show_sets(x, len);
puts("\nAfter:"); show_sets(x, consolidate(x, len));
return 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 n divisorsββ
See also
OEIS:A005179
| #AWK | AWK | Β
# syntax: GAWK -f SEQUENCE_SMALLEST_NUMBER_WITH_EXACTLY_N_DIVISORS.AWK
# converted from Kotlin
BEGIN {
limit = 15
printf("firstΒ %d terms:",limit)
i = 1
n = 0
while (n < limit) {
k = count_divisors(i)
if (k <= limit && seq[k-1]+0 == 0) {
seq[k-1] = i
n++
}
i++
}
for (i=0; i<limit; i++) {
printf("Β %d",seq[i])
}
printf("\n")
exit(0)
}
function count_divisors(n, count,i) {
for (i=1; i*i<=n; i++) {
if (n % i == 0) {
count += (i == n / i) ? 1 : 2
}
}
return(count)
}
Β |
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
| #Haxe | Haxe | import haxe.crypto.Sha256;
Β
class Main {
static function main() {
var sha256 = Sha256.encode("Rosetta code");
Sys.println(sha256);
}
} |
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
| #J | J | require '~addons/ide/qt/qt.ijs'
getsha256=: 'sha256'&gethash_jqtide_ |
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 number with exactly n divisorsββ
| #C.2B.2B | C++ | #include <iostream>
Β
#define MAX 15
Β
using namespace std;
Β
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
Β
int main() {
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (int i = 1, next = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
cout << i << " ";
next++;
}
}
cout << endl;
return 0;
} |
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 number with exactly n divisorsββ
| #Dyalect | Dyalect | func countDivisors(n) {
var count = 0
var i = 1
while i * i <= n {
if nΒ % i == 0 {
if i == n / i {
count += 1
} else {
count += 2
}
}
i += 1
}
return count
}
Β
let max = 15
print("The first \(max) terms of the sequence are:")
var (i, next) = (1, 1)
while next <= max {
if next == countDivisors(i) {
print("\(i) ", terminator: "")
next += 1
}
i += 1
}
Β
print() |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Julia | Julia | using Nettle
Β
testdict = Dict("abc" => "a9993e364706816aba3e25717850c26c9cd0d89d",
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" =>
"84983e441c3bd26ebaae4aa1f95129e5e54670f1",
"a" ^ 1_000_000 => "34aa973cd4c4daa4f61eeb2bdbad27316534016f",)
Β
for (text, expect) in testdict
digest = hexdigest("sha1", text)
if length(text) > 50 text = text[1:50] * "..." end
println("# $text\n -> digest: $digest\n -> expect: $expect")
end |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Kotlin | Kotlin | // version 1.0.6
Β
import java.security.MessageDigest
Β
fun main(args: Array<String>) {
val text = "Rosetta Code"
val bytes = text.toByteArray()
val md = MessageDigest.getInstance("SHA-1")
val digest = md.digest(bytes)
for (byte in digest) print("%02x".format(byte))
println()
} |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #OCaml | OCaml | let dice5() = 1 + Random.int 5 ;;
Β
let dice7 =
let rolls2answer = Hashtbl.create 25 in
let n = ref 0 in
for roll1 = 1 to 5 do
for roll2 = 1 to 5 do
Hashtbl.add rolls2answer (roll1,roll2) (!n / 3 +1);
incr n
done;
done;
let rec aux() =
let trial = Hashtbl.find rolls2answer (dice5(),dice5()) in
if trial <= 7 then trial else aux()
in
aux
;; |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #PARI.2FGP | PARI/GP | dice5()=random(5)+1;
Β
dice7()={
my(t);
while((t=dice5()*5+dice5()) > 21,);
(t+2)\3
}; |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Rust | Rust | // [dependencies]
// primal = "0.2"
// circular-queue = "0.2.5"
Β
use circular_queue::CircularQueue;
Β
fn main() {
let max = 1000035;
let max_group_size = 5;
let diff = 6;
let max_groups = 5;
let max_unsexy = 10;
Β
let sieve = primal::Sieve::new(max + diff);
let mut group_count = vec![0; max_group_size];
let mut unsexy_count = 0;
let mut groups = Vec::new();
let mut unsexy_primes = CircularQueue::with_capacity(max_unsexy);
Β
for _ in 0..max_group_size {
groups.push(CircularQueue::with_capacity(max_groups));
}
Β
for p in sieve.primes_from(2).take_while(|x| *x < max) {
ifΒ !sieve.is_prime(p + diff) && (p < diff + 2 ||Β !sieve.is_prime(p - diff)) {
unsexy_count += 1;
unsexy_primes.push(p);
} else {
let mut group = Vec::new();
group.push(p);
for group_size in 1..max_group_size {
let next = p + group_size * diff;
if next >= max ||Β !sieve.is_prime(next) {
break;
}
group.push(next);
group_count[group_size] += 1;
groups[group_size].push(group.clone());
}
}
}
Β
for size in 1..max_group_size {
println!(
"Number of groups of size {} is {}",
size + 1,
group_count[size]
);
println!("Last {} groups of size {}:", groups[size].len(), size + 1);
println!(
"{}\n",
groups[size]
.asc_iter()
.map(|g| format!("({})", to_string(&mut g.iter())))
.collect::<Vec<String>>()
.join(", ")
);
}
println!("Number of unsexy primes is {}", unsexy_count);
println!("Last {} unsexy primes:", unsexy_primes.len());
println!("{}", to_string(&mut unsexy_primes.asc_iter()));
}
Β
fn to_string<T: ToString>(iter: &mut dyn std::iter::Iterator<Item = T>) -> String {
iter.map(|n| n.to_string())
.collect::<Vec<String>>()
.join(", ")
} |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Scala | Scala | /* We could reduce the number of functions through a polymorphism since we're trying to retrieve sexy N-tuples (pairs, triplets etc...)
but one practical solution would be to use the Shapeless library for this purpose; here we only use built-in Scala packages. */
Β
object SexyPrimes {
Β
/** Check if an input number is prime or not*/
def isPrime(n: Int): Boolean = ! ((2 until n-1) exists (n % _ == 0)) && n > 1
Β
/** Retrieve pairs of sexy primes given a list of Integers*/
def getSexyPrimesPairs (primes : List[Int]) = {
primes
.map(n => if(primes.contains(n+6)) (n, n+6))
.filter(p => p != ())
.map{ case (a,b) => (a.toString.toInt, b.toString.toInt)}
}
Β
/** Retrieve triplets of sexy primes given a list of Integers*/
def getSexyPrimesTriplets (primes : List[Int]) = {
primes
.map(n => if(
primes.contains(n+6) && primes.contains(n+12))
(n, n+6, n+12)
)
.filter(p => p != ())
.map{ case (a,b,c) => (a.toString.toInt, b.toString.toInt, c.toString.toInt)}
}
Β
/** Retrieve quadruplets of sexy primes given a list of Integers*/
def getSexyPrimesQuadruplets (primes : List[Int]) = {
primes
.map(n => if(
primes.contains(n+6) && primes.contains(n+12) && primes.contains(n+18))
(n, n+6, n+12, n+18)
)
.filter(p => p != ())
.map{ case (a,b,c,d) => (a.toString.toInt, b.toString.toInt, c.toString.toInt, d.toString.toInt)}
}
Β
/** Retrieve quintuplets of sexy primes given a list of Integers*/
def getSexyPrimesQuintuplets (primes : List[Int]) = {
primes
.map(n => if (
primes.contains(n+6) && primes.contains(n+12) && primes.contains(n+18) && primes.contains(n + 24))
(n, n + 6, n + 12, n + 18, n + 24)
)
.filter(p => p != ())
.map { case (a, b, c, d, e) => (a.toString.toInt, b.toString.toInt, c.toString.toInt, d.toString.toInt, e.toString.toInt) }
Β
}
Β
/** Retrieve all unsexy primes between 1 and a given limit from an input list of Integers*/
def removeOutsideSexyPrimes( l : List[Int], limit : Int) : List[Int] = {
l.filter(n => !isPrime(n+6) && n+6 < limit)
}
Β
def main(args: Array[String]): Unit = {
val limit = 1000035
val l = List.range(1,limit)
val primes = l.filter( n => isPrime(n))
Β
val sexyPairs = getSexyPrimesPairs(primes)
println("Number of sexy pairsΒ : " + sexyPairs.size)
println("5 last sexy pairsΒ : " + sexyPairs.takeRight(5))
Β
val primes2 = sexyPairs.flatMap(t => List(t._1, t._2)).distinct.sorted
val sexyTriplets = getSexyPrimesTriplets(primes2)
println("Number of sexy tripletsΒ : " + sexyTriplets.size)
println("5 last sexy tripletsΒ : " + sexyTriplets.takeRight(5))
Β
val primes3 = sexyTriplets.flatMap(t => List(t._1, t._2, t._3)).distinct.sorted
val sexyQuadruplets = getSexyPrimesQuadruplets(primes3)
println("Number of sexy quadrupletsΒ : " + sexyQuadruplets.size)
println("5 last sexy quadrupletsΒ : " + sexyQuadruplets.takeRight(5))
Β
val primes4 = sexyQuadruplets.flatMap(t => List(t._1, t._2, t._3, t._4)).distinct.sorted
val sexyQuintuplets = getSexyPrimesQuintuplets(primes4)
println("Number of sexy quintupletsΒ : " + sexyQuintuplets.size)
println("The last sexy quintupletΒ : " + sexyQuintuplets.takeRight(10))
Β
val sexyPrimes = primes2.toSet
val unsexyPrimes = removeOutsideSexyPrimes( primes.toSet.diff((sexyPrimes)).toList.sorted, limit)
println("Number of unsexy primesΒ : " + unsexyPrimes.size)
println("10 last unsexy primesΒ : " + unsexyPrimes.takeRight(10))
Β
}
Β
}
Β |
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
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.C5.8Drmul.C3.A6 | FΕrmulΓ¦ | Β
include "NSLog.incl"
Β
local fn ASCIITable as CFStringRef
'~'1
NSinteger i
CFStringRef temp
Β
CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )
for i = 32 to 127
temp = fn StringWithFormat( @"%c", i )
if i == 32 then temp = @"Spc"
if i == 127 then temp = @"Del"
MutableStringAppendString( mutStr, fn StringWithFormat( @"%-1dΒ :Β %@\n", i, temp ) )
next
Β
CFArrayRef colArr = fn StringComponentsSeparatedByString( mutStr, @"\n" )
MutableStringSetString( mutStr, @"" )
for i = 0 to 15
ObjectRef col0 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i ) )
ObjectRef col1 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 16 ) )
ObjectRef col2 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 32 ) )
ObjectRef col3 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 48 ) )
ObjectRef col4 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 64 ) )
ObjectRef col5 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 80 ) )
MutableStringAppendString( mutStr, fn StringWithFormat( @"%-10sΒ %-10sΒ %-10sΒ %-10sΒ %-10sΒ %-10s\n", col0, col1, col2, col3, col4, col5 ) )
next
end fn = fn StringWithString( mutStr )
Β
NSLog( @"%@", fn ASCIITable )
Β
HandleEvents
Β |
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:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Perl | Perl | sub sierpinski {
my ($n) = @_;
my @down = '*';
my $space = ' ';
foreach (1..$n) {
@down = (map("$space$_$space", @down), map("$_ $_", @down));
$space = "$space$space";
}
return @down;
}
Β
print "$_\n" foreach 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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the Β # Β character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Β Sierpinski triangle
| #JavaScript | JavaScript | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Sierpinski Carpet</title>
<script type='text/javascript'>
Β
var black_char = "#";
var white_char = " ";
Β
var SierpinskiCarpet = function(size) {
this.carpet = [black_char];
for (var i = 1; i <= size; i++) {
this.carpet = [].concat(
this.carpet.map(this.sier_top),
this.carpet.map(this.sier_middle),
this.carpet.map(this.sier_top)
);
}
}
Β
SierpinskiCarpet.prototype.sier_top = function(x) {
var str = new String(x);
return new String(str+str+str);
}
Β
SierpinskiCarpet.prototype.sier_middle = function (x) {
var str = new String(x);
var spacer = str.replace(new RegExp(black_char, 'g'), white_char);
return new String(str+spacer+str);
}
Β
SierpinskiCarpet.prototype.to_string = function() {
return this.carpet.join("\n")
}
Β
SierpinskiCarpet.prototype.to_html = function(target) {
var table = document.createElement('table');
for (var i = 0; i < this.carpet.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < this.carpet[i].length; j++) {
var cell = document.createElement('td');
cell.setAttribute('class', this.carpet[i][j] == black_charΒ ? 'black'Β : 'white');
cell.appendChild(document.createTextNode('\u00a0'));
row.appendChild(cell);
}
table.appendChild(row);
}
target.appendChild(table);
}
Β
</script>
<style type='text/css'>
table {border-collapse: collapse;}
td {width: 1em;}
.black {background-color: black;}
.white {background-color: white;}
</style>
</head>
<body>
Β
<pre id='to_string' style='float:left; margin-right:0.25in'></pre>
<div id='to_html'></div>
Β
<script type='text/javascript'>
var sc = new SierpinskiCarpet(3);
document.getElementById('to_string').appendChild(document.createTextNode(sc.to_string()));
sc.to_html(document.getElementById('to_html'));
</script>
Β
</body>
</html> |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #Modula-2 | Modula-2 | MODULE ShortCircuit;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Β
PROCEDURE a(v : BOOLEAN) : BOOLEAN;
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
FormatString(" # Called function a(%b)\n", buf, v);
WriteString(buf);
RETURN v
END a;
Β
PROCEDURE b(v : BOOLEAN) : BOOLEAN;
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
FormatString(" # Called function b(%b)\n", buf, v);
WriteString(buf);
RETURN v
END b;
Β
PROCEDURE Print(x,y : BOOLEAN);
VAR buf : ARRAY[0..63] OF CHAR;
VAR temp : BOOLEAN;
BEGIN
FormatString("a(%b) AND b(%b)\n", buf, x, y);
WriteString(buf);
temp := a(x) AND b(y);
Β
FormatString("a(%b) OR b(%b)\n", buf, x, y);
WriteString(buf);
temp := a(x) OR b(y);
Β
WriteLn;
END Print;
Β
BEGIN
Print(FALSE,FALSE);
Print(FALSE,TRUE);
Print(TRUE,TRUE);
Print(TRUE,FALSE);
ReadChar
END ShortCircuit. |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Python | Python | #!/usr/bin/python
Β
from itertools import product, combinations
from random import sample
Β
## Major constants
features = [ 'green purple red'.split(),
'one two three'.split(),
'oval diamond squiggle'.split(),
'open striped solid'.split() ]
Β
deck = list(product(list(range(3)), repeat=4))
Β
dealt = 9
Β
## Functions
def printcard(card):
print(' '.join('%8s'Β % f[i] for f,i in zip(features, card)))
Β
def getdeal(dealt=dealt):
deal = sample(deck, dealt)
return deal
Β
def getsets(deal):
good_feature_count = set([1, 3])
sets = [ comb for comb in combinations(deal, 3)
if all( [(len(set(feature)) in good_feature_count)
for feature in zip(*comb)]
) ]
return sets
Β
def printit(deal, sets):
print('DealtΒ %i cards:'Β % len(deal))
for card in deal: printcard(card)
print('\nFoundΒ %i sets:'Β % len(sets))
for s in sets:
for card in s: printcard(card)
print('')
Β
if __name__ == '__main__':
while True:
deal = getdeal()
sets = getsets(deal)
if len(sets) == dealt / 2:
break
printit(deal, sets)
Β |
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 | #C.2B.2B | C++ | #include <iostream>
#include <vector>
Β
std::vector<int> smallPrimes;
Β
bool is_prime(size_t test) {
if (test < 2) {
return false;
}
if (test % 2 == 0) {
return test == 2;
}
for (size_t d = 3; d * d <= test; d += 2) {
if (test % d == 0) {
return false;
}
}
return true;
}
Β
void init_small_primes(size_t numPrimes) {
smallPrimes.push_back(2);
Β
int count = 0;
for (size_t n = 3; count < numPrimes; n += 2) {
if (is_prime(n)) {
smallPrimes.push_back(n);
count++;
}
}
}
Β
size_t divisor_count(size_t n) {
size_t count = 1;
while (n % 2 == 0) {
n /= 2;
count++;
}
for (size_t d = 3; d * d <= n; d += 2) {
size_t q = n / d;
size_t r = n % d;
size_t dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if (n != 1) {
count *= 2;
}
return count;
}
Β
uint64_t OEISA073916(size_t n) {
if (is_prime(n)) {
return (uint64_t) pow(smallPrimes[n - 1], n - 1);
}
Β
size_t count = 0;
uint64_t result = 0;
for (size_t i = 1; count < n; i++) {
if (n % 2 == 1) {
// The solution for an odd (non-prime) term is always a square number
size_t root = (size_t) sqrt(i);
if (root * root != i) {
continue;
}
}
if (divisor_count(i) == n) {
count++;
result = i;
}
}
return result;
}
Β
int main() {
const int MAX = 15;
init_small_primes(MAX);
for (size_t n = 1; n <= MAX; n++) {
if (n == 13) {
std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n";
} else {
std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n';
}
}
Β
return 0;
} |
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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
Β
public class SetConsolidation
{
public static void Main()
{
var setCollection1 = new[] {new[] {"A", "B"}, new[] {"C", "D"}};
var setCollection2 = new[] {new[] {"A", "B"}, new[] {"B", "D"}};
var setCollection3 = new[] {new[] {"A", "B"}, new[] {"C", "D"}, new[] {"B", "D"}};
var setCollection4 = new[] {new[] {"H", "I", "K"}, new[] {"A", "B"}, new[] {"C", "D"},
new[] {"D", "B"}, new[] {"F", "G", "H"}};
var input = new[] {setCollection1, setCollection2, setCollection3, setCollection4};
Β
foreach (var sets in input) {
Console.WriteLine("Start sets:");
Console.WriteLine(string.Join(", ", sets.Select(s => "{" + string.Join(", ", s) + "}")));
Console.WriteLine("Sets consolidated using Nodes:");
Console.WriteLine(string.Join(", ", ConsolidateSets1(sets).Select(s => "{" + string.Join(", ", s) + "}")));
Console.WriteLine("Sets consolidated using Set operations:");
Console.WriteLine(string.Join(", ", ConsolidateSets2(sets).Select(s => "{" + string.Join(", ", s) + "}")));
Console.WriteLine();
}
}
Β
/// <summary>
/// Consolidates sets using a connected-component-finding-algorithm involving Nodes with parent pointers.
/// The more efficient solution, but more elaborate code.
/// </summary>
private static IEnumerable<IEnumerable<T>> ConsolidateSets1<T>(IEnumerable<IEnumerable<T>> sets,
IEqualityComparer<T> comparer = null)
{
if (comparer == null) comparer = EqualityComparer<T>.Default;
var elements = new Dictionary<T, Node<T>>();
foreach (var set in sets) {
Node<T> top = null;
foreach (T value in set) {
Node<T> element;
if (elements.TryGetValue(value, out element)) {
if (top != null) {
var newTop = element.FindTop();
top.Parent = newTop;
element.Parent = newTop;
top = newTop;
} else {
top = element.FindTop();
}
} else {
elements.Add(value, element = new Node<T>(value));
if (top == null) top = element;
else element.Parent = top;
}
}
}
foreach (var g in elements.Values.GroupBy(element => element.FindTop().Value))
yield return g.Select(e => e.Value);
}
Β
private class Node<T>
{
public Node(T value, Node<T> parent = null) {
Value = value;
Parent = parent ?? this;
}
Β
public T Value { get; }
public Node<T> Parent { get; set; }
Β
public Node<T> FindTop() {
var top = this;
while (top != top.Parent) top = top.Parent;
//Set all parents to the top element to prevent repeated iteration in the future
var element = this;
while (element.Parent != top) {
var parent = element.Parent;
element.Parent = top;
element = parent;
}
return top;
}
}
Β
/// <summary>
/// Consolidates sets using operations on the HashSet<T> class.
/// Less efficient than the other method, but easier to write.
/// </summary>
private static IEnumerable<IEnumerable<T>> ConsolidateSets2<T>(IEnumerable<IEnumerable<T>> sets,
IEqualityComparer<T> comparer = null)
{
if (comparer == null) comparer = EqualityComparer<T>.Default;
var currentSets = sets.Select(s => new HashSet<T>(s)).ToList();
int previousSize;
do {
previousSize = currentSets.Count;
for (int i = 0; i < currentSets.Count - 1; i++) {
for (int j = currentSets.Count - 1; j > i; j--) {
if (currentSets[i].Overlaps(currentSets[j])) {
currentSets[i].UnionWith(currentSets[j]);
currentSets.RemoveAt(j);
}
}
}
} while (previousSize > currentSets.Count);
foreach (var set in currentSets) yield return set.Select(value => value);
}
} |
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 n divisorsββ
See also
OEIS:A005179
| #BCPL | BCPL | get "libhdr"
Β
manifest $( LENGTH = 15 $)
Β
let divisors(n) = valof
$( let count = 0 and i = 1
while i*i <= n
$( if n rem i = 0 then
countΒ := count + (i = n/i -> 1, 2)
iΒ := i + 1
$)
resultis count
$)
Β
let sequence(n, seq) be
$( let found = 0 and i = 1
for i=1 to n do seq!iΒ := 0
while found < n
$( let divs = divisors(i)
if divs <= n & seq!divs = 0
$( foundΒ := found + 1
seq!divsΒ := i
$)
iΒ := i + 1
$)
$)
Β
let start() be
$( let seq = vec LENGTH
sequence(LENGTH, seq)
Β
for i=1 to LENGTH do writef("%N ", seq!i)
wrch('*N')
$) |
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 n divisorsββ
See also
OEIS:A005179
| #C | C | #include <stdio.h>
Β
#define MAX 15
Β
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
Β
int main() {
int i, k, n, seq[MAX];
for (i = 0; i < MAX; ++i) seq[i] = 0;
printf("The firstΒ %d terms of the sequence are:\n", MAX);
for (i = 1, n = 0; n < MAX; ++i) {
k = count_divisors(i);
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i;
++n;
}
}
for (i = 0; i < MAX; ++i) printf("%d ", seq[i]);
printf("\n");
return 0;
} |
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
| #Java | Java | Β
const crypto = require('crypto');
Β
const msg = 'Rosetta code';
const hash = crypto.createHash('sha256').update(msg).digest('hex');
Β
console.log(hash);
Β |
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
| #JavaScript | JavaScript | Β
const crypto = require('crypto');
Β
const msg = 'Rosetta code';
const hash = crypto.createHash('sha256').update(msg).digest('hex');
Β
console.log(hash);
Β |
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 number with exactly n divisorsββ
| #F.23 | F# | Β
// Nigel Galloway: November 19th., 2017
let fN g=[1..(float>>sqrt>>int)g]|>List.fold(fun Ξ£ n->if g%n>0 then Ξ£ else if g/n=n then Ξ£+1 else Ξ£+2) 0
let A069654=let rec fG n g=seq{match g-fN n with 0->yield n; yield! fG(n+1)(g+1) |_->yield! fG(n+1)g} in fG 1 1
Β
A069654 |> Seq.take 28|>Seq.iter(printf "%d "); printfn ""
Β |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Lasso | Lasso | cipher_digest('Rosetta Code', -digest='SHA1',-hex=true) |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Liberty_BASIC | Liberty BASIC | Β
'--------------------------------------------------------------------------------
' FAST SHA1 CALCULATION BASED ON MS ADVAPI32.DLL BY CRYPTOMAN '
' BASED ON SHA256 EXAMPLE BY RICHARD T. RUSSEL AUTHOR OF LBB '
' http://lbb.conforums.com/ '
' VERIFY CORRECTNESS BY http://www.fileformat.info/tool/hash.htm '
'--------------------------------------------------------------------------------
Β
print sha1$("Rosetta Code")
end
Β
X$="1234567890ABCDEF"
Β
dat$ = pack$(X$)
Β
print "SPEED TEST"
for i=1 to 20
t1=time$("ms")
print sha1$(dat$)
t2=time$("ms")
print "calculated in ";t2-t1;" ms"
next
end
Β
function sha1$(message$)
Β
HP.HASHVAL = 2
CRYPT.NEWKEYSET = 48
PROV.RSA.AES = 24
buffer$ = space$(128)
Β
PROVRSAFULL = 1
ALGCLASSHASH = 32768
ALGTYPEANY = 0
ALGSIDMD2 = 1
ALGSIDMD4 = 2
ALGSIDMD5 = 3
ALGSIDSHA1 = 4
Β
ALGOSHA1 = ALGCLASSHASH OR ALGTYPEANY OR ALGSIDSHA1
Β
struct temp, v as long
open "ADVAPI32.DLL" for dll as #advapi32
calldll #advapi32, "CryptAcquireContextA", temp as struct, _
0 as long, 0 as long, PROV.RSA.AES as long, _
0 as long, re as long
hprov = temp.v.struct
calldll #advapi32, "CryptCreateHash", hprov as long, _
ALGOSHA1 as long, 0 as long, 0 as long, _
temp as struct, re as long
hhash = temp.v.struct
l = len(message$)
calldll #advapi32, "CryptHashData", hhash as long, message$ as ptr, _
l as long, 0 as long, re as long
temp.v.struct = len(buffer$)
calldll #advapi32, "CryptGetHashParam", hhash as long, _
HP.HASHVAL as long, buffer$ as ptr, _
temp as struct, 0 as long, re as long
calldll #advapi32, "CryptDestroyHash", hhash as long, re as long
calldll #advapi32, "CryptReleaseContext", hprov as long, re as long
close #advapi32
for i = 1 TO temp.v.struct
sha1$ = sha1$ + right$("0" + dechex$(asc(mid$(buffer$,i))), 2)
next
end function
Β
function pack$(x$)
for i = 1 TO len(x$) step 2
pack$ = pack$ + chr$(hexdec(mid$(x$,i,2)))
next
end function
Β |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Pascal | Pascal | Β
unit UConverter;
(*
Defines a converter object to output uniformly distributed random integers 1..7,
given a source of uniformly distributed random integers 1..5.
*)
interface
Β
type
TFace5 = 1..5;
TFace7 = 1..7;
TDice5 = function() : TFace5;
Β
type TConverter = class( TObject)
private
fDigitBuf: array [0..19] of integer; // holds digits in base 7
fBufCount, fBufPtr : integer;
fDice5 : TDice5; // passed-in generator for integers 1..5
fNrDice5 : int64; // diagnostics, counts calls to fDice5
public
constructor Create( aDice5 : TDice5);
procedure Reset();
function Dice7() : TFace7;
property NrDice5 : int64 read fNrDice5;
end;
Β
implementation
Β
constructor TConverter.Create( aDice5 : TDice5);
begin
inherited Create();
fDice5 := aDice5;
self.Reset();
end;
Β
procedure TConverter.Reset();
begin
fBufCount := 0;
fBufPtr := 0;
fNrDice5 := 0;
end;
Β
function TConverter.Dice7() : TFace7;
var
digit_holder, temp : int64;
j : integer;
begin
if fBufPtr = fBufCount then begin // if no more in buffer
fBufCount := 0;
fBufPtr := 0;
repeat // first time through will usually be enough
// Use supplied fDice5 to generate random 23-digit integer in base 5.
digit_holder := 0;
for j := 0 to 22 do begin
digit_holder := 5*digit_holder + fDice5() - 1;
inc( fNrDice5);
end;
// Convert to 20-digit number in base 7. (A simultaneous DivMod
// procedure would be neater, but isn't available for int64.)
for j := 0 to 19 do begin
temp := digit_holder div 7;
fDigitBuf[j] := digit_holder - 7*temp;
digit_holder := temp;
end;
// Maximum possible is 5^23 - 1, which is 10214646460315315132 in base 7.
// If leading digit in base 7 is 0 then low 19 digits are random.
// Else number begins with 100, 101, or 102; and if with
// 100 or 101 then low 17 digits are random. And so on.
if fDigitBuf[19] = 0 then fBufCount := 19
else if fDigitBuf[17] < 2 then fBufCount := 17
else if fDigitBuf[16] = 0 then fBufCount := 16;
// We could go on but that will do.
until fBufCount > 0;
end; // if no more in buffer
result := fDigitBuf[fBufPtr] + 1;
inc( fBufPtr);
end;
end.
Β
program Dice_SevenFromFive;
(*
Demonstrates use of the UConverter unit.
*)
{$mode objfpc}{$H+}
uses
SysUtils, UConverter;
Β
function Dice5() : UConverter.TFace5;
begin
result := Random(5) + 1; // Random(5) returns 0..4
end;
Β
// Percentage points of the chi-squared distribution, 6 degrees of freedom.
// From New Cambridge Statistical Tables, 2nd edn, pp. 40-41.
const
CHI_SQ_6df_95pc = 1.635;
CHI_SQ_6df_05pc = 12.59;
Β
// Main routine
var
nrThrows, j, k : integer;
nrFaces : array [1..7] of integer;
X2, expected, diff : double;
conv : UConverter.TConverter;
begin
conv := UConverter.TConverter.Create( @Dice5);
WriteLn( 'Enter 0 throws to quit');
repeat
WriteLn(''); Write( 'Number of throws (0 to quit): ');
ReadLn( nrThrows);
if nrThrows = 0 then begin
conv.Free();
exit;
end;
conv.Reset(); // clears count of calls to Dice5
for k := 1 to 7 do nrFaces[k] := 0;
for j := 1 to nrThrows do begin
k := conv.Dice7();
inc( nrFaces[k]);
end;
WriteLn('');
WriteLn( SysUtils.Format( 'Number of throws =Β %10d', [nrThrows]));
WriteLn( SysUtils.Format( 'Calls to Dice5 =Β %10d', [conv.NrDice5]));
for k := 1 to 7 do
WriteLn( SysUtils.Format( ' Number ofΒ %d''s =Β %10d', [k, nrFaces[k]]));
Β
// Calculation of chi-squared
expected := nrThrows/7.0;
X2 := 0.0;
for k := 1 to 7 do begin
diff := nrFaces[k] - expected;
X2 := X2 + diff*diff/expected;
end;
WriteLn( SysUtils.Format( 'X^2 =Β %0.3f on 6 degrees of freedom', [X2]));
if X2 < CHI_SQ_6df_95pc then WriteLn( 'Too regular at 5% level')
else if X2 > CHI_SQ_6df_05pc then WriteLn( 'Too irregular at 5% level')
else WriteLn( 'Satisfactory at 5% level')
until false;
end.
Β |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Sidef | Sidef | var limit = 1e6+35
var primes = limit.primes
Β
say "Total number of primes <= #{limit.commify} is #{primes.len.commify}."
say "Sexy k-tuple primes <= #{limit.commify}:\n"
Β
(2..5).each {|k|
var groups = []
primes.each {|p|
var group = (1..^k -> map {|j| 6*j + p })
if (group.all{.is_prime} && (group[-1] <= limit)) {
groups << [p, group...]
}
}
Β
say "...total number of sexy #{k}-tuple primes = #{groups.len.commify}"
say "...where last 5 tuples are: #{groups.last(5).map{'('+.join(' ')+')'}.join(' ')}\n"
}
Β
var unsexy_primes = primes.grep {|p| is_prime(p+6) || is_prime(p-6) -> not }
say "...total number of unsexy primes = #{unsexy_primes.len.commify}"
say "...where last 10 unsexy primes are: #{unsexy_primes.last(10)}" |
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
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FutureBasic | FutureBasic | Β
include "NSLog.incl"
Β
local fn ASCIITable as CFStringRef
'~'1
NSinteger i
CFStringRef temp
Β
CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )
for i = 32 to 127
temp = fn StringWithFormat( @"%c", i )
if i == 32 then temp = @"Spc"
if i == 127 then temp = @"Del"
MutableStringAppendString( mutStr, fn StringWithFormat( @"%-1dΒ :Β %@\n", i, temp ) )
next
Β
CFArrayRef colArr = fn StringComponentsSeparatedByString( mutStr, @"\n" )
MutableStringSetString( mutStr, @"" )
for i = 0 to 15
ObjectRef col0 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i ) )
ObjectRef col1 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 16 ) )
ObjectRef col2 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 32 ) )
ObjectRef col3 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 48 ) )
ObjectRef col4 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 64 ) )
ObjectRef col5 = fn StringUTF8String( fn ArrayObjectAtIndex( colArr, i + 80 ) )
MutableStringAppendString( mutStr, fn StringWithFormat( @"%-10sΒ %-10sΒ %-10sΒ %-10sΒ %-10sΒ %-10s\n", col0, col1, col2, col3, col4, col5 ) )
next
end fn = fn StringWithString( mutStr )
Β
NSLog( @"%@", fn ASCIITable )
Β
HandleEvents
Β |
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:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Phix | Phix | procedure sierpinski(integer n)
integer lim = power(2,n)-1
for y=lim to 0 by -1 do
puts(1,repeat(' ',y))
for x=0 to lim-y do
puts(1,iff(and_bits(x,y)?" ":"* "))
end for
puts(1,"\n")
end for
end procedure
for i=1 to 5 do
sierpinski(i)
end for
|
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the Β # Β character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Β Sierpinski triangle
| #jq | jq | Β
def inCarpet(x; y):
x as $x | y as $y |
if $x == -1 or $y == -1 then "\n"
elif $x == 0 or $y == 0 then "*"
elif ($xΒ % 3) == 1 and ($yΒ % 3) == 1 then " "
else inCarpet($x/3 | floor; $y/3 | floor)
end;
Β
def ipow(n):
. as $in | reduce range(0;n) as $i (1; . * $in);
Β
def carpet(n):
(3|ipow(n)) as $power
| [ inCarpet( range(0; $power)Β ; range(0; $power), -1 )]
| join("")Β ;
Β
Β
carpet(3) |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #MUMPS | MUMPS | SSEVAL1(IN)
WRITEΒ !,?10,$STACK($STACK,"PLACE")
QUIT IN
SSEVAL2(IN)
WRITEΒ !,?10,$STACK($STACK,"PLACE")
QUIT IN
SSEVAL3
NEW Z
WRITE "1 AND 1"
SET Z=$$SSEVAL1(1) SET:Z Z=Z&$$SSEVAL2(1)
WRITEΒ !,$SELECT(Z:"TRUE",1:"FALSE")
WRITEΒ !!,"0 AND 1"
SET Z=$$SSEVAL1(0) SET:Z Z=Z&$$SSEVAL2(1)
WRITEΒ !,$SELECT(Z:"TRUE",1:"FALSE")
WRITEΒ !!,"1 OR 1"
SET Z=$$SSEVAL1(1) SET:'Z Z=Z!$$SSEVAL2(1)
WRITEΒ !,$SELECT(Z:"TRUE",1:"FALSE")
WRITEΒ !!,"0 OR 1"
SET Z=$$SSEVAL1(0) SET:'Z Z=Z!$$SSEVAL2(1)
WRITEΒ !,$SELECT(Z:"TRUE",1:"FALSE")
KILL Z
QUIT |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #Nanoquery | Nanoquery | def short_and(bool1, bool2)
global a
global b
if a(bool1)
if b(bool2)
return true
else
return false
end
else
return false
end
end
Β
def short_or(bool1, bool2)
if a(bool1)
return true
else
if b(bool2)
return true
else
return false
end
end
end
Β
def a(bool)
println "a called."
return bool
end
Β
def b(bool)
println "b called."
return bool
end
Β
println "F and F = " + short_and(false, false) + "\n"
println "F or F = " + short_or(false, false) + "\n"
Β
println "F and T = " + short_and(false, true) + "\n"
println "F or T = " + short_or(false, true) + "\n"
Β
println "T and F = " + short_and(true, false) + "\n"
println "T or F = " + short_or(true, false) + "\n"
Β
println "T and T = " + short_and(true, true) + "\n"
println "T or T = " + short_or(true, true) + "\n" |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Racket | Racket | Β
#lang racket
Β
(struct card [bits name])
Β
(define cards
(for/list ([C '(red green purple )] [Ci '(#o0001 #o0002 #o0004)]
#:when #t
[S '(oval squiggle diamond)] [Si '(#o0010 #o0020 #o0040)]
#:when #t
[N '(one two three )] [Ni '(#o0100 #o0200 #o0400)]
#:when #t
[D '(solid open striped)] [Di '(#o1000 #o2000 #o4000)])
(card (bitwise-ior Ci Si Ni Di) (format "~a, ~a, ~a, ~a" C S N D))))
Β
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(define (set? cards)
(regexp-match? #rx"^[1247]*$"
(number->string (apply bitwise-ior (map card-bits cards)) 8)))
Β
(define (deal C S)
(define hand (take (shuffle cards) C))
(define 3sets (filter set? (nsubsets hand 3)))
(cond [(not (= S (length 3sets))) (deal C S)]
[else (printf "Dealt ~a cards:\n" C)
(for ([c hand]) (printf " ~a\n" (card-name c)))
(printf "\nContaining ~a sets:\n" S)
(for ([set 3sets])
(for ([c set]) (printf " ~a\n" (card-name c)))
(newline))]))
Β
(deal 9 4)
(deal 12 6)
Β |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #Raku | Raku | enum Color (red => 0o1000, green => 0o2000, purple => 0o4000);
enum Count (one => 0o100, two => 0o200, three => 0o400);
enum Shape (oval => 0o10, squiggle => 0o20, diamond => 0o40);
enum Style (solid => 0o1, open => 0o2, striped => 0o4);
Β
my @deck = Color.enums X Count.enums X Shape.enums X Style.enums;
Β
sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) {
sub show-cards(@c) { { printf "%9s%7s%10s%9s\n", @c[$_;*]Β».key } for ^@c }
Β
my @combinations = [^$DRAW].combinations(3);
Β
my @draw;
repeat until (my @sets) == $GOAL {
@draw = @deck.pick($DRAW);
my @bits = @draw.map: { [+] @^enumsΒ».value }
@sets = gather for @combinations -> @c {
take @draw[@c].item when /^ <[1247]>+ $/ given ( [+|] @bits[@c] ).base(8);
}
}
Β
say "Drew $DRAW cards:";
show-cards @draw;
for @sets.kv -> $i, @cards {
say "\nSet {$i+1}:";
show-cards @cards;
}
} |
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 optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Β Emirp primes
Β count in factors
Β prime decomposition
Β factors of an integer
Β extensible prime generator
Β primality by trial division
Β factors of a Mersenne number
Β trial factoring of a Mersenne number
Β partition an integer X into N primes
Β sequence of primes by Trial Division
| #11l | 11l | F primes_upto(limit)
V is_prime = [0B]*2 [+] [1B]*(limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n*n..limit).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
Β
print(primes_upto(100)) |
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 | #D | D | import std.bigint;
import std.math;
import std.stdio;
Β
bool isPrime(long test) {
if (test == 2) {
return true;
}
if (test % 2 == 0) {
return false;
}
for (long d = 3 ; d * d <= test; d += 2) {
if (test % d == 0) {
return false;
}
}
return true;
}
Β
int[] calcSmallPrimes(int numPrimes) {
int[] smallPrimes;
smallPrimes ~= 2;
Β
int count = 0;
int n = 3;
while (count < numPrimes) {
if (isPrime(n)) {
smallPrimes ~= n;
count++;
}
n += 2;
}
Β
return smallPrimes;
}
Β
immutable MAX = 45;
immutable smallPrimes = calcSmallPrimes(MAX);
Β
int getDivisorCount(long n) {
int count = 1;
while (n % 2 == 0) {
n /= 2;
count += 1;
}
for (long d = 3; d * d <= n; d += 2) {
long q = n / d;
long r = n % d;
int dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if (n != 1) {
count *= 2;
}
return count;
}
Β
BigInt OEISA073916(int n) {
if (isPrime(n) ) {
return BigInt(smallPrimes[n-1]) ^^ (n - 1);
}
int count = 0;
int result = 0;
for (int i = 1; count < n; i++) {
if (n % 2 == 1) {
// The solution for an odd (non-prime) term is always a square number
int root = cast(int) sqrt(cast(real) i);
if (root * root != i) {
continue;
}
}
if (getDivisorCount(i) == n) {
count++;
result = i;
}
}
return BigInt(result);
}
Β
void main() {
foreach (n; 1 .. MAX + 1) {
writeln("A073916(", n, ") = ", OEISA073916(n));
}
} |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #Clojure | Clojure | (defn consolidate-linked-sets [sets]
(apply clojure.set/union sets))
Β
(defn linked? [s1 s2]
(not (empty? (clojure.set/intersection s1 s2))))
Β
(defn consolidate [& sets]
(loop [seeds sets
sets sets]
(if (empty? seeds)
sets
(let [s0 (first seeds)
linked (filter #(linked? s0 %) sets)
remove-used (fn [sets used]
(remove #(contains? (set used) %) sets))]
(recur (remove-used (rest seeds) linked)
(conj (remove-used sets linked)
(consolidate-linked-sets linked))))))) |
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 n divisorsββ
See also
OEIS:A005179
| #C.2B.2B | C++ | #include <iostream>
Β
#define MAX 15
Β
using namespace std;
Β
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
Β
int main() {
int i, k, n, seq[MAX];
for (i = 0; i < MAX; ++i) seq[i] = 0;
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (i = 1, n = 0; n < MAX; ++i) {
k = count_divisors(i);
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i;
++n;
}
}
for (i = 0; i < MAX; ++i) cout << seq[i] << " ";
cout << endl;
return 0;
} |
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
| #Jsish | Jsish | /* SHA-256 hash in Jsish */
var str = 'Rosetta code';
puts(Util.hash(str, {type:'sha256'}));
Β
/*
=!EXPECTSTART!=
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
=!EXPECTEND!=
*/ |
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
| #Julia | Julia | msg = "Rosetta code"
Β
using Nettle
digest = hexdigest("sha256", msg)
Β
# native
using SHA
digest1 = join(num2hex.(sha256(msg)))
Β
@assert digest == digest1 |
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 number with exactly n divisorsββ
| #Factor | Factor | USING: io kernel math math.primes.factors prettyprint sequencesΒ ;
Β
: next ( n num -- n' num' )
[ 2dup divisors length = ] [ 1 + ] do until [ 1 + ] dipΒ ;
Β
: A069654 ( n -- seq )
[ 2 1 ] dip [ [ next ] keep ] replicate 2nipΒ ;
Β
"The first 15 terms of the sequence are:" print 15 A069654 . |
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 number with exactly n divisorsββ
| #FreeBASIC | FreeBASIC | #define UPTO 15
Β
function divisors(byval n as ulongint) as uinteger
'find the number of divisors of an integer
dim as integer r = 2, i
for i = 2 to n\2
if n mod i = 0 then r += 1
next i
return r
end function
Β
dim as ulongint i = 2
dim as integer n, nfound = 1
Β
print 1;" "; 'special case
Β
while nfound < UPTO
n = divisors(i)
if n = nfound + 1 then
nfound += 1
print i;" ";
end if
i+=1
wend
print
end |
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 standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Lingo | Lingo | crypto = xtra("Crypto").new()
put crypto.cx_sha1_string("Rosetta Code") |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #LiveCode | LiveCode | command shaRosettaCode
local shex, sha1
put sha1Digest("Rosetta Code") into sha1
get binaryDecode("H*",sha1,shex)
put shex
end shaRosettaCode |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Perl | Perl | sub dice5 { 1+int rand(5) }
Β
sub dice7 {
while(1) {
my $d7 = (5*dice5()+dice5()-6) % 8;
return $d7 if $d7;
}
}
Β
my %count7;
my $n = 1000000;
$count7{dice7()}++ for 1..$n;
printf "%s:Β %5.2f%%\n", $_, 100*($count7{$_}/$n*7-1) for sort keys %count7;
Β |
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 Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
| #Phix | Phix | function dice5()
return rand(5)
end function
function dice7()
while true do
integer r = dice5()*5+dice5()-3 -- ( ie 3..27, but )
if r<24 then return floor(r/3) end if -- (only 3..23 useful)
end while
end function
|
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
Β
var printHelper = Fn.new { |cat, le, lim, max|
var cle = Fmt.commatize(le)
var clim = Fmt.commatize(lim)
if (cat != "unsexy primes") cat = "sexy prime " + cat
System.print("Number ofΒ %(cat) less thanΒ %(clim) =Β %(cle)")
var last = (le < max) ? le : max
var verb = (last == 1) ? "is" : "are"
return [le, last, verb]
}
Β
var lim = 1000035
var sv = Int.primeSieve(lim-1, false)
var pairs = []
var trips = []
var quads = []
var quins = []
var unsexy = [2, 3]
var i = 3
while (i < lim) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
unsexy.add(i)
} else {
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pairs.add([i, i+6])
if (i < lim-12 && !sv[i+12]) {
trips.add([i, i+6, i+12])
if (i < lim-18 && !sv[i+18]) {
quads.add([i, i+6, i+12, i+18])
if (i < lim-24 && !sv[i+24]) {
quins.add([i, i+6, i+12, i+18, i+24])
}
}
}
}
}
i = i + 2
}
var le
var n
var verb
var unwrap = Fn.new { |t|
le = t[0]
n = t[1]
verb = t[2]
}
Β
unwrap.call(printHelper.call("pairs", pairs.count, lim, 5))
System.print("The lastΒ %(n)Β %(verb):\n Β %(pairs[le-n..-1])\n")
Β
unwrap.call(printHelper.call("triplets", trips.count, lim, 5))
System.print("The lastΒ %(n)Β %(verb):\n Β %(trips[le-n..-1])\n")
Β
unwrap.call(printHelper.call("quadruplets", quads.count, lim, 5))
System.print("The lastΒ %(n)Β %(verb):\n Β %(quads[le-n..-1])\n")
Β
unwrap.call(printHelper.call("quintuplets", quins.count, lim, 5))
System.print("The lastΒ %(n)Β %(verb):\n Β %(quins[le-n..-1])\n")
Β
unwrap.call(printHelper.call("unsexy primes", unsexy.count, lim, 10))
System.print("The lastΒ %(n)Β %(verb):\n Β %(unsexy[le-n..-1])\n") |
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
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
Β
import "fmt"
Β
func main() {
for i := 0; i < 16; i++ {
for j := 32 + i; j < 128; j += 16 {
k := string(j)
switch j {
case 32:
k = "Spc"
case 127:
k = "Del"
}
fmt.Printf("%3dΒ :Β %-3s ", j, k)
}
fmt.Println()
}
} |
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:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Phixmonti | Phixmonti | def sierpinski
2 swap power 1 - var lim
lim 0 -1 3 tolist for
var y
32 y 1 + repeat print
0 lim y - 2 tolist for
y bitand if 32 32 chain else "* " endif print
endfor
nl
endfor
enddef
Β
5 for
sierpinski
endfor |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the Β # Β character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Β Sierpinski triangle
| #Julia | Julia | function sierpinski(n::Integer, token::AbstractString="*")
x = fill(token, 1, 1)
for _ in 1:n
t = fill(" ", size(x))
x = [x x x; x t x; x x x]
end
return x
end
Β
function printsierpinski(m::Matrix)
for r in 1:size(m, 1)
println(join(m[r,Β :]))
end
end
Β
sierpinski(2, "#") |> printsierpinski |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #Nemerle | Nemerle | using System.Console;
Β
class ShortCircuit
{
public static a(xΒ : bool)Β : bool
{
WriteLine("a");
x
}
Β
public static b(xΒ : bool)Β : bool
{
WriteLine("b");
x
}
Β
public static Main()Β : void
{
def t = true;
def f = false;
Β
WriteLine("True && TrueΒ : {0}", a(t) && b(t));
WriteLine("True && False: {0}", a(t) && b(f));
WriteLine("False && TrueΒ : {0}", a(f) && b(t));
WriteLine("False && False: {0}", a(f) && b(f));
WriteLine("True || TrueΒ : {0}", a(t) || b(t));
WriteLine("True || False: {0}", a(t) || b(f));
WriteLine("False || TrueΒ : {0}", a(f) || b(t));
WriteLine("False || False: {0}", a(f) || b(f));
}
} |
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, and is to be minimized.
If we needed to compute the conjunction Β (and):
x = a() and b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β false, Β as the value of Β x Β can then only ever be Β false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of Β b() Β if the value of Β a() Β is computed as Β true, Β as the value of Β y Β can then only ever be Β true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called Β short-circuit evaluation Β of boolean expressions
Task
Create two functions named Β a Β and Β b, Β that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function Β b Β is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested Β Β if Β Β statements.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
Β
Parse Version v
Say 'Version='v
Β
If a() | b() Then Say 'a and b are true'
If \a() | b() Then Say 'Surprise'
Else Say 'ok'
Β
If a(), b() Then Say 'a is true'
If \a(), b() Then Say 'Surprise'
Else Say 'ok: \\a() is false'
Β
Select
When \a(), b() Then Say 'Surprise'
Otherwise Say 'ok: \\a() is false (Select)'
End
Return
Β
method a private static binary returns boolean
state = Boolean.TRUE.booleanValue()
Say '--a returns' state
Return state
Β
method b private static binary returns boolean
state = Boolean.TRUE.booleanValue()
Say '--b returns' state
Return state
Β |
http://rosettacode.org/wiki/Set_puzzle | Set puzzle | Set Puzzles are created with a deck of cards from the Set Gameβ’. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
There are 81 cards in a deck.
Each card contains a unique variation of the following four features: color, symbol, number and shading.
there are three colors:
Β Β Β red, green, purple
there are three symbols:
Β Β Β oval, squiggle, diamond
there is a number of symbols on the card:
Β Β Β one, two, three
there are three shadings:
Β Β Β solid, open, striped
Three cards form a set if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.
There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.
When creating sets you may use the same card more than once.
Task
Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.
For instance:
DEALT 9 CARDS:
green, one, oval, striped
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
red, three, oval, open
red, three, diamond, solid
CONTAINING 4 SETS:
green, one, oval, striped
purple, two, squiggle, open
red, three, diamond, solid
green, one, diamond, open
green, one, diamond, striped
green, one, diamond, solid
green, one, diamond, open
purple, two, squiggle, open
red, three, oval, open
purple, one, diamond, open
purple, two, squiggle, open
purple, three, oval, open
| #REXX | REXX | /*REXX program finds and displays "sets" (solutions) for the SET puzzle (game). */
parse arg game seed . /*get optional # cards to deal and seed*/
if game=='' | game=="," then game= 9 /*Not specified? Then use the default.*/
if seed=='' | seed=="," then seed= 77 /* " " " " " " */
call aGame 0 /*with tell=0: suppress the output. */
call aGame 1 /*with tell=1: display " " */
exit sets /*stick a fork in it, we're all done. */
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
aGame: parse arg tell; good= gameΒ % 2 /*enable/disable the showing of output.*/
/* [β] the GOOD var is the right #sets*/
do seed=seed until good==sets /*generate deals until good # of sets.*/
call random ,,seed /*repeatability for the RANDOM invokes.*/
call genFeatures /*generate various card game features. */
call genDeck /* " a deck (with 81 "cards").*/
call dealer game /*deal a number of cards for the game. */
call findSets game%2 /*find # of sets from the dealt cards. */
end /*until*/ /* [β] when leaving, SETS is right #.*/
return /*return to invoker of this subroutine.*/
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
dealer: call sey 'dealing' game "cards:", , . /*shuffle and deal the cards. */
Β
do cards=1 until cards==game /*keep dealing until finished. */
_= random(1, words(##) ) /*pick a card. */
##= delword(##, _, 1) /*delete " " */
@.cards= deck._ /*add the card to the tableau. */
call sey right('card' cards, 30) " " @.cards /*display a card to terminal.*/
Β
do j=1 for words(@.cards) /* [β] define cells for cards. */
@.cards.j= word(@.cards, j) /*define a cell for a card. */
end /*j*/
end /*cards*/
Β
return
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
defFeatures: parse arg what,v; _= words(v) /*obtain what is to be defined. */
Β
if _\==values then do; call sey 'error,' what "features Β¬=" values, ., .
exit -1
end /* [β] check for typos and/or errors. */
Β
do k=1 for words(values) /*define all the possible values. */
call value what'.'k, word(values, k) /*define a card feature. */
end /*k*/
Β
return
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
findSets: parse arg n; call genPoss /*N: the number of sets to be found. */
call sey /*find any sets that were generated [β]*/
Β
do j=1 for p /*P: is the number of possible sets. */
do f=1 for features
do g=1 for groups; Β !!.j.f.g= word(!.j.f, g)
end /*g*/
end /*f*/
Β
ok= 1 /*everything is peachyβkean (OK) so far*/
Β
do g=1 for groups
_=Β !!.j.1.g /*build strings to hold possibilities. */
equ= 1 /* [β] handles all the equal features.*/
Β
do f=2 to features while equ; equ= equ & _==!!.j.f.g
end /*f*/
Β
dif= 1
__=Β !!.j.1.g /* [β] handles all unequal features.*/
do f=2 to features while \equ
dif= dif & (wordpos(!!.j.f.g, __)==0)
__= __ Β !!.j.f.g /*append to string for next test*/
end /*f*/
Β
ok=ok & (equ | dif) /*now, see if all are equal or unequal.*/
end /*g*/
Β
if \ok then iterate /*Is this set OK? Nope, then skip it.*/
sets= sets + 1 /*bump the number of the sets found. */
call sey right('set' sets": ", 15) Β !.j.1 sep Β !.j.2 sep Β !.j.3
end /*j*/
Β
call sey sets 'sets found.', .
return
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
genDeck: #= 0; ##= /*#: cards in deck; ##: shuffle aid.*/
Β
do num=1 for values; xnum = word(numbers, num)
do col=1 for values; xcol = word(colors, col)
do sym=1 for values; xsym = word(symbols, sym)
do sha=1 for values; xsha = word(shadings, sha)
#= # + 1; ##= ## #;
deck.#= xnum xcol xsym xsha /*create a card. */
end /*sha*/
end /*num*/
end /*sym*/
end /*col*/
Β
return /*#: the number of cards in the deck. */
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
genFeatures: features= 3; groups= 4; values= 3 /*define # features, groups, values. */
numbers = 'one two three' Β ; call defFeatures 'number', numbers
colors = 'red green purple' Β ; call defFeatures 'color', colors
symbols = 'oval squiggle diamond' Β ; call defFeatures 'symbol', symbols
shadings= 'solid open striped' Β ; call defFeatures 'shading', shadings
return
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
genPoss: p= 0; sets= 0; sep=' βββββ ' /*define some REXX variables. */
Β !.=
do i=1 for game /* [β] the IFs eliminate duplicates.*/
do j=i+1 to game
do k=j+1 to game
p= p + 1; Β !.p.1= @.i; Β !.p.2= @.j; Β !.p.3= @.k
end /*k*/
end /*j*/
end /*i*/ /* [β] generate the permutation list. */
Β
return
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
sey: if \tell then return /*Β¬ tell? Then suppress the output. */
if arg(2)==. then say; say arg(1); if arg(3)==. then say; return |
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 optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Β Emirp primes
Β count in factors
Β prime decomposition
Β factors of an integer
Β extensible prime generator
Β primality by trial division
Β factors of a Mersenne number
Β trial factoring of a Mersenne number
Β partition an integer X into N primes
Β sequence of primes by Trial Division
| #360_Assembly | 360 Assembly | * Sieve of Eratosthenes
ERATOST CSECT
USING ERATOST,R12
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'ERATOST'
STM STM R14,R12,12(R13) save calling context
ST R13,4(R15)
ST R15,8(R13)
LR R12,R15 set addessability
* ---- CODE
LA R4,1 I=1
LA R6,1 increment
L R7,N limit
LOOPI BXH R4,R6,ENDLOOPI do I=2 to N
LR R1,R4 R1=I
BCTR R1,0
LA R14,CRIBLE(R1)
CLI 0(R14),X'01'
BNE ENDIF if not CRIBLE(I)
LR R5,R4 J=I
LR R8,R4
LR R9,R7
LOOPJ BXH R5,R8,ENDLOOPJ do J=I*2 to N by I
LR R1,R5 R1=J
BCTR R1,0
LA R14,CRIBLE(R1)
MVI 0(R14),X'00' CRIBLE(J)='0'B
B LOOPJ
ENDLOOPJ EQU *
ENDIF EQU *
B LOOPI
ENDLOOPI EQU *
LA R4,1 I=1
LA R6,1
L R7,N
LOOP BXH R4,R6,ENDLOOP do I=1 to N
LR R1,R4 R1=I
BCTR R1,0
LA R14,CRIBLE(R1)
CLI 0(R14),X'01'
BNE NOTPRIME if not CRIBLE(I)
CVD R4,P P=I
UNPK Z,P Z=P
MVC C,Z C=Z
OI C+L'C-1,X'F0' zap sign
MVC WTOBUF(8),C+8
WTO MF=(E,WTOMSG)
NOTPRIME EQU *
B LOOP
ENDLOOP EQU *
RETURN EQU *
LM R14,R12,12(R13) restore context
XR R15,R15 set return code to 0
BR R14 return to caller
* ---- DATA
I DS F
J DS F
DS 0F
P DS PL8 packed
Z DS ZL16 zoned
C DS CL16 character
WTOMSG DS 0F
DC H'80' length of WTO buffer
DC H'0' must be binary zeroes
WTOBUF DC 80C' '
LTORG
N DC F'100000'
CRIBLE DC 100000X'01'
YREGS
END ERATOST |
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.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
| #C | C | Β
#include <gmp.h>
Β
int main(void)
{
mpz_t p, s;
mpz_init_set_ui(p, 1);
mpz_init_set_ui(s, 1);
Β
for (int n = 1, i = 0; i < 20; n++) {
mpz_nextprime(s, s);
mpz_mul(p, p, s);
Β
mpz_add_ui(p, p, 1);
if (mpz_probab_prime_p(p, 25)) {
mpz_sub_ui(p, p, 1);
gmp_printf("%d\n", n);
i++;
continue;
}
Β
mpz_sub_ui(p, p, 2);
if (mpz_probab_prime_p(p, 25)) {
mpz_add_ui(p, p, 1);
gmp_printf("%d\n", n);
i++;
continue;
}
Β
mpz_add_ui(p, p, 1);
}
Β
mpz_clear(s);
mpz_clear(p);
}
Β |
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 | #Factor | Factor | USING: combinators formatting fry kernel lists lists.lazy
lists.lazy.examples literals math math.functions math.primes
math.primes.factors math.ranges sequencesΒ ;
IN: rosetta-code.nth-n-div
Β
CONSTANT: primes $[ 100 nprimes ]
Β
: prime ( m -- n ) 1 - [ primes nth ] [ ^ ] biΒ ;
Β
: (non-prime) ( m quot -- n )
'[
[ 1 - ] [ drop @ ] [ ] tri '[ divisors length _ = ]
lfilter swap [ cdr ] times car
] callΒ ; inline
Β
: non-prime ( m quot -- n )
{
{ [ over 2 = ] [ 2drop 3 ] }
{ [ over 10 = ] [ 2drop 405 ] }
[ (non-prime) ]
} condΒ ; inline
Β
: fn ( m -- n )
{
{ [ dup even? ] [ [ evens ] non-prime ] }
{ [ dup prime? ] [ prime ] }
[ [ squares ] non-prime ]
} condΒ ;
Β
: main ( -- ) 45 [1,b] [ dup fn "%2dΒ :Β %d\n" printf ] eachΒ ;
Β
MAIN: main |
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 | #FreeBASIC | FreeBASIC | Dim As Integer n, num, pnum
Dim As Ulongint m, p
Dim As Ulongint limit = 18446744073709551615
Β
Print "The first 15 terms of OEIS:A073916 are:"
For n = 1 To 15
num = 0
For m = 1 To limit
pnum = 0
For p = 1 To limit
If (m Mod p = 0) Then pnum += 1
Next p
If pnum = n Then num += 1
If num = n Then
Print Using "##Β : &"; n; m
Exit For
End If
Next m
Next n
Sleep |
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.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
| #Common_Lisp | Common Lisp | (defun consolidate (ss)
(labels ((comb (cs s)
(cond ((null s) cs)
((null cs) (list s))
((null (intersection s (first cs)))
(cons (first cs) (comb (rest cs) s)))
((consolidate (cons (union s (first cs)) (rest cs)))))))
(reduce #'comb ss :initial-value nil))) |
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 n divisorsββ
See also
OEIS:A005179
| #Cowgol | Cowgol | include "cowgol.coh";
Β
const AMOUNTΒ := 15;
typedef I is uint16;
Β
sub divisors(n: I): (count: I) is
var i: IΒ := 1;
countΒ := 0;
Β
while i*i <= n loop
if n%i == 0 then
if n/i == i then
countΒ := count + 1;
else
countΒ := count + 2;
end if;
end if;
iΒ := i + 1;
end loop;
end sub;
Β
var seq: I[AMOUNT+1];
MemZero(&seq as [uint8], @bytesof seq);
Β
var found: IΒ := 0;
var i: IΒ := 1;
Β
while found < AMOUNT loop
var divsΒ := divisors(i) as @indexof seq;
if divs <= AMOUNT and seq[divs] == 0 then
foundΒ := found + 1;
seq[divs]Β := i;
end if;
iΒ := i + 1;
end loop;
Β
var j: @indexof seqΒ := 1;
while j <= AMOUNT loop
print_i16(seq[j]);
print_char(' ');
jΒ := j + 1;
end loop;
print_nl(); |
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 n divisorsββ
See also
OEIS:A005179
| #F.23 | F# | Β
// Find AntΔ±-Primes plus. Nigel Galloway: April 9th., 2019
// Increasing the value 14 will increase the number of anti-primes plus found
let fI=primes|>Seq.take 14|>Seq.map bigint|>List.ofSeq
let N=Seq.reduce(*) fI
let fG g=Seq.unfold(fun ((n,i,e) as z)->Some(z,(n+1,i+1,(e*g)))) (1,2,g)
let fE n i=n|>Seq.collect(fun(n,e,g)->Seq.map(fun(a,c,b)->(a,c*e,g*b)) (i|>Seq.takeWhile(fun(g,_,_)->g<=n))|> Seq.takeWhile(fun(_,_,n)->n<N))
let fL=let mutable g=0 in (fun n->g<-g+1; n=g)
let n=Seq.concat(Seq.scan(fun n g->fE n (fG g)) (seq[(2147483647,1,1I)]) fI)|>List.ofSeq|>List.groupBy(fun(_,n,_)->n)|>List.sortBy(fun(n,_)->n)|>List.takeWhile(fun(n,_)->fL n)
for n,g in n do printfn "%d->%A" n (g|>List.map(fun(_,_,n)->n)|>List.min)
Β |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.