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/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #XSLT | XSLT | <xsl:variable name="foo" select="XPath expression" />
<xsl:if test="$foo = 4">... </xsl:if> <!-- prepend '$' to reference a variable or parameter--> |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Fortran | Fortran | IsNaN(x) |
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim i As Integer '' initialized to 0 by default
Dim j As Integer = 3 '' initialized to 3
Dim k As Integer = Any '' left uninitialized (compiler warning but can be ignored)
Print i, j, k
Sleep |
|
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #80386_Assembly | 80386 Assembly | #!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
# UNICHAR/UNICODE must be printed using REPR to convert to UTF8 #
MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 #
MODE UNICODE = FLEX[0]UNICHAR;
OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out);
OP INITUNICHAR = (CHAR char)UNICHAR: (UNICHAR out; bits OF out := BIN ABS char; out);
OP INITBITS = (UNICHAR unichar)BITS: #BIN# bits OF unichar;
PROC raise value error = ([]UNION(FORMAT,BITS,STRING)argv )VOID: (
putf(stand error, argv); stop
);
MODE YIELDCHAR = PROC(CHAR)VOID; MODE GENCHAR = PROC(YIELDCHAR)VOID;
MODE YIELDUNICHAR = PROC(UNICHAR)VOID; MODE GENUNICHAR = PROC(YIELDUNICHAR)VOID;
PRIO DOCONV = 1;
# Convert a stream of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (GENUNICHAR gen unichar, YIELDCHAR yield)VOID:(
BITS non ascii = NOT 2r1111111;
# FOR UNICHAR unichar IN # gen unichar( # ) DO ( #
## (UNICHAR unichar)VOID: (
BITS bits := INITBITS unichar;
IF (bits AND non ascii) = 2r0 THEN # ascii #
yield(REPR ABS bits)
ELSE
FLEX[6]CHAR buf := "?"*6; # initialise work around #
INT bytes := 0;
BITS byte lead bits = 2r10000000;
FOR ofs FROM UPB buf BY -1 WHILE
bytes +:= 1;
buf[ofs]:= REPR ABS (byte lead bits OR bits AND 2r111111);
bits := bits SHR 6;
# WHILE # bits NE 2r0 DO
SKIP
OD;
BITS first byte lead bits = BIN (ABS(2r1 SHL bytes)-2) SHL (UPB buf - bytes + 1);
buf := buf[UPB buf-bytes+1:];
buf[1] := REPR ABS(BIN ABS buf[1] OR first byte lead bits);
FOR i TO UPB buf DO yield(buf[i]) OD
FI
# OD # ))
);
# Convert a STRING into a stream of UNICHAR #
OP DOCONV = (STRING string, YIELDUNICHAR yield)VOID: (
PROC gen char = (YIELDCHAR yield)VOID:
FOR i FROM LWB string TO UPB string DO yield(string[i]) OD;
gen char DOCONV yield
);
CO Prosser/Thompson UTF8 encoding scheme
Bits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6
7 U+007F 0xxxxxxx
11 U+07FF 110xxxxx 10xxxxxx
16 U+FFFF 1110xxxx 10xxxxxx 10xxxxxx
21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
26 U+3FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
31 U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
END CO
# Quickly calculate the length of the UTF8 encoded string #
PROC upb utf8 = (STRING utf8 string)INT:(
INT bytes to go := 0;
INT upb := 0;
FOR i FROM LWB utf8 string TO UPB utf8 string DO
CHAR byte := utf8 string[i];
IF bytes to go = 0 THEN # start new utf char #
bytes to go :=
IF ABS byte <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF ABS byte <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF ABS byte <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF ABS byte <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF ABS byte <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF ABS byte <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN ABS byte)); ~ FI
FI;
bytes to go -:= 1; # skip over trailing bytes #
IF bytes to go = 0 THEN upb +:= 1 FI
OD;
upb
);
# Convert a stream of CHAR into a stream of UNICHAR #
OP DOCONV = (GENCHAR gen char, YIELDUNICHAR yield)VOID: (
INT bytes to go := 0;
INT lshift;
BITS mask, out;
# FOR CHAR byte IN # gen char( # ) DO ( #
## (CHAR byte)VOID: (
INT bits := ABS byte;
IF bytes to go = 0 THEN # start new unichar #
bytes to go :=
IF bits <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF bits <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF bits <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF bits <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF bits <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF bits <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN bits)); ~ FI;
IF bytes to go = 1 THEN
lshift := 7; mask := 2r1111111
ELSE
lshift := 7 - bytes to go; mask := BIN(ABS(2r1 SHL lshift)-1)
FI;
out := mask AND BIN bits;
lshift := 6; mask := 2r111111 # subsequently pic 6 bits at a time #
ELSE
out := (out SHL lshift) OR ( mask AND BIN bits)
FI;
bytes to go -:= 1;
IF bytes to go = 0 THEN yield(INITUNICHAR out) FI
# OD # ))
);
# Convert a string of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (UNICODE unicode, YIELDCHAR yield)VOID:(
PROC gen unichar = (YIELDUNICHAR yield)VOID:
FOR i FROM LWB unicode TO UPB unicode DO yield(unicode[i]) OD;
gen unichar DOCONV yield
);
# Some convenience/shorthand U operators #
# Convert a BITS into a UNICODE char #
OP U = (BITS bits)UNICHAR:
INITUNICHAR bits;
# Convert a []BITS into a UNICODE char #
OP U = ([]BITS array bits)[]UNICHAR:(
[LWB array bits:UPB array bits]UNICHAR out;
FOR i FROM LWB array bits TO UPB array bits DO bits OF out[i]:=array bits[i] OD;
out
);
# Convert a CHAR into a UNICODE char #
OP U = (CHAR char)UNICHAR:
INITUNICHAR char;
# Convert a STRING into a UNICODE string #
OP U = (STRING utf8 string)UNICODE: (
FLEX[upb utf8(utf8 string)]UNICHAR out;
INT i := 0;
# FOR UNICHAR char IN # utf8 string DOCONV (
## (UNICHAR char)VOID:
out[i+:=1] := char
# OD #);
out
);
# Convert a UNICODE string into a UTF8 STRING #
OP REPR = (UNICODE string)STRING: (
STRING out;
# FOR CHAR char IN # string DOCONV (
## (CHAR char)VOID: (
out +:= char
# OD #));
out
);
# define the most useful OPerators on UNICODE CHARacter arrays #
# Note: LWB, UPB and slicing works as per normal #
OP + = (UNICODE a,b)UNICODE: (
[UPB a + UPB b]UNICHAR out;
out[:UPB a]:= a; out[UPB a+1:]:= b;
out
);
OP + = (UNICODE a, UNICHAR b)UNICODE: a+UNICODE(b);
OP + = (UNICHAR a, UNICODE b)UNICODE: UNICODE(a)+b;
OP + = (UNICHAR a,b)UNICODE: UNICODE(a)+b;
# Suffix a character to the end of a UNICODE string #
OP +:= = (REF UNICODE a, UNICODE b)VOID: a := a + b;
OP +:= = (REF UNICODE a, UNICHAR b)VOID: a := a + b;
# Prefix a character to the beginning of a UNICODE string #
OP +=: = (UNICODE b, REF UNICODE a)VOID: a := b + a;
OP +=: = (UNICHAR b, REF UNICODE a)VOID: a := b + a;
OP * = (UNICODE a, INT n)UNICODE: (
UNICODE out := a;
FOR i FROM 2 TO n DO out +:= a OD;
out
);
OP * = (INT n, UNICODE a)UNICODE: a * n;
OP * = (UNICHAR a, INT n)UNICODE: UNICODE(a)*n;
OP * = (INT n, UNICHAR a)UNICODE: n*UNICODE(a);
OP *:= = (REF UNICODE a, INT b)VOID: a := a * b;
# Wirthy Operators #
OP LT = (UNICHAR a,b)BOOL: ABS bits OF a LT ABS bits OF b,
LE = (UNICHAR a,b)BOOL: ABS bits OF a LE ABS bits OF b,
EQ = (UNICHAR a,b)BOOL: ABS bits OF a EQ ABS bits OF b,
NE = (UNICHAR a,b)BOOL: ABS bits OF a NE ABS bits OF b,
GE = (UNICHAR a,b)BOOL: ABS bits OF a GE ABS bits OF b,
GT = (UNICHAR a,b)BOOL: ABS bits OF a GT ABS bits OF b;
# ASCII OPerators #
OP < = (UNICHAR a,b)BOOL: a LT b,
<= = (UNICHAR a,b)BOOL: a LE b,
= = (UNICHAR a,b)BOOL: a EQ b,
/= = (UNICHAR a,b)BOOL: a NE b,
>= = (UNICHAR a,b)BOOL: a GE b,
> = (UNICHAR a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICHAR a,b)BOOL: a LE b,
≠ = (UNICHAR a,b)BOOL: a NE b,
≥ = (UNICHAR a,b)BOOL: a GE b;
#
# Compare two UNICODE strings for equality #
PROC unicode cmp = (UNICODE str a,str b)INT: (
IF LWB str a > LWB str b THEN exit lt ELIF LWB str a < LWB str b THEN exit gt FI;
INT min upb = UPB(UPB str a < UPB str b | str a | str b );
FOR i FROM LWB str a TO min upb DO
UNICHAR a := str a[i], UNICHAR b := str b[i];
IF a < b THEN exit lt ELIF a > b THEN exit gt FI
OD;
IF UPB str a > UPB str b THEN exit gt ELIF UPB str a < UPB str b THEN exit lt FI;
exit eq: 0 EXIT
exit lt: -1 EXIT
exit gt: 1
);
OP LT = (UNICODE a,b)BOOL: unicode cmp(a,b)< 0,
LE = (UNICODE a,b)BOOL: unicode cmp(a,b)<=0,
EQ = (UNICODE a,b)BOOL: unicode cmp(a,b) =0,
NE = (UNICODE a,b)BOOL: unicode cmp(a,b)/=0,
GE = (UNICODE a,b)BOOL: unicode cmp(a,b)>=0,
GT = (UNICODE a,b)BOOL: unicode cmp(a,b)> 0;
# ASCII OPerators #
OP < = (UNICODE a,b)BOOL: a LT b,
<= = (UNICODE a,b)BOOL: a LE b,
= = (UNICODE a,b)BOOL: a EQ b,
/= = (UNICODE a,b)BOOL: a NE b,
>= = (UNICODE a,b)BOOL: a GE b,
> = (UNICODE a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICODE a,b)BOOL: a LE b,
≠ = (UNICODE a,b)BOOL: a NE b,
≥ = (UNICODE a,b)BOOL: a GE b;
#
COMMENT - Todo: for all UNICODE and UNICHAR
Add NonASCII OPerators: ×, ×:=,
Add ASCII Operators: &, &:=, &=:
Add Wirthy OPerators: PLUSTO, PLUSAB, TIMESAB for UNICODE/UNICHAR,
Add UNICODE against UNICHAR comparison OPerators,
Add char_in_string and string_in_string PROCedures,
Add standard Unicode functions:
to_upper_case, to_lower_case, unicode_block, char_count,
get_directionality, get_numeric_value, get_type, is_defined,
is_digit, is_identifier_ignorable, is_iso_control,
is_letter, is_letter_or_digit, is_lower_case, is_mirrored,
is_space_char, is_supplementary_code_point, is_title_case,
is_unicode_identifier_part, is_unicode_identifier_start,
is_upper_case, is_valid_code_point, is_whitespace
END COMMENT
test:(
UNICHAR aircraft := U16r 2708;
printf(($"aircraft: "$, $"16r"16rdddd$, UNICODE(aircraft), $g$, " => ", REPR UNICODE(aircraft), $l$));
UNICODE chinese forty two = U16r 56db + U16r 5341 + U16r 4e8c;
printf(($"chinese forty two: "$, $g$, REPR chinese forty two, ", length string = ", UPB chinese forty two, $l$));
UNICODE poker = U "A123456789♥♦♣♠JQK";
printf(($"poker: "$, $g$, REPR poker, ", length string = ", UPB poker, $l$));
UNICODE selectric := U"×÷≤≥≠¬∨∧⏨→↓↑□⌊⌈⎩⎧○⊥¢";
printf(($"selectric: "$, $g$, REPR selectric, $l$));
printf(($"selectric*4: "$, $g$, REPR(selectric*4), $l$));
print((
"1 < 2 is ", U"1" < U"2", ", ",
"111 < 11 is ",U"111" < U"11", ", ",
"111 < 12 is ",U"111" < U"12", ", ",
"♥ < ♦ is ", U"♥" < U"♦", ", ",
"♥Q < ♥K is ",U"♥Q" < U"♥K", " & ",
"♥J < ♥K is ",U"♥J" < U"♥K", new line
))
) |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #11l | 11l | V limit = 10'000'000
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 + 1).step(n)
is_prime[i] = 0B
F unprimeable(a)
I :is_prime[a]
R 0B
V d = 1
L d <= a
V base = (a I/ (d * 10)) * (d * 10) + (a % d)
I any((base .< base + d * 10).step(d).map(y -> :is_prime[y]))
R 0B
d *= 10
R 1B
F unprime(n)
[Int] r
L(a) 1..
I unprimeable(a)
r [+]= a
I r.len == n
L.break
R r
print(‘First 35:’)
print(unprime(35).map(i -> String(i)).join(‘ ’))
print("\nThe 600-th:")
print(unprime(600).last)
print()
V first = [0] * 10
V need = 10
L(p) 1..
I unprimeable(p)
V i = p % 10
I first[i] != 0
L.continue
first[i] = p
I --need == 0
L.break
L(v) first
print(L.index‘ ending: ’v) |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #AutoHotkey | AutoHotkey | Δ = 1
Δ++
MsgBox, % Δ |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #BaCon | BaCon | PRAGMA COMPILER clang
DECLARE Δ TYPE INT
Δ = 1
INCR Δ
PRINT Δ |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #11l | 11l | F randN(n)
‘1,0 random generator factory with 1 appearing 1/n'th of the time’
R () -> random:(@=n) == 0
F unbiased(biased)
‘uses a biased() generator of 1 or 0, to create an unbiased one’
V (this, that) = (biased(), biased())
L this == that
(this, that) = (biased(), biased())
R this
L(n) 3..6
V biased = randN(n)
V v = (0.<1000000).map(x -> @biased())
V (v1, v0) = (v.count(1), v.count(0))
print(‘Biased(#.): count1=#., count0=#., percent=#.2’.format(n, v1, v0, 100.0 * v1 / (v1 + v0)))
v = (0.<1000000).map(x -> unbiased(@biased))
(v1, v0) = (v.count(1), v.count(0))
print(‘ Unbiased: count1=#., count0=#., percent=#.2’.format(v1, v0, 100.0 * v1 / (v1 + v0))) |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #ALGOL_68 | ALGOL 68 | BEGIN # find some untouchable numbers - numbers not equal to the sum of the #
# proper divisors of any +ve integer #
INT max untouchable = 1 000 000;
# a table of the untouchable numbers #
[ 1 : max untouchable ]BOOL untouchable; FOR i TO UPB untouchable DO untouchable[ i ] := TRUE OD;
# show the counts of untouchable numbers found #
PROC show untouchable statistics = VOID:
BEGIN
print( ( "Untouchable numbers:", newline ) );
INT u count := 0;
FOR i TO UPB untouchable DO
IF untouchable[ i ] THEN u count +:= 1 FI;
IF i = 10
OR i = 100
OR i = 1 000
OR i = 10 000
OR i = 100 000
OR i = 1 000 000
THEN
print( ( whole( u count, -7 ), " to ", whole( i, -8 ), newline ) )
FI
OD
END; # show untouchable counts #
# prints the untouchable numbers up to n #
PROC print untouchables = ( INT n )VOID:
BEGIN
print( ( "Untouchable numbers up to ", whole( n, 0 ), newline ) );
INT u count := 0;
FOR i TO n DO
IF untouchable[ i ] THEN
print( ( whole( i, -4 ) ) );
IF u count +:= 1;
u count MOD 16 = 0
THEN print( ( newline ) )
ELSE print( ( " " ) )
FI
FI
OD;
print( ( newline ) );
print( ( whole( u count, -7 ), " to ", whole( n, -8 ), newline ) )
END; # print untouchables #
# find the untouchable numbers #
# to find untouchable numbers up to e.g.: 10 000, we need to sieve up to #
# 10 000 ^2 i.e. 100 000 000 #
# however if we also use the facts that no untouchable = prime + 1 #
# and no untouchable = odd prime + 3 and 5 is (very probably) the only #
# odd untouchable, other samples suggest we can use limit * 64 to find #
# untlouchables up to 1 000 000 - experimentation reveals this to be true #
# assume the conjecture that there are no odd untouchables except 5 #
BEGIN
untouchable[ 1 ] := FALSE;
untouchable[ 3 ] := FALSE;
FOR i FROM 7 BY 2 TO UPB untouchable DO untouchable[ i ] := FALSE OD
END;
# sieve the primes to max untouchable and flag the non untouchables #
BEGIN
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE max untouchable;
FOR i FROM 3 BY 2 TO UPB prime DO
IF prime[ i ] THEN
IF i < max untouchable THEN
untouchable[ i + 1 ] := FALSE;
IF i < ( max untouchable - 2 ) THEN
untouchable[ i + 3 ] := FALSE
FI
FI
FI
OD;
untouchable[ 2 + 1 ] := FALSE # special case for the only even prime #
END;
# construct the proper divisor sums and flag the non untouchables #
BEGIN
[ 1 : max untouchable * 64 ]INT spd;
FOR i TO UPB spd DO spd[ i ] := 1 OD;
FOR i FROM 2 TO UPB spd DO
FOR j FROM i + i BY i TO UPB spd DO spd[ j ] +:= i OD
OD;
FOR i TO UPB spd DO
IF spd[ i ] <= UPB untouchable THEN untouchable[ spd[ i ] ] := FALSE FI
OD
END;
# show the untouchable numbers up to 2000 #
print untouchables( 2 000 );
# show the counts of untouchable numbers #
show untouchable statistics
END |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Unix_ls
{
public class UnixLS
{
public static void Main(string[] args)
{
UnixLS ls = new UnixLS();
ls.list(args.Length.Equals(0) ? "." : args[0]);
}
private void list(string folder)
{
foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(fileSystemInfo.Name);
}
}
}
} |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #C.2B.2B | C++ |
#include <iostream>
#include <set>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main(void)
{
fs::path p(fs::current_path());
std::set<std::string> tree;
for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
tree.insert(it->path().filename().native());
for (auto entry : tree)
std::cout << entry << '\n';
}
|
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #PowerShell | PowerShell |
function dot-product($a,$b) {
$a[0]*$b[0] + $a[1]*$b[1] + $a[2]*$b[2]
}
function cross-product($a,$b) {
$v1 = $a[1]*$b[2] - $a[2]*$b[1]
$v2 = $a[2]*$b[0] - $a[0]*$b[2]
$v3 = $a[0]*$b[1] - $a[1]*$b[0]
@($v1,$v2,$v3)
}
function scalar-triple-product($a,$b,$c) {
dot-product $a (cross-product $b $c)
}
function vector-triple-product($a,$b) {
cross-product $a (cross-product $b $c)
}
$a = @(3, 4, 5)
$b = @(4, 3, 5)
$c = @(-5, -12, -13)
"a.b = $(dot-product $a $b)"
"axb = $(cross-product $a $b)"
"a.(bxc) = $(scalar-triple-product $a $b $c)"
"ax(bxc) = $(vector-triple-product $a $b $c)"
|
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Scheme | Scheme | (define str (read))
(define num (read))
(display "String = ") (display str)
(display "Integer = ") (display num) |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: integer_input is 0;
var string: string_input is "";
begin
write("Enter an integer: ");
readln(integer_input);
write("Enter a string: ");
readln(string_input);
end func; |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Z80_Assembly | Z80 Assembly | UserRam equ &C000
ld a,&50 ;load hexadecimal 50 into A
ld (UserRam),a ;initialize UserRam with a value of &50
ld a,&40 ;load hexadecimal 40 into A
ld (UserRam),a ;assign UserRam a new value of &40 |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #zkl | zkl | var v; // global to the class that encloses this file
class C{ var v } // global to class C, each instance gets a new v
class C{fcn f{var v=123;}} // v can only be seen by f, initialized when C is
class C{fcn init{var [const] v=5;}} // init is part of the constructor,
so vars are promoted yo class scope. This allows const vars to be created at
construction time
var v=123; v="hoho"; //not typed
class C{var v} // C.v OK, but just v is not found
class C{var[const]v=4} // C.v=3 illegal (compile or run time, depending)
class C{var[mixin]v=4} // the compiler treats v as an int for type checking
class C{var[proxy]v=f; fcn f{println("my name is ",self.fcn.name)} }
v acts like a property to run f so C.v is the same as C.f()
class C{reg r} // C.r is compile time error
r:=5; // := syntax is same as "reg r=5", convenience |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #GAP | GAP | IsBound(a);
# true
Unbind(a);
IsBound(a);
# false |
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Go | Go | package main
import "fmt"
var (
s []int
p *int
f func()
i interface{}
m map[int]int
c chan int
)
func main() {
fmt.Println("Exercise nil objects:")
status()
// initialize objects
s = make([]int, 1)
p = &s[0] // yes, reference element of slice just created
f = func() { fmt.Println("function call") }
i = user(0) // see user defined type just below
m = make(map[int]int)
c = make(chan int, 1)
fmt.Println("\nExercise objects after initialization:")
status()
}
type user int
func (user) m() {
fmt.Println("method call")
}
func status() {
trySlice()
tryPointer()
tryFunction()
tryInterface()
tryMap()
tryChannel()
}
func reportPanic() {
if x := recover(); x != nil {
fmt.Println("panic:", x)
}
}
func trySlice() {
defer reportPanic()
fmt.Println("s[0] =", s[0])
}
func tryPointer() {
defer reportPanic()
fmt.Println("*p =", *p)
}
func tryFunction() {
defer reportPanic()
f()
}
func tryInterface() {
defer reportPanic()
// normally the nil identifier accesses a nil value for one of
// six predefined types. In a type switch however, nil can be used
// as a type. In this case, it matches the nil interface.
switch i.(type) {
case nil:
fmt.Println("i is nil interface")
case interface {
m()
}:
fmt.Println("i has method m")
}
// assert type with method and then call method
i.(interface {
m()
}).m()
}
func tryMap() {
defer reportPanic()
m[0] = 0
fmt.Println("m[0] =", m[0])
}
func tryChannel() {
defer reportPanic()
close(c)
fmt.Println("channel closed")
} |
|
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #8th | 8th | #!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
# UNICHAR/UNICODE must be printed using REPR to convert to UTF8 #
MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 #
MODE UNICODE = FLEX[0]UNICHAR;
OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out);
OP INITUNICHAR = (CHAR char)UNICHAR: (UNICHAR out; bits OF out := BIN ABS char; out);
OP INITBITS = (UNICHAR unichar)BITS: #BIN# bits OF unichar;
PROC raise value error = ([]UNION(FORMAT,BITS,STRING)argv )VOID: (
putf(stand error, argv); stop
);
MODE YIELDCHAR = PROC(CHAR)VOID; MODE GENCHAR = PROC(YIELDCHAR)VOID;
MODE YIELDUNICHAR = PROC(UNICHAR)VOID; MODE GENUNICHAR = PROC(YIELDUNICHAR)VOID;
PRIO DOCONV = 1;
# Convert a stream of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (GENUNICHAR gen unichar, YIELDCHAR yield)VOID:(
BITS non ascii = NOT 2r1111111;
# FOR UNICHAR unichar IN # gen unichar( # ) DO ( #
## (UNICHAR unichar)VOID: (
BITS bits := INITBITS unichar;
IF (bits AND non ascii) = 2r0 THEN # ascii #
yield(REPR ABS bits)
ELSE
FLEX[6]CHAR buf := "?"*6; # initialise work around #
INT bytes := 0;
BITS byte lead bits = 2r10000000;
FOR ofs FROM UPB buf BY -1 WHILE
bytes +:= 1;
buf[ofs]:= REPR ABS (byte lead bits OR bits AND 2r111111);
bits := bits SHR 6;
# WHILE # bits NE 2r0 DO
SKIP
OD;
BITS first byte lead bits = BIN (ABS(2r1 SHL bytes)-2) SHL (UPB buf - bytes + 1);
buf := buf[UPB buf-bytes+1:];
buf[1] := REPR ABS(BIN ABS buf[1] OR first byte lead bits);
FOR i TO UPB buf DO yield(buf[i]) OD
FI
# OD # ))
);
# Convert a STRING into a stream of UNICHAR #
OP DOCONV = (STRING string, YIELDUNICHAR yield)VOID: (
PROC gen char = (YIELDCHAR yield)VOID:
FOR i FROM LWB string TO UPB string DO yield(string[i]) OD;
gen char DOCONV yield
);
CO Prosser/Thompson UTF8 encoding scheme
Bits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6
7 U+007F 0xxxxxxx
11 U+07FF 110xxxxx 10xxxxxx
16 U+FFFF 1110xxxx 10xxxxxx 10xxxxxx
21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
26 U+3FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
31 U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
END CO
# Quickly calculate the length of the UTF8 encoded string #
PROC upb utf8 = (STRING utf8 string)INT:(
INT bytes to go := 0;
INT upb := 0;
FOR i FROM LWB utf8 string TO UPB utf8 string DO
CHAR byte := utf8 string[i];
IF bytes to go = 0 THEN # start new utf char #
bytes to go :=
IF ABS byte <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF ABS byte <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF ABS byte <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF ABS byte <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF ABS byte <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF ABS byte <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN ABS byte)); ~ FI
FI;
bytes to go -:= 1; # skip over trailing bytes #
IF bytes to go = 0 THEN upb +:= 1 FI
OD;
upb
);
# Convert a stream of CHAR into a stream of UNICHAR #
OP DOCONV = (GENCHAR gen char, YIELDUNICHAR yield)VOID: (
INT bytes to go := 0;
INT lshift;
BITS mask, out;
# FOR CHAR byte IN # gen char( # ) DO ( #
## (CHAR byte)VOID: (
INT bits := ABS byte;
IF bytes to go = 0 THEN # start new unichar #
bytes to go :=
IF bits <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF bits <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF bits <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF bits <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF bits <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF bits <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN bits)); ~ FI;
IF bytes to go = 1 THEN
lshift := 7; mask := 2r1111111
ELSE
lshift := 7 - bytes to go; mask := BIN(ABS(2r1 SHL lshift)-1)
FI;
out := mask AND BIN bits;
lshift := 6; mask := 2r111111 # subsequently pic 6 bits at a time #
ELSE
out := (out SHL lshift) OR ( mask AND BIN bits)
FI;
bytes to go -:= 1;
IF bytes to go = 0 THEN yield(INITUNICHAR out) FI
# OD # ))
);
# Convert a string of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (UNICODE unicode, YIELDCHAR yield)VOID:(
PROC gen unichar = (YIELDUNICHAR yield)VOID:
FOR i FROM LWB unicode TO UPB unicode DO yield(unicode[i]) OD;
gen unichar DOCONV yield
);
# Some convenience/shorthand U operators #
# Convert a BITS into a UNICODE char #
OP U = (BITS bits)UNICHAR:
INITUNICHAR bits;
# Convert a []BITS into a UNICODE char #
OP U = ([]BITS array bits)[]UNICHAR:(
[LWB array bits:UPB array bits]UNICHAR out;
FOR i FROM LWB array bits TO UPB array bits DO bits OF out[i]:=array bits[i] OD;
out
);
# Convert a CHAR into a UNICODE char #
OP U = (CHAR char)UNICHAR:
INITUNICHAR char;
# Convert a STRING into a UNICODE string #
OP U = (STRING utf8 string)UNICODE: (
FLEX[upb utf8(utf8 string)]UNICHAR out;
INT i := 0;
# FOR UNICHAR char IN # utf8 string DOCONV (
## (UNICHAR char)VOID:
out[i+:=1] := char
# OD #);
out
);
# Convert a UNICODE string into a UTF8 STRING #
OP REPR = (UNICODE string)STRING: (
STRING out;
# FOR CHAR char IN # string DOCONV (
## (CHAR char)VOID: (
out +:= char
# OD #));
out
);
# define the most useful OPerators on UNICODE CHARacter arrays #
# Note: LWB, UPB and slicing works as per normal #
OP + = (UNICODE a,b)UNICODE: (
[UPB a + UPB b]UNICHAR out;
out[:UPB a]:= a; out[UPB a+1:]:= b;
out
);
OP + = (UNICODE a, UNICHAR b)UNICODE: a+UNICODE(b);
OP + = (UNICHAR a, UNICODE b)UNICODE: UNICODE(a)+b;
OP + = (UNICHAR a,b)UNICODE: UNICODE(a)+b;
# Suffix a character to the end of a UNICODE string #
OP +:= = (REF UNICODE a, UNICODE b)VOID: a := a + b;
OP +:= = (REF UNICODE a, UNICHAR b)VOID: a := a + b;
# Prefix a character to the beginning of a UNICODE string #
OP +=: = (UNICODE b, REF UNICODE a)VOID: a := b + a;
OP +=: = (UNICHAR b, REF UNICODE a)VOID: a := b + a;
OP * = (UNICODE a, INT n)UNICODE: (
UNICODE out := a;
FOR i FROM 2 TO n DO out +:= a OD;
out
);
OP * = (INT n, UNICODE a)UNICODE: a * n;
OP * = (UNICHAR a, INT n)UNICODE: UNICODE(a)*n;
OP * = (INT n, UNICHAR a)UNICODE: n*UNICODE(a);
OP *:= = (REF UNICODE a, INT b)VOID: a := a * b;
# Wirthy Operators #
OP LT = (UNICHAR a,b)BOOL: ABS bits OF a LT ABS bits OF b,
LE = (UNICHAR a,b)BOOL: ABS bits OF a LE ABS bits OF b,
EQ = (UNICHAR a,b)BOOL: ABS bits OF a EQ ABS bits OF b,
NE = (UNICHAR a,b)BOOL: ABS bits OF a NE ABS bits OF b,
GE = (UNICHAR a,b)BOOL: ABS bits OF a GE ABS bits OF b,
GT = (UNICHAR a,b)BOOL: ABS bits OF a GT ABS bits OF b;
# ASCII OPerators #
OP < = (UNICHAR a,b)BOOL: a LT b,
<= = (UNICHAR a,b)BOOL: a LE b,
= = (UNICHAR a,b)BOOL: a EQ b,
/= = (UNICHAR a,b)BOOL: a NE b,
>= = (UNICHAR a,b)BOOL: a GE b,
> = (UNICHAR a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICHAR a,b)BOOL: a LE b,
≠ = (UNICHAR a,b)BOOL: a NE b,
≥ = (UNICHAR a,b)BOOL: a GE b;
#
# Compare two UNICODE strings for equality #
PROC unicode cmp = (UNICODE str a,str b)INT: (
IF LWB str a > LWB str b THEN exit lt ELIF LWB str a < LWB str b THEN exit gt FI;
INT min upb = UPB(UPB str a < UPB str b | str a | str b );
FOR i FROM LWB str a TO min upb DO
UNICHAR a := str a[i], UNICHAR b := str b[i];
IF a < b THEN exit lt ELIF a > b THEN exit gt FI
OD;
IF UPB str a > UPB str b THEN exit gt ELIF UPB str a < UPB str b THEN exit lt FI;
exit eq: 0 EXIT
exit lt: -1 EXIT
exit gt: 1
);
OP LT = (UNICODE a,b)BOOL: unicode cmp(a,b)< 0,
LE = (UNICODE a,b)BOOL: unicode cmp(a,b)<=0,
EQ = (UNICODE a,b)BOOL: unicode cmp(a,b) =0,
NE = (UNICODE a,b)BOOL: unicode cmp(a,b)/=0,
GE = (UNICODE a,b)BOOL: unicode cmp(a,b)>=0,
GT = (UNICODE a,b)BOOL: unicode cmp(a,b)> 0;
# ASCII OPerators #
OP < = (UNICODE a,b)BOOL: a LT b,
<= = (UNICODE a,b)BOOL: a LE b,
= = (UNICODE a,b)BOOL: a EQ b,
/= = (UNICODE a,b)BOOL: a NE b,
>= = (UNICODE a,b)BOOL: a GE b,
> = (UNICODE a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICODE a,b)BOOL: a LE b,
≠ = (UNICODE a,b)BOOL: a NE b,
≥ = (UNICODE a,b)BOOL: a GE b;
#
COMMENT - Todo: for all UNICODE and UNICHAR
Add NonASCII OPerators: ×, ×:=,
Add ASCII Operators: &, &:=, &=:
Add Wirthy OPerators: PLUSTO, PLUSAB, TIMESAB for UNICODE/UNICHAR,
Add UNICODE against UNICHAR comparison OPerators,
Add char_in_string and string_in_string PROCedures,
Add standard Unicode functions:
to_upper_case, to_lower_case, unicode_block, char_count,
get_directionality, get_numeric_value, get_type, is_defined,
is_digit, is_identifier_ignorable, is_iso_control,
is_letter, is_letter_or_digit, is_lower_case, is_mirrored,
is_space_char, is_supplementary_code_point, is_title_case,
is_unicode_identifier_part, is_unicode_identifier_start,
is_upper_case, is_valid_code_point, is_whitespace
END COMMENT
test:(
UNICHAR aircraft := U16r 2708;
printf(($"aircraft: "$, $"16r"16rdddd$, UNICODE(aircraft), $g$, " => ", REPR UNICODE(aircraft), $l$));
UNICODE chinese forty two = U16r 56db + U16r 5341 + U16r 4e8c;
printf(($"chinese forty two: "$, $g$, REPR chinese forty two, ", length string = ", UPB chinese forty two, $l$));
UNICODE poker = U "A123456789♥♦♣♠JQK";
printf(($"poker: "$, $g$, REPR poker, ", length string = ", UPB poker, $l$));
UNICODE selectric := U"×÷≤≥≠¬∨∧⏨→↓↑□⌊⌈⎩⎧○⊥¢";
printf(($"selectric: "$, $g$, REPR selectric, $l$));
printf(($"selectric*4: "$, $g$, REPR(selectric*4), $l$));
print((
"1 < 2 is ", U"1" < U"2", ", ",
"111 < 11 is ",U"111" < U"11", ", ",
"111 < 12 is ",U"111" < U"12", ", ",
"♥ < ♦ is ", U"♥" < U"♦", ", ",
"♥Q < ♥K is ",U"♥Q" < U"♥K", " & ",
"♥J < ♥K is ",U"♥J" < U"♥K", new line
))
) |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #ALGOL_68 | ALGOL 68 | BEGIN # find unprimable numbers - numbers which can't be made into a prime by changing one digit #
# construct a sieve of primes up to max prime #
PR read "primes.incl.a68" PR
INT max prime = 9 999 999;
[]BOOL prime = PRIMESIEVE max prime;
# returns TRUE if n is unprimeable, FALSE otherwise #
PROC is unprimeable = ( INT n )BOOL:
IF n < 100
THEN FALSE
ELIF prime[ n ]
THEN FALSE
ELIF
# need to try changing a digit #
INT last digit = n MOD 10;
INT leading digits = n - last digit;
prime[ leading digits + 1 ]
THEN FALSE
ELIF prime[ leading digits + 3 ] THEN FALSE
ELIF prime[ leading digits + 7 ] THEN FALSE
ELIF prime[ leading digits + 9 ] THEN FALSE
ELIF last digit = 2 OR last digit = 5
THEN
# the final digit is 2 or 5, changing the other digits can't make a prime #
# unless there is only one other digit which we change to 0 #
INT v := leading digits;
INT dc := 1;
WHILE ( v OVERAB 10 ) > 0 DO IF v MOD 10 /= 0 THEN dc +:= 1 FI OD;
dc /= 2
ELIF NOT ODD last digit
THEN TRUE # last digit is even - can't make a prime #
ELSE
# last digit is 1, 3, 7, 9: must try changing the other digoits #
INT m10 := 10;
INT r10 := 100;
BOOL result := TRUE;
WHILE result AND n > r10 DO
INT base = ( ( n OVER r10 ) * r10 ) + ( n MOD m10 );
FOR i FROM 0 BY m10 WHILE result AND i < r10 DO
result := NOT prime[ base + i ]
OD;
m10 *:= 10;
r10 *:= 10
OD;
IF result THEN
# still not unprimeable, try changing the first digit #
INT base = n MOD m10;
FOR i FROM 0 BY m10 WHILE result AND i < r10 DO
result := NOT prime[ base + i ]
OD
FI;
result
FI # is unprimeable # ;
# returns a string representation of n with commas #
PROC commatise = ( LONG LONG INT n )STRING:
BEGIN
STRING result := "";
STRING unformatted = whole( n, 0 );
INT ch count := 0;
FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
IF ch count <= 2 THEN ch count +:= 1
ELSE ch count := 1; "," +=: result
FI;
unformatted[ c ] +=: result
OD;
result
END; # commatise #
# find unprimeable numbers #
INT u count := 0;
INT d count := 0;
[ 0 : 9 ]INT first unprimeable := []INT( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 )[ AT 0 ];
FOR i FROM 100 WHILE i < UPB prime AND d count < 10 DO
IF is unprimeable( i ) THEN
u count +:= 1;
IF u count = 1 THEN
print( ( "First 35 unprimeable numbers: ", whole( i, 0 ) ) )
ELIF u count <= 35 THEN
print( ( " ", whole( i, 0 ) ) )
ELIF u count = 600 THEN
print( ( newline, "600th unprimeable number: ", commatise( i ) ) )
FI;
INT final digit = i MOD 10;
IF first unprimeable[ final digit ] = 0 THEN
# first unprimeable number with this final digit #
d count +:= 1;
first unprimeable[ final digit ] := i
FI
FI
OD;
# show the first unprimeable number that ends with each digit #
print( ( newline ) );
FOR i FROM 0 TO 9 DO
print( ( "First unprimeable number ending in "
, whole( i, 0 )
, ": "
, commatise( first unprimeable[ i ] )
, newline
)
)
OD
END |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Bracmat | Bracmat | ( (Δ=1)
& 1+!Δ:?Δ
& out$("Δ:" !Δ)
); |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #C | C | // Works for clang and GCC 10+
#include<stdio.h>
int main() {
int Δ = 1; // if unsupported, use \u0394
Δ++;
printf("%d",Δ);
return 0;
} |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #Ada | Ada | with Ada.Text_IO; with Ada.Numerics.Discrete_Random;
procedure Bias_Unbias is
Modulus: constant Integer := 60; -- lcm of {3,4,5,6}
type M is mod Modulus;
package Rand is new Ada.Numerics.Discrete_Random(M);
Gen: Rand.Generator;
subtype Bit is Integer range 0 .. 1;
function Biased_Bit(Bias_Base: Integer) return Bit is
begin
if (Integer(Rand.Random(Gen))* Bias_Base) / Modulus > 0 then
return 0;
else
return 1;
end if;
end Biased_Bit;
function Unbiased_Bit(Bias_Base: Integer) return Bit is
A, B: Bit := 0;
begin
while A = B loop
A := Biased_Bit(Bias_Base);
B := Biased_Bit(Bias_Base);
end loop;
return A;
end Unbiased_Bit;
package FIO is new Ada.Text_IO.Float_IO(Float);
Counter_B, Counter_U: Natural;
Number_Of_Samples: constant Natural := 10_000;
begin
Rand.Reset(Gen);
Ada.Text_IO.Put_Line(" I Biased% UnBiased%");
for I in 3 .. 6 loop
Counter_B := 0;
Counter_U := 0;
for J in 1 .. Number_Of_Samples loop
Counter_B := Counter_B + Biased_Bit(I);
Counter_U := Counter_U + Unbiased_Bit(I);
end loop;
Ada.Text_IO.Put(Integer'Image(I));
FIO.Put(100.0 * Float(Counter_B) / Float(Number_Of_Samples), 5, 2, 0);
FIO.Put(100.0 * Float(Counter_U) / Float(Number_Of_Samples), 5, 2, 0);
Ada.Text_IO.New_Line;
end loop;
end Bias_Unbias; |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #C.2B.2B | C++ |
// Untouchable Numbers : Nigel Galloway - March 4th., 2021;
#include <functional>
#include <bitset>
#include <iostream>
#include <cmath>
using namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;
const int maxUT{3000000}, dL{(int)log2(maxUT)};
struct uT{
bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};
void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}
Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}
Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}
Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}
void fL(Z3 n, int g){for(;;){
if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}
if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}
if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}
if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}
}
int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}
uT(const int n):mUT{n}{
N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();
N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);
}
};
|
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Clojure | Clojure | (def files (sort (filter #(= "." (.getParent %)) (file-seq (clojure.java.io/file ".")))))
(doseq [n files] (println (.getName n))) |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Common_Lisp | Common Lisp | (defun files-list (&optional (path "."))
(let* ((dir (concatenate 'string path "/"))
(abs-path (car (directory dir)))
(file-pattern (concatenate 'string dir "*"))
(subdir-pattern (concatenate 'string file-pattern "/")))
(remove-duplicates
(mapcar (lambda (p) (enough-namestring p abs-path))
(mapcan #'directory (list file-pattern subdir-pattern)))
:test #'string-equal)))
(defun ls (&optional (path "."))
(format t "~{~a~%~}" (sort (files-list path) #'string-lessp))) |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Prolog | Prolog |
dot_product([A1, A2, A3], [B1, B2, B3], Ans) :-
Ans is A1 * B1 + A2 * B2 + A3 * B3.
cross_product([A1, A2, A3], [B1, B2, B3], Ans) :-
T1 is A2 * B3 - A3 * B2,
T2 is A3 * B1 - A1 * B3,
T3 is A1 * B2 - A2 * B1,
Ans = [T1, T2, T3].
scala_triple(A, B, C, Ans) :-
cross_product(B, C, Temp),
dot_product(A, Temp, Ans).
vector_triple(A, B, C, Ans) :-
cross_product(B, C, Temp),
cross_product(A, Temp, Ans).
|
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Sidef | Sidef | var s = read(String);
var i = read(Number); # auto-conversion to a number |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Slate | Slate | print: (query: 'Enter a String: ').
[| n |
n: (Integer readFrom: (query: 'Enter an Integer: ')).
(n is: Integer)
ifTrue: [print: n]
ifFalse: [inform: 'Not an integer: ' ; n printString]
] do. |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Zoea | Zoea | program: variables
# The concept of variables is completely alien in zoea:
# there is no support for variables and no way of defining or using them.
# Instead programs are described by giving examples of input and output values.
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Haskell | Haskell | main = print $ "Incoming error--" ++ undefined
-- When run in GHC:
-- "Incoming error--*** Exception: Prelude.undefined |
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Icon_and_Unicon | Icon and Unicon | global G1
procedure main(arglist)
local ML1
static MS1
undeftest()
end
procedure undeftest(P1)
static S1
local L1,L2
every #write all local, parameter, static, and global variable names
write((localnames|paramnames|staticnames|globalnames)(¤t,0)) # ... visible in the current co-expression at this calling level (0)
return
end |
|
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #Ada | Ada | #!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
# UNICHAR/UNICODE must be printed using REPR to convert to UTF8 #
MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 #
MODE UNICODE = FLEX[0]UNICHAR;
OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out);
OP INITUNICHAR = (CHAR char)UNICHAR: (UNICHAR out; bits OF out := BIN ABS char; out);
OP INITBITS = (UNICHAR unichar)BITS: #BIN# bits OF unichar;
PROC raise value error = ([]UNION(FORMAT,BITS,STRING)argv )VOID: (
putf(stand error, argv); stop
);
MODE YIELDCHAR = PROC(CHAR)VOID; MODE GENCHAR = PROC(YIELDCHAR)VOID;
MODE YIELDUNICHAR = PROC(UNICHAR)VOID; MODE GENUNICHAR = PROC(YIELDUNICHAR)VOID;
PRIO DOCONV = 1;
# Convert a stream of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (GENUNICHAR gen unichar, YIELDCHAR yield)VOID:(
BITS non ascii = NOT 2r1111111;
# FOR UNICHAR unichar IN # gen unichar( # ) DO ( #
## (UNICHAR unichar)VOID: (
BITS bits := INITBITS unichar;
IF (bits AND non ascii) = 2r0 THEN # ascii #
yield(REPR ABS bits)
ELSE
FLEX[6]CHAR buf := "?"*6; # initialise work around #
INT bytes := 0;
BITS byte lead bits = 2r10000000;
FOR ofs FROM UPB buf BY -1 WHILE
bytes +:= 1;
buf[ofs]:= REPR ABS (byte lead bits OR bits AND 2r111111);
bits := bits SHR 6;
# WHILE # bits NE 2r0 DO
SKIP
OD;
BITS first byte lead bits = BIN (ABS(2r1 SHL bytes)-2) SHL (UPB buf - bytes + 1);
buf := buf[UPB buf-bytes+1:];
buf[1] := REPR ABS(BIN ABS buf[1] OR first byte lead bits);
FOR i TO UPB buf DO yield(buf[i]) OD
FI
# OD # ))
);
# Convert a STRING into a stream of UNICHAR #
OP DOCONV = (STRING string, YIELDUNICHAR yield)VOID: (
PROC gen char = (YIELDCHAR yield)VOID:
FOR i FROM LWB string TO UPB string DO yield(string[i]) OD;
gen char DOCONV yield
);
CO Prosser/Thompson UTF8 encoding scheme
Bits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6
7 U+007F 0xxxxxxx
11 U+07FF 110xxxxx 10xxxxxx
16 U+FFFF 1110xxxx 10xxxxxx 10xxxxxx
21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
26 U+3FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
31 U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
END CO
# Quickly calculate the length of the UTF8 encoded string #
PROC upb utf8 = (STRING utf8 string)INT:(
INT bytes to go := 0;
INT upb := 0;
FOR i FROM LWB utf8 string TO UPB utf8 string DO
CHAR byte := utf8 string[i];
IF bytes to go = 0 THEN # start new utf char #
bytes to go :=
IF ABS byte <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF ABS byte <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF ABS byte <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF ABS byte <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF ABS byte <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF ABS byte <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN ABS byte)); ~ FI
FI;
bytes to go -:= 1; # skip over trailing bytes #
IF bytes to go = 0 THEN upb +:= 1 FI
OD;
upb
);
# Convert a stream of CHAR into a stream of UNICHAR #
OP DOCONV = (GENCHAR gen char, YIELDUNICHAR yield)VOID: (
INT bytes to go := 0;
INT lshift;
BITS mask, out;
# FOR CHAR byte IN # gen char( # ) DO ( #
## (CHAR byte)VOID: (
INT bits := ABS byte;
IF bytes to go = 0 THEN # start new unichar #
bytes to go :=
IF bits <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF bits <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF bits <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF bits <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF bits <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF bits <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN bits)); ~ FI;
IF bytes to go = 1 THEN
lshift := 7; mask := 2r1111111
ELSE
lshift := 7 - bytes to go; mask := BIN(ABS(2r1 SHL lshift)-1)
FI;
out := mask AND BIN bits;
lshift := 6; mask := 2r111111 # subsequently pic 6 bits at a time #
ELSE
out := (out SHL lshift) OR ( mask AND BIN bits)
FI;
bytes to go -:= 1;
IF bytes to go = 0 THEN yield(INITUNICHAR out) FI
# OD # ))
);
# Convert a string of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (UNICODE unicode, YIELDCHAR yield)VOID:(
PROC gen unichar = (YIELDUNICHAR yield)VOID:
FOR i FROM LWB unicode TO UPB unicode DO yield(unicode[i]) OD;
gen unichar DOCONV yield
);
# Some convenience/shorthand U operators #
# Convert a BITS into a UNICODE char #
OP U = (BITS bits)UNICHAR:
INITUNICHAR bits;
# Convert a []BITS into a UNICODE char #
OP U = ([]BITS array bits)[]UNICHAR:(
[LWB array bits:UPB array bits]UNICHAR out;
FOR i FROM LWB array bits TO UPB array bits DO bits OF out[i]:=array bits[i] OD;
out
);
# Convert a CHAR into a UNICODE char #
OP U = (CHAR char)UNICHAR:
INITUNICHAR char;
# Convert a STRING into a UNICODE string #
OP U = (STRING utf8 string)UNICODE: (
FLEX[upb utf8(utf8 string)]UNICHAR out;
INT i := 0;
# FOR UNICHAR char IN # utf8 string DOCONV (
## (UNICHAR char)VOID:
out[i+:=1] := char
# OD #);
out
);
# Convert a UNICODE string into a UTF8 STRING #
OP REPR = (UNICODE string)STRING: (
STRING out;
# FOR CHAR char IN # string DOCONV (
## (CHAR char)VOID: (
out +:= char
# OD #));
out
);
# define the most useful OPerators on UNICODE CHARacter arrays #
# Note: LWB, UPB and slicing works as per normal #
OP + = (UNICODE a,b)UNICODE: (
[UPB a + UPB b]UNICHAR out;
out[:UPB a]:= a; out[UPB a+1:]:= b;
out
);
OP + = (UNICODE a, UNICHAR b)UNICODE: a+UNICODE(b);
OP + = (UNICHAR a, UNICODE b)UNICODE: UNICODE(a)+b;
OP + = (UNICHAR a,b)UNICODE: UNICODE(a)+b;
# Suffix a character to the end of a UNICODE string #
OP +:= = (REF UNICODE a, UNICODE b)VOID: a := a + b;
OP +:= = (REF UNICODE a, UNICHAR b)VOID: a := a + b;
# Prefix a character to the beginning of a UNICODE string #
OP +=: = (UNICODE b, REF UNICODE a)VOID: a := b + a;
OP +=: = (UNICHAR b, REF UNICODE a)VOID: a := b + a;
OP * = (UNICODE a, INT n)UNICODE: (
UNICODE out := a;
FOR i FROM 2 TO n DO out +:= a OD;
out
);
OP * = (INT n, UNICODE a)UNICODE: a * n;
OP * = (UNICHAR a, INT n)UNICODE: UNICODE(a)*n;
OP * = (INT n, UNICHAR a)UNICODE: n*UNICODE(a);
OP *:= = (REF UNICODE a, INT b)VOID: a := a * b;
# Wirthy Operators #
OP LT = (UNICHAR a,b)BOOL: ABS bits OF a LT ABS bits OF b,
LE = (UNICHAR a,b)BOOL: ABS bits OF a LE ABS bits OF b,
EQ = (UNICHAR a,b)BOOL: ABS bits OF a EQ ABS bits OF b,
NE = (UNICHAR a,b)BOOL: ABS bits OF a NE ABS bits OF b,
GE = (UNICHAR a,b)BOOL: ABS bits OF a GE ABS bits OF b,
GT = (UNICHAR a,b)BOOL: ABS bits OF a GT ABS bits OF b;
# ASCII OPerators #
OP < = (UNICHAR a,b)BOOL: a LT b,
<= = (UNICHAR a,b)BOOL: a LE b,
= = (UNICHAR a,b)BOOL: a EQ b,
/= = (UNICHAR a,b)BOOL: a NE b,
>= = (UNICHAR a,b)BOOL: a GE b,
> = (UNICHAR a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICHAR a,b)BOOL: a LE b,
≠ = (UNICHAR a,b)BOOL: a NE b,
≥ = (UNICHAR a,b)BOOL: a GE b;
#
# Compare two UNICODE strings for equality #
PROC unicode cmp = (UNICODE str a,str b)INT: (
IF LWB str a > LWB str b THEN exit lt ELIF LWB str a < LWB str b THEN exit gt FI;
INT min upb = UPB(UPB str a < UPB str b | str a | str b );
FOR i FROM LWB str a TO min upb DO
UNICHAR a := str a[i], UNICHAR b := str b[i];
IF a < b THEN exit lt ELIF a > b THEN exit gt FI
OD;
IF UPB str a > UPB str b THEN exit gt ELIF UPB str a < UPB str b THEN exit lt FI;
exit eq: 0 EXIT
exit lt: -1 EXIT
exit gt: 1
);
OP LT = (UNICODE a,b)BOOL: unicode cmp(a,b)< 0,
LE = (UNICODE a,b)BOOL: unicode cmp(a,b)<=0,
EQ = (UNICODE a,b)BOOL: unicode cmp(a,b) =0,
NE = (UNICODE a,b)BOOL: unicode cmp(a,b)/=0,
GE = (UNICODE a,b)BOOL: unicode cmp(a,b)>=0,
GT = (UNICODE a,b)BOOL: unicode cmp(a,b)> 0;
# ASCII OPerators #
OP < = (UNICODE a,b)BOOL: a LT b,
<= = (UNICODE a,b)BOOL: a LE b,
= = (UNICODE a,b)BOOL: a EQ b,
/= = (UNICODE a,b)BOOL: a NE b,
>= = (UNICODE a,b)BOOL: a GE b,
> = (UNICODE a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICODE a,b)BOOL: a LE b,
≠ = (UNICODE a,b)BOOL: a NE b,
≥ = (UNICODE a,b)BOOL: a GE b;
#
COMMENT - Todo: for all UNICODE and UNICHAR
Add NonASCII OPerators: ×, ×:=,
Add ASCII Operators: &, &:=, &=:
Add Wirthy OPerators: PLUSTO, PLUSAB, TIMESAB for UNICODE/UNICHAR,
Add UNICODE against UNICHAR comparison OPerators,
Add char_in_string and string_in_string PROCedures,
Add standard Unicode functions:
to_upper_case, to_lower_case, unicode_block, char_count,
get_directionality, get_numeric_value, get_type, is_defined,
is_digit, is_identifier_ignorable, is_iso_control,
is_letter, is_letter_or_digit, is_lower_case, is_mirrored,
is_space_char, is_supplementary_code_point, is_title_case,
is_unicode_identifier_part, is_unicode_identifier_start,
is_upper_case, is_valid_code_point, is_whitespace
END COMMENT
test:(
UNICHAR aircraft := U16r 2708;
printf(($"aircraft: "$, $"16r"16rdddd$, UNICODE(aircraft), $g$, " => ", REPR UNICODE(aircraft), $l$));
UNICODE chinese forty two = U16r 56db + U16r 5341 + U16r 4e8c;
printf(($"chinese forty two: "$, $g$, REPR chinese forty two, ", length string = ", UPB chinese forty two, $l$));
UNICODE poker = U "A123456789♥♦♣♠JQK";
printf(($"poker: "$, $g$, REPR poker, ", length string = ", UPB poker, $l$));
UNICODE selectric := U"×÷≤≥≠¬∨∧⏨→↓↑□⌊⌈⎩⎧○⊥¢";
printf(($"selectric: "$, $g$, REPR selectric, $l$));
printf(($"selectric*4: "$, $g$, REPR(selectric*4), $l$));
print((
"1 < 2 is ", U"1" < U"2", ", ",
"111 < 11 is ",U"111" < U"11", ", ",
"111 < 12 is ",U"111" < U"12", ", ",
"♥ < ♦ is ", U"♥" < U"♦", ", ",
"♥Q < ♥K is ",U"♥Q" < U"♥K", " & ",
"♥J < ♥K is ",U"♥J" < U"♥K", new line
))
) |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #Arturo | Arturo | unprimeable?: function [n][
if prime? n -> return false
nd: to :string n
loop.with:'i nd 'prevDigit [
loop `0`..`9` 'newDigit [
if newDigit <> prevDigit [
nd\[i]: newDigit
if prime? to :integer nd -> return false
]
]
nd\[i]: prevDigit
]
return true
]
cnt: 0
x: 1
unprimeables: []
while [cnt < 600][
if unprimeable? x [
unprimeables: unprimeables ++ x
cnt: cnt + 1
]
x: x + 1
]
print "First 35 unprimeable numbers:"
print first.n: 35 unprimeables
print ""
print ["600th unprimeable number:" last unprimeables] |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #C.23 | C# | class Program
{
static void Main()
{
var Δ = 1;
Δ++;
System.Console.WriteLine(Δ);
}
} |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Clojure | Clojure | (let [Δ 1]
(inc Δ)) |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Common_Lisp | Common Lisp | (let ((Δ 1))
(incf Δ)) |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #Aime | Aime | integer
biased(integer bias)
{
1 ^ min(drand(bias - 1), 1);
}
integer
unbiased(integer bias)
{
integer a;
while ((a = biased(bias)) == biased(bias)) {
}
a;
}
integer
main(void)
{
integer b, n, cb, cu, i;
n = 10000;
b = 3;
while (b <= 6) {
i = cb = cu = 0;
while ((i += 1) <= n) {
cb += biased(b);
cu += unbiased(b);
}
o_form("bias ~: /d2p2/%% vs /d2p2/%%\n", b, 100r * cb / n,
100r * cu / n);
b += 1;
}
0;
} |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #AutoHotkey | AutoHotkey | Biased(){
Random, q, 0, 4
return q=4
}
Unbiased(){
Loop
If ((a := Biased()) != biased())
return a
}
Loop 1000
t .= biased(), t2 .= unbiased()
StringReplace, junk, t2, 1, , UseErrorLevel
MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000
StringReplace, junk, t, 1, , UseErrorLevel
MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000 |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #Delphi | Delphi |
program Untouchable_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function SumDivisors(n: Integer): Integer;
begin
Result := 1;
var k := 2;
if not odd(n) then
k := 1;
var i := 1 + k;
while i * i <= n do
begin
if (n mod i) = 0 then
begin
inc(Result, i);
var j := n div i;
if j <> i then
inc(Result, j);
end;
inc(i, k);
end;
end;
function Sieve(n: Integer): TArray<Boolean>;
begin
inc(n);
SetLength(result, n + 1);
for var i := 6 to n do
begin
var sd := SumDivisors(i);
if sd <= n then
result[sd] := True;
end;
end;
function PrimeSieve(limit: Integer): TArray<Boolean>;
begin
inc(limit);
SetLength(result, limit);
Result[0] := True;
Result[1] := True;
var p := 3;
repeat
var p2 := p * p;
if p2 >= limit then
Break;
var i := p2;
while i < limit do
begin
Result[i] := True;
inc(i, 2 * p);
end;
repeat
inc(p, 2);
until not Result[p];
until (False);
end;
function Commatize(n: Double): string;
var
fmt: TFormatSettings;
begin
fmt := TFormatSettings.Create('en-US');
Result := n.ToString(ffNumber, 64, 0, fmt);
end;
begin
var limit := 1000000;
var c := primeSieve(limit);
var s := sieve(63 * limit);
var untouchable: TArray<Integer> := [2, 5];
var n := 6;
while n <= limit do
begin
if not s[n] and c[n - 1] and c[n - 3] then
begin
SetLength(untouchable, Length(untouchable) + 1);
untouchable[High(untouchable)] := n;
end;
inc(n, 2);
end;
writeln('List of untouchable numbers <= 2,000:');
var count := 0;
var i := 0;
while untouchable[i] <= 2000 do
begin
write(commatize(untouchable[i]): 6);
if ((i + 1) mod 10) = 0 then
writeln;
inc(i);
end;
writeln(#10#10, commatize(count): 7, ' untouchable numbers were found <= 2,000');
var p := 10;
count := 0;
for n in untouchable do
begin
inc(count);
if n > p then
begin
var cc := commatize(count - 1);
var cp := commatize(p);
writeln(cc, ' untouchable numbers were found <= ', cp);
p := p * 10;
if p = limit then
Break;
end;
end;
var cu := commatize(Length(untouchable));
var cl := commatize(limit);
writeln(cu:7, ' untouchable numbers were found <= ', cl);
readln;
end. |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #D | D | void main() {
import std.stdio, std.file, std.path, std.array, std.algorithm;
foreach (const string path; dirEntries(getcwd, SpanMode.shallow).array.sort)
path.baseName.writeln;
} |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Delphi | Delphi |
program LsCommand;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IoUtils;
procedure Ls(folder: string = '.');
var
offset: Integer;
fileName: string;
// simulate unix results in windows
function ToUnix(path: string): string;
begin
Result := path.Replace('/', PathDelim, [rfReplaceAll])
end;
begin
folder := IncludeTrailingPathDelimiter(ToUnix(folder));
offset := length(folder);
for fileName in TDirectory.GetFileSystemEntries(folder, '*') do
writeln(^I, ToUnix(fileName).Substring(offset));
end;
begin
writeln('cd foo'#10'ls');
ls('foo');
writeln(#10'cd bar'#10'ls');
ls('foo/bar');
{$IFNDEF LINUX} readln; {$ENDIF}
end. |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #PureBasic | PureBasic | Structure vector
x.f
y.f
z.f
EndStructure
;convert vector to a string for display
Procedure.s toString(*v.vector)
ProcedureReturn "[" + StrF(*v\x, 2) + ", " + StrF(*v\y, 2) + ", " + StrF(*v\z, 2) + "]"
EndProcedure
Procedure.f dotProduct(*a.vector, *b.vector)
ProcedureReturn *a\x * *b\x + *a\y * *b\y + *a\z * *b\z
EndProcedure
Procedure crossProduct(*a.vector, *b.vector, *r.vector)
*r\x = *a\y * *b\z - *a\z * *b\y
*r\y = *a\z * *b\x - *a\x * *b\z
*r\z = *a\x * *b\y - *a\y * *b\x
EndProcedure
Procedure.f scalarTriple(*a.vector, *b.vector, *c.vector)
Protected r.vector
crossProduct(*b, *c, r)
ProcedureReturn dotProduct(*a, r)
EndProcedure
Procedure vectorTriple(*a.vector, *b.vector, *c.vector, *r.vector)
Protected r.vector
crossProduct(*b, *c, r)
crossProduct(*a, r, *r)
EndProcedure
If OpenConsole()
Define.vector a, b, c, r
a\x = 3: a\y = 4: a\z = 5
b\x = 4: b\y = 3: b\z = 5
c\x = -5: c\y = -12: c\z = -13
PrintN("a = " + toString(a) + ", b = " + toString(b) + ", c = " + toString(c))
PrintN("a . b = " + StrF(dotProduct(a, b), 2))
crossProduct(a, b, r)
PrintN("a x b = " + toString(r))
PrintN("a . b x c = " + StrF(scalarTriple(a, b, c), 2))
vectorTriple(a, b, c, r)
PrintN("a x b x c = " + toString(r))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Smalltalk | Smalltalk | 'Enter a number: ' display.
a := stdin nextLine asInteger.
'Enter a string: ' display.
b := stdin nextLine. |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #smart_BASIC | smart BASIC | INPUT "Enter a string.":a$
INPUT "Enter the value 75000.":n |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #J | J |
foo=: 3
nc;:'foo bar'
0 _1 |
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Java | Java | String string = null; // the variable string is undefined
System.out.println(string); //prints "null" to std out
System.out.println(string.length()); // dereferencing null throws java.lang.NullPointerException |
|
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
# UNICHAR/UNICODE must be printed using REPR to convert to UTF8 #
MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 #
MODE UNICODE = FLEX[0]UNICHAR;
OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out);
OP INITUNICHAR = (CHAR char)UNICHAR: (UNICHAR out; bits OF out := BIN ABS char; out);
OP INITBITS = (UNICHAR unichar)BITS: #BIN# bits OF unichar;
PROC raise value error = ([]UNION(FORMAT,BITS,STRING)argv )VOID: (
putf(stand error, argv); stop
);
MODE YIELDCHAR = PROC(CHAR)VOID; MODE GENCHAR = PROC(YIELDCHAR)VOID;
MODE YIELDUNICHAR = PROC(UNICHAR)VOID; MODE GENUNICHAR = PROC(YIELDUNICHAR)VOID;
PRIO DOCONV = 1;
# Convert a stream of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (GENUNICHAR gen unichar, YIELDCHAR yield)VOID:(
BITS non ascii = NOT 2r1111111;
# FOR UNICHAR unichar IN # gen unichar( # ) DO ( #
## (UNICHAR unichar)VOID: (
BITS bits := INITBITS unichar;
IF (bits AND non ascii) = 2r0 THEN # ascii #
yield(REPR ABS bits)
ELSE
FLEX[6]CHAR buf := "?"*6; # initialise work around #
INT bytes := 0;
BITS byte lead bits = 2r10000000;
FOR ofs FROM UPB buf BY -1 WHILE
bytes +:= 1;
buf[ofs]:= REPR ABS (byte lead bits OR bits AND 2r111111);
bits := bits SHR 6;
# WHILE # bits NE 2r0 DO
SKIP
OD;
BITS first byte lead bits = BIN (ABS(2r1 SHL bytes)-2) SHL (UPB buf - bytes + 1);
buf := buf[UPB buf-bytes+1:];
buf[1] := REPR ABS(BIN ABS buf[1] OR first byte lead bits);
FOR i TO UPB buf DO yield(buf[i]) OD
FI
# OD # ))
);
# Convert a STRING into a stream of UNICHAR #
OP DOCONV = (STRING string, YIELDUNICHAR yield)VOID: (
PROC gen char = (YIELDCHAR yield)VOID:
FOR i FROM LWB string TO UPB string DO yield(string[i]) OD;
gen char DOCONV yield
);
CO Prosser/Thompson UTF8 encoding scheme
Bits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6
7 U+007F 0xxxxxxx
11 U+07FF 110xxxxx 10xxxxxx
16 U+FFFF 1110xxxx 10xxxxxx 10xxxxxx
21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
26 U+3FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
31 U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
END CO
# Quickly calculate the length of the UTF8 encoded string #
PROC upb utf8 = (STRING utf8 string)INT:(
INT bytes to go := 0;
INT upb := 0;
FOR i FROM LWB utf8 string TO UPB utf8 string DO
CHAR byte := utf8 string[i];
IF bytes to go = 0 THEN # start new utf char #
bytes to go :=
IF ABS byte <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF ABS byte <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF ABS byte <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF ABS byte <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF ABS byte <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF ABS byte <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN ABS byte)); ~ FI
FI;
bytes to go -:= 1; # skip over trailing bytes #
IF bytes to go = 0 THEN upb +:= 1 FI
OD;
upb
);
# Convert a stream of CHAR into a stream of UNICHAR #
OP DOCONV = (GENCHAR gen char, YIELDUNICHAR yield)VOID: (
INT bytes to go := 0;
INT lshift;
BITS mask, out;
# FOR CHAR byte IN # gen char( # ) DO ( #
## (CHAR byte)VOID: (
INT bits := ABS byte;
IF bytes to go = 0 THEN # start new unichar #
bytes to go :=
IF bits <= ABS 2r01111111 THEN 1 # 7 bits #
ELIF bits <= ABS 2r11011111 THEN 2 # 11 bits #
ELIF bits <= ABS 2r11101111 THEN 3 # 16 bits #
ELIF bits <= ABS 2r11110111 THEN 4 # 21 bits #
ELIF bits <= ABS 2r11111011 THEN 5 # 26 bits #
ELIF bits <= ABS 2r11111101 THEN 6 # 31 bits #
ELSE raise value error(("Invalid UTF-8 bytes", BIN bits)); ~ FI;
IF bytes to go = 1 THEN
lshift := 7; mask := 2r1111111
ELSE
lshift := 7 - bytes to go; mask := BIN(ABS(2r1 SHL lshift)-1)
FI;
out := mask AND BIN bits;
lshift := 6; mask := 2r111111 # subsequently pic 6 bits at a time #
ELSE
out := (out SHL lshift) OR ( mask AND BIN bits)
FI;
bytes to go -:= 1;
IF bytes to go = 0 THEN yield(INITUNICHAR out) FI
# OD # ))
);
# Convert a string of UNICHAR into a stream of UTFCHAR #
OP DOCONV = (UNICODE unicode, YIELDCHAR yield)VOID:(
PROC gen unichar = (YIELDUNICHAR yield)VOID:
FOR i FROM LWB unicode TO UPB unicode DO yield(unicode[i]) OD;
gen unichar DOCONV yield
);
# Some convenience/shorthand U operators #
# Convert a BITS into a UNICODE char #
OP U = (BITS bits)UNICHAR:
INITUNICHAR bits;
# Convert a []BITS into a UNICODE char #
OP U = ([]BITS array bits)[]UNICHAR:(
[LWB array bits:UPB array bits]UNICHAR out;
FOR i FROM LWB array bits TO UPB array bits DO bits OF out[i]:=array bits[i] OD;
out
);
# Convert a CHAR into a UNICODE char #
OP U = (CHAR char)UNICHAR:
INITUNICHAR char;
# Convert a STRING into a UNICODE string #
OP U = (STRING utf8 string)UNICODE: (
FLEX[upb utf8(utf8 string)]UNICHAR out;
INT i := 0;
# FOR UNICHAR char IN # utf8 string DOCONV (
## (UNICHAR char)VOID:
out[i+:=1] := char
# OD #);
out
);
# Convert a UNICODE string into a UTF8 STRING #
OP REPR = (UNICODE string)STRING: (
STRING out;
# FOR CHAR char IN # string DOCONV (
## (CHAR char)VOID: (
out +:= char
# OD #));
out
);
# define the most useful OPerators on UNICODE CHARacter arrays #
# Note: LWB, UPB and slicing works as per normal #
OP + = (UNICODE a,b)UNICODE: (
[UPB a + UPB b]UNICHAR out;
out[:UPB a]:= a; out[UPB a+1:]:= b;
out
);
OP + = (UNICODE a, UNICHAR b)UNICODE: a+UNICODE(b);
OP + = (UNICHAR a, UNICODE b)UNICODE: UNICODE(a)+b;
OP + = (UNICHAR a,b)UNICODE: UNICODE(a)+b;
# Suffix a character to the end of a UNICODE string #
OP +:= = (REF UNICODE a, UNICODE b)VOID: a := a + b;
OP +:= = (REF UNICODE a, UNICHAR b)VOID: a := a + b;
# Prefix a character to the beginning of a UNICODE string #
OP +=: = (UNICODE b, REF UNICODE a)VOID: a := b + a;
OP +=: = (UNICHAR b, REF UNICODE a)VOID: a := b + a;
OP * = (UNICODE a, INT n)UNICODE: (
UNICODE out := a;
FOR i FROM 2 TO n DO out +:= a OD;
out
);
OP * = (INT n, UNICODE a)UNICODE: a * n;
OP * = (UNICHAR a, INT n)UNICODE: UNICODE(a)*n;
OP * = (INT n, UNICHAR a)UNICODE: n*UNICODE(a);
OP *:= = (REF UNICODE a, INT b)VOID: a := a * b;
# Wirthy Operators #
OP LT = (UNICHAR a,b)BOOL: ABS bits OF a LT ABS bits OF b,
LE = (UNICHAR a,b)BOOL: ABS bits OF a LE ABS bits OF b,
EQ = (UNICHAR a,b)BOOL: ABS bits OF a EQ ABS bits OF b,
NE = (UNICHAR a,b)BOOL: ABS bits OF a NE ABS bits OF b,
GE = (UNICHAR a,b)BOOL: ABS bits OF a GE ABS bits OF b,
GT = (UNICHAR a,b)BOOL: ABS bits OF a GT ABS bits OF b;
# ASCII OPerators #
OP < = (UNICHAR a,b)BOOL: a LT b,
<= = (UNICHAR a,b)BOOL: a LE b,
= = (UNICHAR a,b)BOOL: a EQ b,
/= = (UNICHAR a,b)BOOL: a NE b,
>= = (UNICHAR a,b)BOOL: a GE b,
> = (UNICHAR a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICHAR a,b)BOOL: a LE b,
≠ = (UNICHAR a,b)BOOL: a NE b,
≥ = (UNICHAR a,b)BOOL: a GE b;
#
# Compare two UNICODE strings for equality #
PROC unicode cmp = (UNICODE str a,str b)INT: (
IF LWB str a > LWB str b THEN exit lt ELIF LWB str a < LWB str b THEN exit gt FI;
INT min upb = UPB(UPB str a < UPB str b | str a | str b );
FOR i FROM LWB str a TO min upb DO
UNICHAR a := str a[i], UNICHAR b := str b[i];
IF a < b THEN exit lt ELIF a > b THEN exit gt FI
OD;
IF UPB str a > UPB str b THEN exit gt ELIF UPB str a < UPB str b THEN exit lt FI;
exit eq: 0 EXIT
exit lt: -1 EXIT
exit gt: 1
);
OP LT = (UNICODE a,b)BOOL: unicode cmp(a,b)< 0,
LE = (UNICODE a,b)BOOL: unicode cmp(a,b)<=0,
EQ = (UNICODE a,b)BOOL: unicode cmp(a,b) =0,
NE = (UNICODE a,b)BOOL: unicode cmp(a,b)/=0,
GE = (UNICODE a,b)BOOL: unicode cmp(a,b)>=0,
GT = (UNICODE a,b)BOOL: unicode cmp(a,b)> 0;
# ASCII OPerators #
OP < = (UNICODE a,b)BOOL: a LT b,
<= = (UNICODE a,b)BOOL: a LE b,
= = (UNICODE a,b)BOOL: a EQ b,
/= = (UNICODE a,b)BOOL: a NE b,
>= = (UNICODE a,b)BOOL: a GE b,
> = (UNICODE a,b)BOOL: a GT b;
# Non ASCII OPerators
OP ≤ = (UNICODE a,b)BOOL: a LE b,
≠ = (UNICODE a,b)BOOL: a NE b,
≥ = (UNICODE a,b)BOOL: a GE b;
#
COMMENT - Todo: for all UNICODE and UNICHAR
Add NonASCII OPerators: ×, ×:=,
Add ASCII Operators: &, &:=, &=:
Add Wirthy OPerators: PLUSTO, PLUSAB, TIMESAB for UNICODE/UNICHAR,
Add UNICODE against UNICHAR comparison OPerators,
Add char_in_string and string_in_string PROCedures,
Add standard Unicode functions:
to_upper_case, to_lower_case, unicode_block, char_count,
get_directionality, get_numeric_value, get_type, is_defined,
is_digit, is_identifier_ignorable, is_iso_control,
is_letter, is_letter_or_digit, is_lower_case, is_mirrored,
is_space_char, is_supplementary_code_point, is_title_case,
is_unicode_identifier_part, is_unicode_identifier_start,
is_upper_case, is_valid_code_point, is_whitespace
END COMMENT
test:(
UNICHAR aircraft := U16r 2708;
printf(($"aircraft: "$, $"16r"16rdddd$, UNICODE(aircraft), $g$, " => ", REPR UNICODE(aircraft), $l$));
UNICODE chinese forty two = U16r 56db + U16r 5341 + U16r 4e8c;
printf(($"chinese forty two: "$, $g$, REPR chinese forty two, ", length string = ", UPB chinese forty two, $l$));
UNICODE poker = U "A123456789♥♦♣♠JQK";
printf(($"poker: "$, $g$, REPR poker, ", length string = ", UPB poker, $l$));
UNICODE selectric := U"×÷≤≥≠¬∨∧⏨→↓↑□⌊⌈⎩⎧○⊥¢";
printf(($"selectric: "$, $g$, REPR selectric, $l$));
printf(($"selectric*4: "$, $g$, REPR(selectric*4), $l$));
print((
"1 < 2 is ", U"1" < U"2", ", ",
"111 < 11 is ",U"111" < U"11", ", ",
"111 < 12 is ",U"111" < U"12", ", ",
"♥ < ♦ is ", U"♥" < U"♦", ", ",
"♥Q < ♥K is ",U"♥Q" < U"♥K", " & ",
"♥J < ♥K is ",U"♥J" < U"♥K", new line
))
) |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #ALGOL_68 | ALGOL 68 | BEGIN # find members of the sequence a(n) = smallest k such that 2^(2^n) - k is prime #
PR precision 650 PR # set number of digits for LONG LOMG INT #
# 2^(2^10) has 308 digits but we need more for #
# Miller Rabin primality testing #
PR read "primes.incl.a68" PR # include the prime related utilities #
FOR n TO 10 DO
LONG LONG INT two up 2 up n = LONG LONG INT( 2 ) ^ ( 2 ^ n );
FOR i BY 2
WHILE IF is probably prime( two up 2 up n - i ) THEN
# found a sequence member #
print( ( " ", whole( i, 0 ) ) );
FALSE # stop looking #
ELSE
TRUE # haven't found a sequence member yet #
FI
DO SKIP OD
OD
END |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #C | C | #include <assert.h>
#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct bit_array_tag {
uint32_t size;
uint32_t* array;
} bit_array;
bool bit_array_create(bit_array* b, uint32_t size) {
uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
if (array == NULL)
return false;
b->size = size;
b->array = array;
return true;
}
void bit_array_destroy(bit_array* b) {
free(b->array);
b->array = NULL;
}
void bit_array_set(bit_array* b, uint32_t index, bool value) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
if (value)
*p |= bit;
else
*p &= ~bit;
}
bool bit_array_get(const bit_array* b, uint32_t index) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
return (*p & bit) != 0;
}
typedef struct sieve_tag {
uint32_t limit;
bit_array not_prime;
} sieve;
bool sieve_create(sieve* s, uint32_t limit) {
if (!bit_array_create(&s->not_prime, limit/2))
return false;
for (uint32_t p = 3; p * p <= limit; p += 2) {
if (bit_array_get(&s->not_prime, p/2 - 1) == false) {
uint32_t inc = 2 * p;
for (uint32_t q = p * p; q <= limit; q += inc)
bit_array_set(&s->not_prime, q/2 - 1, true);
}
}
s->limit = limit;
return true;
}
void sieve_destroy(sieve* s) {
bit_array_destroy(&s->not_prime);
}
bool is_prime(const sieve* s, uint32_t n) {
assert(n <= s->limit);
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
return bit_array_get(&s->not_prime, n/2 - 1) == false;
}
// return number of decimal digits
uint32_t count_digits(uint32_t n) {
uint32_t digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
// return the number with one digit replaced
uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {
uint32_t p = 1;
uint32_t changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
// returns true if n unprimeable
bool unprimeable(const sieve* s, uint32_t n) {
if (is_prime(s, n))
return false;
uint32_t d = count_digits(n);
for (uint32_t i = 0; i < d; ++i) {
for (uint32_t j = 0; j <= 9; ++j) {
uint32_t m = change_digit(n, i, j);
if (m != n && is_prime(s, m))
return false;
}
}
return true;
}
int main() {
const uint32_t limit = 10000000;
setlocale(LC_ALL, "");
sieve s = { 0 };
if (!sieve_create(&s, limit)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
printf("First 35 unprimeable numbers:\n");
uint32_t n = 100;
uint32_t lowest[10] = { 0 };
for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(&s, n)) {
if (count < 35) {
if (count != 0)
printf(", ");
printf("%'u", n);
}
++count;
if (count == 600)
printf("\n600th unprimeable number: %'u\n", n);
uint32_t last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
sieve_destroy(&s);
for (uint32_t i = 0; i < 10; ++i)
printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]);
return 0;
} |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Crystal | Crystal | Δ = 1
Δ += 1
puts Δ |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #D | D | import std.stdio;
void main() {
auto Δ = 1;
Δ++;
writeln(Δ);
} |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Delphi | Delphi | (* Compiled with Delphi XE *)
program UnicodeVariableName;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
Δ: Integer;
begin
Δ:= 1;
Inc(Δ);
Writeln(Δ);
Readln;
end. |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #BASIC | BASIC |
function randN (n)
if int(rand * n) + 1 <> 1 then return 0 else return 1
end function
function unbiased (n)
do
a = randN (n)
b = randN (n)
until a <> b
return a
end function
numveces = 100000
print "Resultados de números aleatorios sesgados e imparciales" + chr(10)
for n = 3 to 6
dim b_numveces(n) fill 0
dim u_numveces(n) fill 0
for m = 1 to numveces
x = randN (n)
b_numveces[x] += 1
x = unbiased (n)
u_numveces[x] += 1
next m
print "N = "; n
print " Biased =>", "#0="; (b_numveces[0]); " #1="; (b_numveces[1]); " ratio = "; (b_numveces[1]/numveces*100); "%"
print "Unbiased =>", "#0="; (u_numveces[0]); " #1="; (u_numveces[1]); " ratio = "; (u_numveces[1]/numveces*100); "%"
next n
end
|
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #BBC_BASIC | BBC BASIC | FOR N% = 3 TO 6
biased% = 0
unbiased% = 0
FOR I% = 1 TO 10000
IF FNrandN(N%) biased% += 1
IF FNunbiased(N%) unbiased% += 1
NEXT
PRINT "N = ";N% " : biased = "; biased%/100 "%, unbiased = "; unbiased%/100 "%"
NEXT
END
DEF FNunbiased(N%)
LOCAL A%,B%
REPEAT
A% = FNrandN(N%)
B% = FNrandN(N%)
UNTIL A%<>B%
= A%
DEF FNrandN(N%) = -(RND(N%) = 1) |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #F.23 | F# |
// Applied dendrology. Nigel Galloway: February 15., 2021
let uT a=let N,G=Array.create(a+1) true, [|yield! primes64()|>Seq.takeWhile((>)(int64 a))|]
let fN n i e=let mutable p=e-1 in (fun()->p<-p+1; if p<G.Length && (n+i)*(1L+G.[p])-n*G.[p]<=(int64 a) then Some(n,i,p) else None)
let fG n i e=let g=n+i in let mutable n,l,p=n,1L,1L
(fun()->n<-n*G.[e]; p<-p*G.[e]; l<-l+p; let i=g*l-n in if i<=(int64 a) then Some(n,i,e) else None)
let rec fL n g=match n() with Some(f,i,e)->N.[(int i)]<-false; fL n ((fN f i (e+1))::g)
|_->match g with n::t->match n() with Some (n,i,e)->fL (fG n i e) g |_->fL n t
|_->N.[0]<-false; N
fL (fG 1L 0L 0) [fN 1L 0L 1]
|
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #EchoLisp | EchoLisp |
;; ls of stores (kind of folders)
(for-each writeln (list-sort < (local-stores))) →
AGES
NEMESIS
info
objects.dat
reader
system
user
words
;; ls of "NEMESIS" store
(for-each writeln (local-keys "NEMESIS")) →
Alan
Glory
Jonah
|
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Elixir | Elixir | iex(1)> ls = fn dir -> File.ls!(dir) |> Enum.each(&IO.puts &1) end
#Function<6.54118792/1 in :erl_eval.expr/5>
iex(2)> ls.("foo")
bar
:ok
iex(3)> ls.("foo/bar")
1
2
a
b
:ok |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Python | Python | def crossp(a, b):
'''Cross product of two 3D vectors'''
assert len(a) == len(b) == 3, 'For 3D vectors only'
a1, a2, a3 = a
b1, b2, b3 = b
return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)
def dotp(a,b):
'''Dot product of two eqi-dimensioned vectors'''
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
def scalartriplep(a, b, c):
'''Scalar triple product of three vectors: "a . (b x c)"'''
return dotp(a, crossp(b, c))
def vectortriplep(a, b, c):
'''Vector triple product of three vectors: "a x (b x c)"'''
return crossp(a, crossp(b, c))
if __name__ == '__main__':
a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)
print("a = %r; b = %r; c = %r" % (a, b, c))
print("a . b = %r" % dotp(a,b))
print("a x b = %r" % (crossp(a,b),))
print("a . (b x c) = %r" % scalartriplep(a, b, c))
print("a x (b x c) = %r" % (vectortriplep(a, b, c),)) |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #SNOBOL4 | SNOBOL4 | output = "Enter a string:"
str = trim(input)
output = "Enter an integer:"
int = trim(input)
output = "String: " str " Integer: " int
end |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #SPL | SPL | text = #.input("Input a string")
number = #.val(#.input("Input a number")) |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #JavaScript | JavaScript | var a;
typeof(a) === "undefined";
typeof(b) === "undefined";
var obj = {}; // Empty object.
typeof(obj.c) === "undefined";
obj.c = 42;
obj.c === 42;
delete obj.c;
typeof(obj.c) === "undefined"; |
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #jq | jq | {}["key"] #=> null |
|
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #Arturo | Arturo | text: "你好"
print ["text:" text]
print ["length:" size text]
print ["contains string '好'?:" contains? text "好"]
print ["contains character '平'?:" contains? text `平`]
print ["text as ascii:" as.ascii text] |
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #AutoHotkey | AutoHotkey | VDU 23,22,640;512;8,16,16,128+8 : REM Select UTF-8 mode
*FONT Times New Roman, 20
PRINT "Arabic:"
arabic1$ = "هنا مثال يمكنك من الكتابة من اليمين"
arabic2$ = "الى اليسار باللغة العربية"
VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing
PRINT FNarabic(arabic1$) ' FNarabic(arabic2$)
VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing
PRINT '"Hebrew:"
hebrew$ = "זוהי הדגמה של כתיבת טקסט בעברית מימין לשמאל"
VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing
PRINT hebrew$
VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing
END
REM!Eject
DEF FNarabic(A$)
LOCAL A%, B%, L%, O%, P%, U%, B$
A$ += CHR$0
FOR A% = !^A$ TO !^A$+LENA$-1
IF ?A%<&80 OR ?A%>=&C0 THEN
L% = O% : O% = P% : P% = U%
U% = ((?A% AND &3F) << 6) + (A%?1 AND &3F)
IF ?A%<&80 U% = 0
CASE TRUE OF
WHEN U%=&60C OR U%=&61F: U% = 0
WHEN U%<&622:
WHEN U%<&626: U% = &01+2*(U%-&622)
WHEN U%<&628: U% = &09+4*(U%-&626)
WHEN U%<&62A: U% = &0F+4*(U%-&628)
WHEN U%<&62F: U% = &15+4*(U%-&62A)
WHEN U%<&633: U% = &29+2*(U%-&62F)
WHEN U%<&63B: U% = &31+4*(U%-&633)
WHEN U%<&641:
WHEN U%<&648: U% = &51+4*(U%-&641)
WHEN U%<&64B: U% = &6D+2*(U%-&648)
ENDCASE
IF P% IF P%<&80 THEN
B% = P%
IF O%=&5D IF P%<&5 B% += &74
IF O%=&5D IF P%=&7 B% += &72
IF O%=&5D IF P%=&D B% += &6E
IF B%>P% B$=LEFT$(B$,LENB$-3) : O% = L%
IF U% IF P%>7 IF P%<>&D IF P%<>&13 IF P%<>&29 IF P%<>&2B IF P%<>&2D IF P%<>&2F IF P%<>&6D IF P%<>&6F B% += 2
IF O% IF O%>7 IF O%<>&D IF O%<>&13 IF O%<>&29 IF O%<>&2B IF O%<>&2D IF O%<>&2F IF O%<>&6D IF O%<>&6F B% += 1
B$ = LEFT$(LEFT$(B$))+CHR$&EF+CHR$(&BA+(B%>>6))+CHR$(&80+(B%AND&3F))
ENDIF
ENDIF
B$ += CHR$?A%
NEXT
= LEFT$(B$) |
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #AWK | AWK | VDU 23,22,640;512;8,16,16,128+8 : REM Select UTF-8 mode
*FONT Times New Roman, 20
PRINT "Arabic:"
arabic1$ = "هنا مثال يمكنك من الكتابة من اليمين"
arabic2$ = "الى اليسار باللغة العربية"
VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing
PRINT FNarabic(arabic1$) ' FNarabic(arabic2$)
VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing
PRINT '"Hebrew:"
hebrew$ = "זוהי הדגמה של כתיבת טקסט בעברית מימין לשמאל"
VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing
PRINT hebrew$
VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing
END
REM!Eject
DEF FNarabic(A$)
LOCAL A%, B%, L%, O%, P%, U%, B$
A$ += CHR$0
FOR A% = !^A$ TO !^A$+LENA$-1
IF ?A%<&80 OR ?A%>=&C0 THEN
L% = O% : O% = P% : P% = U%
U% = ((?A% AND &3F) << 6) + (A%?1 AND &3F)
IF ?A%<&80 U% = 0
CASE TRUE OF
WHEN U%=&60C OR U%=&61F: U% = 0
WHEN U%<&622:
WHEN U%<&626: U% = &01+2*(U%-&622)
WHEN U%<&628: U% = &09+4*(U%-&626)
WHEN U%<&62A: U% = &0F+4*(U%-&628)
WHEN U%<&62F: U% = &15+4*(U%-&62A)
WHEN U%<&633: U% = &29+2*(U%-&62F)
WHEN U%<&63B: U% = &31+4*(U%-&633)
WHEN U%<&641:
WHEN U%<&648: U% = &51+4*(U%-&641)
WHEN U%<&64B: U% = &6D+2*(U%-&648)
ENDCASE
IF P% IF P%<&80 THEN
B% = P%
IF O%=&5D IF P%<&5 B% += &74
IF O%=&5D IF P%=&7 B% += &72
IF O%=&5D IF P%=&D B% += &6E
IF B%>P% B$=LEFT$(B$,LENB$-3) : O% = L%
IF U% IF P%>7 IF P%<>&D IF P%<>&13 IF P%<>&29 IF P%<>&2B IF P%<>&2D IF P%<>&2F IF P%<>&6D IF P%<>&6F B% += 2
IF O% IF O%>7 IF O%<>&D IF O%<>&13 IF O%<>&29 IF O%<>&2B IF O%<>&2D IF O%<>&2F IF O%<>&6D IF O%<>&6F B% += 1
B$ = LEFT$(LEFT$(B$))+CHR$&EF+CHR$(&BA+(B%>>6))+CHR$(&80+(B%AND&3F))
ENDIF
ENDIF
B$ += CHR$?A%
NEXT
= LEFT$(B$) |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Arturo | Arturo | ultraUseful: function [n][
k: 1
p: (2^2^n) - k
while ø [
if prime? p -> return k
p: p-2
k: k+2
]
]
print [pad "n" 3 "|" pad.right "k" 4]
print repeat "-" 10
loop 1..10 'x ->
print [(pad to :string x 3) "|" (pad.right to :string ultraUseful x 4)] |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Factor | Factor | USING: io kernel lists lists.lazy math math.primes prettyprint ;
: useful ( -- list )
1 lfrom
[ 2^ 2^ 1 lfrom [ - prime? ] with lfilter car ] lmap-lazy ;
10 useful ltake [ pprint bl ] leach nl |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Go | Go | package main
import (
"fmt"
big "github.com/ncw/gmp"
)
var two = big.NewInt(2)
func a(n uint) int {
one := big.NewInt(1)
p := new(big.Int).Lsh(one, 1 << n)
p.Sub(p, one)
for k := 1; ; k += 2 {
if p.ProbablyPrime(15) {
return k
}
p.Sub(p, two)
}
}
func main() {
fmt.Println(" n k")
fmt.Println("----------")
for n := uint(1); n < 14; n++ {
fmt.Printf("%2d %d\n", n, a(n))
}
} |
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
// return number of decimal digits
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
// return the number with one digit replaced
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
// returns true if n unprimeable
bool unprimeable(const prime_sieve& sieve, integer n) {
if (sieve.is_prime(n))
return false;
int d = count_digits(n);
for (int i = 0; i < d; ++i) {
for (int j = 0; j <= 9; ++j) {
integer m = change_digit(n, i, j);
if (m != n && sieve.is_prime(m))
return false;
}
}
return true;
}
int main() {
const integer limit = 10000000;
prime_sieve sieve(limit);
// print numbers with commas
std::cout.imbue(std::locale(""));
std::cout << "First 35 unprimeable numbers:\n";
integer n = 100;
integer lowest[10] = { 0 };
for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(sieve, n)) {
if (count < 35) {
if (count != 0)
std::cout << ", ";
std::cout << n;
}
++count;
if (count == 600)
std::cout << "\n600th unprimeable number: " << n << '\n';
int last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
for (int i = 0; i < 10; ++i)
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
} |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #DWScript | DWScript | var Δ : Integer;
Δ := 1;
Inc(Δ);
PrintLn(Δ); |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | set :Δ 1
set :Δ ++ Δ
!. Δ |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #EchoLisp | EchoLisp |
(define ∆-🍒 1) → ∆-🍒
(set! ∆-🍒 (1+ ∆-🍒)) → 2
(printf "🔦 Look at ∆-🍒 : %d" ∆-🍒)
🔦 Look at ∆-🍒 : 2
|
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #C | C | #include <stdio.h>
#include <stdlib.h>
int biased(int bias)
{
/* balance out the bins, being pedantic */
int r, rand_max = RAND_MAX - (RAND_MAX % bias);
while ((r = rand()) > rand_max);
return r < rand_max / bias;
}
int unbiased(int bias)
{
int a;
while ((a = biased(bias)) == biased(bias));
return a;
}
int main()
{
int b, n = 10000, cb, cu, i;
for (b = 3; b <= 6; b++) {
for (i = cb = cu = 0; i < n; i++) {
cb += biased(b);
cu += unbiased(b);
}
printf("bias %d: %5.3f%% vs %5.3f%%\n", b,
100. * cb / n, 100. * cu / n);
}
return 0;
} |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #Go | Go | package main
import "fmt"
func sumDivisors(n int) int {
sum := 1
k := 2
if n%2 == 0 {
k = 1
}
for i := 1 + k; i*i <= n; i += k {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
}
return sum
}
func sieve(n int) []bool {
n++
s := make([]bool, n+1) // all false by default
for i := 6; i <= n; i++ {
sd := sumDivisors(i)
if sd <= n {
s[sd] = true
}
}
return s
}
func primeSieve(limit int) []bool {
limit++
// True denotes composite, false denotes prime.
c := make([]bool, limit) // all false by default
c[0] = true
c[1] = true
// no need to bother with even numbers over 2 for this task
p := 3 // Start from 3.
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := 1000000
c := primeSieve(limit)
s := sieve(63 * limit)
untouchable := []int{2, 5}
for n := 6; n <= limit; n += 2 {
if !s[n] && c[n-1] && c[n-3] {
untouchable = append(untouchable, n)
}
}
fmt.Println("List of untouchable numbers <= 2,000:")
count := 0
for i := 0; untouchable[i] <= 2000; i++ {
fmt.Printf("%6s", commatize(untouchable[i]))
if (i+1)%10 == 0 {
fmt.Println()
}
count++
}
fmt.Printf("\n\n%7s untouchable numbers were found <= 2,000\n", commatize(count))
p := 10
count = 0
for _, n := range untouchable {
count++
if n > p {
cc := commatize(count - 1)
cp := commatize(p)
fmt.Printf("%7s untouchable numbers were found <= %9s\n", cc, cp)
p = p * 10
if p == limit {
break
}
}
}
cu := commatize(len(untouchable))
cl := commatize(limit)
fmt.Printf("%7s untouchable numbers were found <= %s\n", cu, cl)
} |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Erlang | Erlang |
1> Ls = fun(Dir) ->
1> {ok, DirContents} = file:list_dir(Dir),
1> [io:format("~s~n", [X]) || X <- lists:sort(DirContents)]
1> end.
#Fun<erl_eval.6.36634728>
2> Ls("foo").
bar
[ok]
3> Ls("foo/bar").
1
2
a
b
[ok,ok,ok,ok]
|
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #F.23 | F# | let ls = DirectoryInfo(".").EnumerateFileSystemInfos() |> Seq.map (fun i -> i.Name) |> Seq.sort |> Seq.iter (printfn "%s") |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Quackery | Quackery | [ 0 unrot witheach
[ over i^ peek *
rot + swap ]
drop ] is dotproduct ( [ [ --> n )
[ join
dup 1 peek over 5 peek *
swap
dup 2 peek over 4 peek *
swap dip -
dup 2 peek over 3 peek *
swap
dup 0 peek over 5 peek *
swap dip -
dup 0 peek over 4 peek *
swap
dup 1 peek swap 3 peek *
- join join ] is crossproduct ( [ [ --> [ )
[ crossproduct dotproduct ] is scalartriple ( [ [ [ --> n )
[ crossproduct crossproduct ] is vectortriple ( [ [ [ --> [ )
[ ' [ 3 4 5 ] ] is a ( --> [ )
[ ' [ 4 3 5 ] ] is b ( --> [ )
[ ' [ -5 -12 -13 ] ] is c ( --> [ )
a b dotproduct echo cr
a b crossproduct echo cr
a b c scalartriple echo cr
a b c vectortriple echo cr |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Standard_ML | Standard ML | print "Enter a string: ";
let val str = valOf (TextIO.inputLine TextIO.stdIn) in (* note: this keeps the trailing newline *)
print "Enter an integer: ";
let val num = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn) in
print (str ^ Int.toString num ^ "\n")
end
end |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Swift | Swift | print("Enter a string: ", terminator: "")
if let str = readLine() {
print(str)
} |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Julia | Julia | julia> x + 1
ERROR: UndefVarError: x not defined
Stacktrace:
[1] top-level scope at none:0
|
|
http://rosettacode.org/wiki/Undefined_values | Undefined values | #Kotlin | Kotlin | // version 1.1.2
class SomeClass
class SomeOtherClass {
lateinit var sc: SomeClass
fun initialize() {
sc = SomeClass() // not initialized in place or in constructor
}
fun printSomething() {
println(sc) // 'sc' may not have been initialized at this point
}
fun someFunc(): String {
// for now calls a library function which throws an error and returns Nothing
TODO("someFunc not yet implemented")
}
}
fun main(args: Array<String>) {
val soc = SomeOtherClass()
try {
soc.printSomething()
}
catch (ex: Exception) {
println(ex)
}
try {
soc.someFunc()
}
catch (e: Error) {
println(e)
}
} |
|
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #BBC_BASIC | BBC BASIC | VDU 23,22,640;512;8,16,16,128+8 : REM Select UTF-8 mode
*FONT Times New Roman, 20
PRINT "Arabic:"
arabic1$ = "هنا مثال يمكنك من الكتابة من اليمين"
arabic2$ = "الى اليسار باللغة العربية"
VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing
PRINT FNarabic(arabic1$) ' FNarabic(arabic2$)
VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing
PRINT '"Hebrew:"
hebrew$ = "זוהי הדגמה של כתיבת טקסט בעברית מימין לשמאל"
VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing
PRINT hebrew$
VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing
END
REM!Eject
DEF FNarabic(A$)
LOCAL A%, B%, L%, O%, P%, U%, B$
A$ += CHR$0
FOR A% = !^A$ TO !^A$+LENA$-1
IF ?A%<&80 OR ?A%>=&C0 THEN
L% = O% : O% = P% : P% = U%
U% = ((?A% AND &3F) << 6) + (A%?1 AND &3F)
IF ?A%<&80 U% = 0
CASE TRUE OF
WHEN U%=&60C OR U%=&61F: U% = 0
WHEN U%<&622:
WHEN U%<&626: U% = &01+2*(U%-&622)
WHEN U%<&628: U% = &09+4*(U%-&626)
WHEN U%<&62A: U% = &0F+4*(U%-&628)
WHEN U%<&62F: U% = &15+4*(U%-&62A)
WHEN U%<&633: U% = &29+2*(U%-&62F)
WHEN U%<&63B: U% = &31+4*(U%-&633)
WHEN U%<&641:
WHEN U%<&648: U% = &51+4*(U%-&641)
WHEN U%<&64B: U% = &6D+2*(U%-&648)
ENDCASE
IF P% IF P%<&80 THEN
B% = P%
IF O%=&5D IF P%<&5 B% += &74
IF O%=&5D IF P%=&7 B% += &72
IF O%=&5D IF P%=&D B% += &6E
IF B%>P% B$=LEFT$(B$,LENB$-3) : O% = L%
IF U% IF P%>7 IF P%<>&D IF P%<>&13 IF P%<>&29 IF P%<>&2B IF P%<>&2D IF P%<>&2F IF P%<>&6D IF P%<>&6F B% += 2
IF O% IF O%>7 IF O%<>&D IF O%<>&13 IF O%<>&29 IF O%<>&2B IF O%<>&2D IF O%<>&2F IF O%<>&6D IF O%<>&6F B% += 1
B$ = LEFT$(LEFT$(B$))+CHR$&EF+CHR$(&BA+(B%>>6))+CHR$(&80+(B%AND&3F))
ENDIF
ENDIF
B$ += CHR$?A%
NEXT
= LEFT$(B$) |
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
Task
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
How easy is it to present Unicode strings in source code?
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
How well can the language communicate with the rest of the world?
Is it good at input/output with Unicode?
Is it convenient to manipulate Unicode strings in the language?
How broad/deep does the language support Unicode?
What encodings (e.g. UTF-8, UTF-16, etc) can be used?
Does it support normalization?
Note
This task is a bit unusual in that it encourages general discussion rather than clever coding.
See also
Unicode variable names
Terminal control/Display an extended character
| #Bracmat | Bracmat | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
/* wchar_t is the standard type for wide chars; what it is internally
* depends on the compiler.
*/
wchar_t poker[] = L"♥♦♣♠";
wchar_t four_two[] = L"\x56db\x5341\x4e8c";
int main() {
/* Set the locale to alert C's multibyte output routines */
if (!setlocale(LC_CTYPE, "")) {
fprintf(stderr, "Locale failure, check your env vars\n");
return 1;
}
#ifdef __STDC_ISO_10646__
/* C99 compilers should understand these */
printf("%lc\n", 0x2708); /* ✈ */
printf("%ls\n", poker); /* ♥♦♣♠ */
printf("%ls\n", four_two); /* 四十二 */
#else
/* oh well */
printf("airplane\n");
printf("club diamond club spade\n");
printf("for ty two\n");
#endif
return 0;
} |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Julia | Julia | using Primes
nearpow2pow2prime(n) = findfirst(k -> isprime(2^(big"2"^n) - k), 1:10000)
@time println([nearpow2pow2prime(n) for n in 1:12])
|
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[FindUltraUsefulPrimeK]
FindUltraUsefulPrimeK[n_] := Module[{num, tmp},
num = 2^(2^n);
Do[
If[PrimeQ[num - k],
tmp = k;
Break[];
]
,
{k, 1, \[Infinity], 2}
];
tmp
]
res = FindUltraUsefulPrimeK /@ Range[13];
TableForm[res, TableHeadings -> Automatic] |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use bigint;
use ntheory 'is_prime';
sub useful {
my @n = @_;
my @u;
for my $n (@n) {
my $p = 2**(2**$n);
LOOP: for (my $k = 1; $k < $p; $k += 2) {
is_prime($p-$k) and push @u, $k and last LOOP;
}
}
@u
}
say join ' ', useful 1..13; |
http://rosettacode.org/wiki/Ultra_useful_primes | Ultra useful primes | An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime.
k must always be an odd number since 2 to any power is always even.
Task
Find and show here, on this page, the first 10 elements of the sequence.
Stretch
Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
See also
OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| #Phix | Phix | with javascript_semantics
atom t0 = time()
include mpfr.e
mpz p = mpz_init()
function a(integer n)
mpz_ui_pow_ui(p,2,power(2,n))
mpz_sub_si(p,p,1)
integer k = 1
while not mpz_prime(p) do
k += 2
mpz_sub_si(p,p,2)
end while
return k
end function
for i=1 to 10 do
printf(1,"%d ",a(i))
end for
if machine_bits()=64 then
?elapsed(time()-t0)
for i=11 to 13 do
printf(1,"%d ",a(i))
end for
end if
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/Unprimeable_numbers | Unprimeable numbers | Definitions
As used here, all unprimeable numbers (positive integers) are always expressed in base ten.
───── Definition from OEIS ─────:
Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.
───── Definition from Wiktionary (referenced from Adam Spencer's book) ─────:
(arithmetic) that cannot be turned into a prime number by changing just one of its digits to any other
digit. (sic)
Unprimeable numbers are also spelled: unprimable.
All one─ and two─digit numbers can be turned into primes by changing a single decimal digit.
Examples
190 isn't unprimeable, because by changing the zero digit into a three yields 193, which is a prime.
The number 200 is unprimeable, since none of the numbers 201, 202, 203, ··· 209 are
prime, and all the other numbers obtained by changing a single digit to
produce 100, 300, 400, ··· 900, or 210, 220, 230, ··· 290 which are all even.
It is valid to change 189 into 089 by changing the 1 (one) into
a 0 (zero), which then the leading zero can be removed, and then treated as if
the "new" number is 89.
Task
show the first 35 unprimeable numbers (horizontally, on one line, preferably with a title)
show the 600th unprimeable number
(optional) show the lowest unprimeable number ending in a specific decimal digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(optional) use commas in the numbers where appropriate
Show all output here, on this page.
Also see
the OEIS entry: A118118 (unprimeable)
with some useful counts to compare unprimeable number
the Wiktionary entry (reference from below): (arithmetic definition) unprimeable
from the Adam Spencer book (page 200): Adam Spencer's World of Numbers (Xoum Publishing)
| #D | D | import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
immutable MAX = 10_000_000;
bool[] primes;
bool[] sieve(int limit) {
bool[] p = uninitializedArray!(bool[])(limit);
p[0..2] = false;
p[2..$] = true;
foreach (i; 2..limit) {
if (p[i]) {
for (int j = 2 * i; j < limit; j += i) {
p[j] = false;
}
}
}
return p;
}
string replace(CHAR)(CHAR[] str, int position, CHAR value) {
str[position] = value;
return str.idup;
}
bool unPrimeable(int n) {
if (primes[n]) {
return false;
}
auto test = n.to!string;
foreach (i; 0 .. test.length) {
for (char j = '0'; j <= '9'; j++) {
auto r = replace(test.dup, i, j);
if (primes[r.to!int]) {
return false;
}
}
}
return true;
}
void displayUnprimeableNumbers(int maxCount) {
int test = 1;
for (int count = 0; count < maxCount;) {
test++;
if (unPrimeable(test)) {
count++;
write(test, ' ');
}
}
writeln;
}
int nthUnprimeableNumber(int maxCount) {
int test = 1;
for (int count = 0; count < maxCount;) {
test++;
if (unPrimeable(test)) {
count++;
}
}
return test;
}
int[] genLowest() {
int[] lowest = uninitializedArray!(int[])(10);
lowest[] = 0;
int count = 0;
int test = 1;
while (count < 10) {
test++;
if (unPrimeable(test) && lowest[test % 10] == 0) {
lowest[test % 10] = test;
count++;
}
}
return lowest;
}
void main() {
primes = sieve(MAX);
writeln("First 35 unprimeable numbers:");
displayUnprimeableNumbers(35);
writeln;
int n = 600;
writefln("The %dth unprimeable number = %,d", n, nthUnprimeableNumber(n));
writeln;
writeln("Least unprimeable number that ends in:");
foreach (i,v; genLowest()) {
writefln(" %d is %,d", i, v);
}
} |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Elena | Elena | public program()
{
var Δ := 1;
Δ := Δ + 1;
console.writeLine:Δ
} |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #Emacs_Lisp | Emacs Lisp | (setq Δ 1)
(setq Δ (1+ Δ))
(message "Δ is %d" Δ) |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identifiers
| #F.23 | F# | let mutable Δ = 1
Δ <- Δ + 1
printfn "%d" Δ |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| #C.2B.2B | C++ | #include <iostream>
#include <random>
std::default_random_engine generator;
bool biased(int n) {
std::uniform_int_distribution<int> distribution(1, n);
return distribution(generator) == 1;
}
bool unbiased(int n) {
bool flip1, flip2;
/* Flip twice, and check if the values are the same.
* If so, flip again. Otherwise, return the value of the first flip. */
do {
flip1 = biased(n);
flip2 = biased(n);
} while (flip1 == flip2);
return flip1;
}
int main() {
for (size_t n = 3; n <= 6; n++) {
int biasedZero = 0;
int biasedOne = 0;
int unbiasedZero = 0;
int unbiasedOne = 0;
for (size_t i = 0; i < 100000; i++) {
if (biased(n)) {
biasedOne++;
} else {
biasedZero++;
}
if (unbiased(n)) {
unbiasedOne++;
} else {
unbiasedZero++;
}
}
std::cout << "(N = " << n << ")\n";
std::cout << "Biased:\n";
std::cout << " 0 = " << biasedZero << "; " << biasedZero / 1000.0 << "%\n";
std::cout << " 1 = " << biasedOne << "; " << biasedOne / 1000.0 << "%\n";
std::cout << "Unbiased:\n";
std::cout << " 0 = " << unbiasedZero << "; " << unbiasedZero / 1000.0 << "%\n";
std::cout << " 1 = " << unbiasedOne << "; " << unbiasedOne / 1000.0 << "%\n";
std::cout << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #J | J |
factor=: 3 : 0 NB. explicit
'primes powers'=. __&q: y
input_to_cartesian_product=. primes ^&.> i.&.> >: powers
cartesian_product=. , { input_to_cartesian_product
, */&> cartesian_product
)
factor=: [: , [: */&> [: { [: (^&.> i.&.>@>:)/ __&q: NB. tacit
proper_divisors=: [: }: factor
sum_of_proper_divisors=: +/@proper_divisors
candidates=: 5 , [: +: [: #\@i. >.@-: NB. within considered range, all but one candidate are even.
spds=:([:sum_of_proper_divisors"0(#\@i.-.i.&.:(p:inv))@*:)f. NB. remove primes which contribute 1
|
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
An untouchable are those numbers that are not in the image of the aliquot sum function. (From Wikipedia)
Untouchable numbers: impossible values for the sum of all aliquot parts function. (From OEIS: The On-line Encyclopedia of Integer Sequences®)
An untouchable number is a positive integer that is not the sum of the proper divisors of any number. (From MathWorld™)
Observations and conjectures
All untouchable numbers > 5 are composite numbers.
No untouchable number is perfect.
No untouchable number is sociable.
No untouchable number is a Mersenne prime.
No untouchable number is one more than a prime number, since if p is prime, then
the sum of the proper divisors of p2 is p + 1.
No untouchable number is three more than an odd prime number, since if p is an odd prime, then the
sum of the proper divisors of 2p is p + 3.
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a
slightly stronger version of the Goldbach's conjecture, since the sum of the
proper divisors of pq (with p, q being
distinct primes) is 1 + p + q.
There are infinitely many untouchable numbers, a fact that was proven
by Paul Erdős.
According to Chen & Zhao, their natural density is at least d > 0.06.
Task
show (in a grid format) all untouchable numbers ≤ 2,000.
show (for the above) the count of untouchable numbers.
show the count of untouchable numbers from unity up to (inclusive):
10
100
1,000
10,000
100,000
... or as high as is you think is practical.
all output is to be shown here, on this page.
See also
Wolfram MathWorld: untouchable number.
OEIS: A005114 untouchable numbers.
OEIS: a list of all untouchable numbers below 100,000 (inclusive).
Wikipedia: untouchable number.
Wikipedia: Goldbach's conjecture.
| #Julia | Julia | using Primes
function properfactorsum(n)
f = [one(n)]
for (p,e) in factor(n)
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
pop!(f)
return sum(f)
end
const maxtarget, sievelimit = 1_000_000, 512_000_000
const untouchables = ones(Bool, maxtarget)
for i in 2:sievelimit
n = properfactorsum(i)
if n <= maxtarget
untouchables[n] = false
end
end
for i in 6:maxtarget
if untouchables[i] && (isprime(i - 1) || isprime(i - 3))
untouchables[i] = false
end
end
println("The untouchable numbers ≤ 2000 are: ")
for (i, n) in enumerate(filter(x -> untouchables[x], 1:2000))
print(rpad(n, 5), i % 10 == 0 || i == 196 ? "\n" : "")
end
for N in [2000, 10, 100, 1000, 10_000, 100_000, 1_000_000]
println("The count of untouchable numbers ≤ $N is: ", count(x -> untouchables[x], 1:N))
end
|
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Forth | Forth | 256 buffer: filename-buf
: each-filename { xt -- } \ xt-consuming variant
s" ." open-dir throw { d }
begin filename-buf 256 d read-dir throw while
filename-buf swap xt execute
repeat d close-dir throw ;
\ immediate variant
: each-filename[ s" ." postpone sliteral ]] open-dir throw >r begin filename-buf 256 r@ read-dir throw while filename-buf swap [[ ; immediate compile-only
: ]each-filename ]] repeat drop r> close-dir throw [[ ; immediate compile-only
: ls ( -- ) [: cr type ;] each-filename ; |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| #Fortran | Fortran | PROGRAM LS !Names the files in the current directory.
USE DFLIB !Mysterious library.
TYPE(FILE$INFO) INFO !With mysterious content.
NAMELIST /HIC/INFO !This enables annotated output.
INTEGER MARK,L !Assistants.
MARK = FILE$FIRST !Starting state.
Call for the next file.
10 L = GETFILEINFOQQ("*",INFO,MARK) !Mystery routine returns the length of the file name.
IF (MARK.EQ.FILE$ERROR) THEN !Or possibly, not.
WRITE (6,*) "Error!",L !Something went wrong.
WRITE (6,HIC) !Reveal INFO, annotated.
STOP "That wasn't nice." !Quite.
ELSE IF (IAND(INFO.PERMIT,FILE$DIR) .EQ. 0) THEN !Not a directory.
IF (L.GT.0) WRITE (6,*) INFO.NAME(1:L) !The object of the exercise!
END IF !So much for that entry.
IF (MARK.NE.FILE$LAST) GO TO 10 !Lastness is discovered after the last file is fingered.
END !If FILE$LAST is not reached, "system resources may be lost." |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #R | R | #===============================================================
# Vector products
# R implementation
#===============================================================
a <- c(3, 4, 5)
b <- c(4, 3, 5)
c <- c(-5, -12, -13)
#---------------------------------------------------------------
# Dot product
#---------------------------------------------------------------
dotp <- function(x, y) {
if (length(x) == length(y)) {
sum(x*y)
}
}
#---------------------------------------------------------------
# Cross product
#---------------------------------------------------------------
crossp <- function(x, y) {
if (length(x) == 3 && length(y) == 3) {
c(x[2]*y[3] - x[3]*y[2], x[3]*y[1] - x[1]*y[3], x[1]*y[2] - x[2]*y[1])
}
}
#---------------------------------------------------------------
# Scalar triple product
#---------------------------------------------------------------
scalartriplep <- function(x, y, z) {
if (length(x) == 3 && length(y) == 3 && length(z) == 3) {
dotp(x, crossp(y, z))
}
}
#---------------------------------------------------------------
# Vector triple product
#---------------------------------------------------------------
vectortriplep <- function(x, y, z) {
if (length(x) == 3 && length(y) == 3 && length(z) == 3) {
crosssp(x, crossp(y, z))
}
}
#---------------------------------------------------------------
# Compute and print
#---------------------------------------------------------------
cat("a . b =", dotp(a, b))
cat("a x b =", crossp(a, b))
cat("a . (b x c) =", scalartriplep(a, b, c))
cat("a x (b x c) =", vectortriplep(a, b, c)) |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Tcl | Tcl | set str [gets stdin]
set num [gets stdin] |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #TI-83_BASIC | TI-83 BASIC |
:Input "Enter a string:",Str1
:Prompt i
:If(i ≠ 75000): Then
:Disp "That isn't 75000"
:Else
:Stop
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.