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/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Ruby | Ruby | class Integer
def popcount
digits(2).count(1) #pre Ruby 2.4: self.to_s(2).count("1")
end
def evil?
self >= 0 && popcount.even?
end
end
puts "Powers of 3:", (0...30).map{|n| (3**n).popcount}.join(' ')
puts "Evil:" , 0.step.lazy.select(&:evil?).first(30).join(' ')
puts "Odious:", 0.step.lazy.reject(&:evil?).first(30).join(' ') |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Scheme | Scheme | (define (power-set set)
(if (null? set)
'(())
(let ((rest (power-set (cdr set))))
(append (map (lambda (element) (cons (car set) element))
rest)
rest))))
(display (power-set (list 1 2 3)))
(newline)
(display (power-set (list "A" "C" "E")))
(newline) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Lingo | Lingo | on isPrime (n)
if n<=1 or (n>2 and n mod 2=0) then return FALSE
sq = sqrt(n)
repeat with i = 3 to sq
if n mod i = 0 then return FALSE
end repeat
return TRUE
end |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Racket | Racket |
#lang racket
(require math)
(define (factors n)
(append-map (λ (x) (make-list (cadr x) (car x))) (factorize n)))
|
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Rust | Rust | fn main() {
let mut num = 1u64;
let mut vec = Vec::new();
for _ in 0..30 {
vec.push(num.count_ones());
num *= 3;
}
println!("pop count of 3^0, 3^1 ... 3^29:\n{:?}",vec);
let mut even = Vec::new();
let mut odd = Vec::new();
num = 1;
while even.len() < 30 || odd.len() < 30 {
match 0 == num.count_ones()%2 {
true if even.len() < 30 => even.push(num),
false if odd.len() < 30 => odd.push(num),
_ => {}
}
num += 1;
}
println!("\nFirst 30 even pop count:\n{:?}",even);
println!("\nFirst 30 odd pop count:\n{:?}",odd);
} |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func array bitset: powerSet (in bitset: baseSet) is func
result
var array bitset: pwrSet is [] (bitset.value);
local
var integer: element is 0;
var integer: index is 0;
var bitset: aSet is bitset.value;
begin
for element range baseSet do
for key index range pwrSet do
aSet := pwrSet[index];
if element not in aSet then
incl(aSet, element);
pwrSet &:= aSet;
end if;
end for;
end for;
end func;
const proc: main is func
local
var bitset: aSet is bitset.value;
begin
for aSet range powerSet({1, 2, 3, 4}) do
writeln(aSet);
end for;
end func; |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #SETL | SETL | Pfour := pow({1, 2, 3, 4});
Pempty := pow({});
PPempty := pow(Pempty);
print(Pfour);
print(Pempty);
print(PPempty); |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Logo | Logo | to prime? :n
if :n < 2 [output "false]
if :n = 2 [output "true]
if equal? 0 modulo :n 2 [output "false]
for [i 3 [sqrt :n] 2] [if equal? 0 modulo :n :i [output "false]]
output "true
end |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Raku | Raku | sub prime-factors ( Int $n where * > 0 ) {
return $n if $n.is-prime;
return () if $n == 1;
my $factor = find-factor( $n );
sort flat ( $factor, $n div $factor ).map: &prime-factors;
}
sub find-factor ( Int $n, $constant = 1 ) {
return 2 unless $n +& 1;
if (my $gcd = $n gcd 6541380665835015) > 1 { # magic number: [*] primes 3 .. 43
return $gcd if $gcd != $n
}
my $x = 2;
my $rho = 1;
my $factor = 1;
while $factor == 1 {
$rho = $rho +< 1;
my $fixed = $x;
my int $i = 0;
while $i < $rho {
$x = ( $x * $x + $constant ) % $n;
$factor = ( $x - $fixed ) gcd $n;
last if 1 < $factor;
$i = $i + 1;
}
}
$factor = find-factor( $n, $constant + 1 ) if $n == $factor;
$factor;
}
.put for (2²⁹-1, 2⁴¹-1, 2⁵⁹-1, 2⁷¹-1, 2⁷⁹-1, 2⁹⁷-1, 2¹¹⁷-1, 2²⁴¹-1,
5465610891074107968111136514192945634873647594456118359804135903459867604844945580205745718497)\
.hyper(:1batch).map: -> $n {
my $start = now;
"factors of $n: ",
prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
} |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Scala | Scala | import java.lang.Long.bitCount
object PopCount extends App {
val nNumber = 30
def powersThree(start: Long): LazyList[Long] = start #:: powersThree(start * 3L)
println("Population count of 3ⁿ :")
println(powersThree(1L).map(bitCount).take(nNumber).mkString(", "))
def series(start: Long): LazyList[Long] = start #:: series(start + 1L)
println("Evil numbers:")
println(series(0L).filter(bitCount(_) % 2 == 0).take(nNumber).mkString(", "))
println("Odious numbers:")
println(series(0L).filter(bitCount(_) % 2 != 0).take(nNumber).mkString(", "))
} |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Sidef | Sidef | var arr = %w(a b c)
for i in (0 .. arr.len) {
say arr.combinations(i)
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #LSE64 | LSE64 | over : 2 pick
2dup : over over
even? : 1 & 0 =
# trial n d yields "n d 0/1 false" or "n d+2 true"
trial : 2 + true
trial : 2dup % 0 = then 0 false
trial : 2dup dup * < then 1 false
trial-loop : trial &repeat
# prime? n yields flag
prime? : 3 trial-loop >flag drop drop
prime? : dup even? then drop false
prime? : dup 2 = then drop true
prime? : dup 2 < then drop false |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #REXX | REXX | /*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
numeric digits 1000 /*handle thousand digits for the powers*/
parse arg bot top step base add /*get optional arguments from the C.L. */
if bot=='' then do; bot=1; top=100; end /*no BOT given? Then use the default.*/
if top=='' then top=bot /* " TOP? " " " " " */
if step=='' then step= 1 /* " STEP? " " " " " */
if add =='' then add= -1 /* " ADD? " " " " " */
tell= top>0; top=abs(top) /*if TOP is negative, suppress displays*/
w=length(top) /*get maximum width for aligned display*/
if base\=='' then w=length(base**top) /*will be testing powers of two later? */
@.=left('', 7); @.0="{unity}"; @.1='[prime]' /*some literals: pad; prime (or not).*/
numeric digits max(9, w+1) /*maybe increase the digits precision. */
#=0 /*#: is the number of primes found. */
do n=bot to top by step /*process a single number or a range.*/
?=n; if base\=='' then ?=base**n + add /*should we perform a "Mercenne" test? */
pf=factr(?); f=words(pf) /*get prime factors; number of factors.*/
if f==1 then #=#+1 /*Is N prime? Then bump prime counter.*/
if tell then say right(?,w) right('('f")",9) 'prime factors: ' @.f pf
end /*n*/
say
ps= 'primes'; if p==1 then ps= "prime" /*setup for proper English in sentence.*/
say right(#, w+9+1) ps 'found.' /*display the number of primes found. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure; parse arg x 1 d,$ /*set X, D to argument 1; $ to null.*/
if x==1 then return '' /*handle the special case of X = 1. */
do while x//2==0; $=$ 2; x=x%2; end /*append all the 2 factors of new X.*/
do while x//3==0; $=$ 3; x=x%3; end /* " " " 3 " " " " */
do while x//5==0; $=$ 5; x=x%5; end /* " " " 5 " " " " */
do while x//7==0; $=$ 7; x=x%7; end /* " " " 7 " " " " */
/* ___*/
q=1; do while q<=x; q=q*4; end /*these two lines compute integer √ X */
r=0; do while q>1; q=q%4; _=d-r-q; r=r%2; if _>=0 then do; d=_; r=r+q; end; end
do j=11 by 6 to r /*insure that J isn't divisible by 3.*/
parse var j '' -1 _ /*obtain the last decimal digit of J. */
if _\==5 then do while x//j==0; $=$ j; x=x%j; end /*maybe reduce by J. */
if _ ==3 then iterate /*Is next Y is divisible by 5? Skip.*/
y=j+2; do while x//y==0; $=$ y; x=x%y; end /*maybe reduce by J. */
end /*j*/
/* [↓] The $ list has a leading blank.*/
if x==1 then return $ /*Is residual=unity? Then don't append.*/
return $ x /*return $ with appended residual. */ |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: popcount (in integer: n) is
return card(bitset(n));
const proc: main is func
local
var integer: count is 0;
var integer: num is 0;
begin
for num range 0 to 29 do
write(popcount(3 ** num) <& " ");
end for;
writeln;
write("evil: ");
for num range 0 to integer.last until count >= 30 do
if not odd(popcount(num)) then
write(num <& " ");
incr(count);
end if;
end for;
writeln;
write("odious: ");
count := 0;
for num range 0 to integer.last until count >= 30 do
if odd(popcount(num)) then
write(num <& " ");
incr(count);
end if;
end for;
writeln;
end func; |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Simula | Simula | SIMSET
BEGIN
LINK CLASS LOF_INT(N); INTEGER N;;
LINK CLASS LOF_LOF_INT(H); REF(HEAD) H;;
REF(HEAD) PROCEDURE MAP(P_LI, P_LLI);
REF(HEAD) P_LI;
REF(HEAD) P_LLI;
BEGIN
REF(HEAD) V_RESULT;
V_RESULT :- NEW HEAD;
IF NOT P_LLI.EMPTY THEN BEGIN
REF(LOF_LOF_INT) V_LLI;
V_LLI :- P_LLI.FIRST QUA LOF_LOF_INT;
WHILE V_LLI =/= NONE DO BEGIN
REF(HEAD) V_NEWLIST;
V_NEWLIST :- NEW HEAD;
! ADD THE SAME 1ST ELEMENT TO EVERY NEWLIST ;
NEW LOF_INT(P_LI.FIRST QUA LOF_INT.N).INTO(V_NEWLIST);
IF NOT V_LLI.H.EMPTY THEN BEGIN
REF(LOF_INT) V_LI;
V_LI :- V_LLI.H.FIRST QUA LOF_INT;
WHILE V_LI =/= NONE DO BEGIN
NEW LOF_INT(V_LI.N).INTO(V_NEWLIST);
V_LI :- V_LI.SUC;
END;
END;
NEW LOF_LOF_INT(V_NEWLIST).INTO(V_RESULT);
V_LLI :- V_LLI.SUC;
END;
END;
MAP :- V_RESULT;
END MAP;
REF(HEAD) PROCEDURE SUBSETS(P_LI);
REF(HEAD) P_LI;
BEGIN
REF(HEAD) V_RESULT;
IF P_LI.EMPTY THEN BEGIN
V_RESULT :- NEW HEAD;
NEW LOF_LOF_INT(NEW HEAD).INTO(V_RESULT);
END ELSE BEGIN
REF(HEAD) V_SUBSET, V_MAP;
REF(LOF_INT) V_LI;
V_SUBSET :- NEW HEAD;
V_LI :- P_LI.FIRST QUA LOF_INT;
! SKIP OVER 1ST ELEMENT ;
IF V_LI =/= NONE THEN V_LI :- V_LI.SUC;
WHILE V_LI =/= NONE DO BEGIN
NEW LOF_INT(V_LI.N).INTO(V_SUBSET);
V_LI :- V_LI.SUC;
END;
V_RESULT :- SUBSETS(V_SUBSET);
V_MAP :- MAP(P_LI, V_RESULT);
IF NOT V_MAP.EMPTY THEN BEGIN
REF(LOF_LOF_INT) V_LLI;
V_LLI :- V_MAP.FIRST QUA LOF_LOF_INT;
WHILE V_LLI =/= NONE DO BEGIN
NEW LOF_LOF_INT(V_LLI.H).INTO(V_RESULT);
V_LLI :- V_LLI.SUC;
END;
END;
END;
SUBSETS :- V_RESULT;
END SUBSETS;
PROCEDURE PRINT_LIST(P_LI); REF(HEAD) P_LI;
BEGIN
OUTTEXT("[");
IF NOT P_LI.EMPTY THEN BEGIN
INTEGER I;
REF(LOF_INT) V_LI;
I := 0;
V_LI :- P_LI.FIRST QUA LOF_INT;
WHILE V_LI =/= NONE DO BEGIN
IF I > 0 THEN OUTTEXT(",");
OUTINT(V_LI.N, 0);
V_LI :- V_LI.SUC;
I := I+1;
END;
END;
OUTTEXT("]");
END PRINT_LIST;
PROCEDURE PRINT_LIST_LIST(P_LLI); REF(HEAD) P_LLI;
BEGIN
OUTTEXT("[");
IF NOT P_LLI.EMPTY THEN BEGIN
INTEGER I;
REF(LOF_LOF_INT) V_LLI;
I := 0;
V_LLI :- P_LLI.FIRST QUA LOF_LOF_INT;
WHILE V_LLI =/= NONE DO BEGIN
IF I > 0 THEN BEGIN
OUTTEXT(",");
! OUTIMAGE;
END;
PRINT_LIST(V_LLI.H);
V_LLI :- V_LLI.SUC;
I := I+1;
END;
END;
OUTTEXT("]");
OUTIMAGE;
END PRINT_LIST_LIST;
INTEGER N;
REF(HEAD) V_RANGE;
REF(HEAD) V_LISTS;
V_RANGE :- NEW HEAD;
V_LISTS :- SUBSETS(V_RANGE);
PRINT_LIST_LIST(V_LISTS);
OUTIMAGE;
FOR N := 1 STEP 1 UNTIL 4 DO BEGIN
NEW LOF_INT(N).INTO(V_RANGE);
V_LISTS :- SUBSETS(V_RANGE);
PRINT_LIST_LIST(V_LISTS);
OUTIMAGE;
END;
END.
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Lua | Lua | function IsPrime( n )
if n <= 1 or ( n ~= 2 and n % 2 == 0 ) then
return false
end
for i = 3, math.sqrt(n), 2 do
if n % i == 0 then
return false
end
end
return true
end |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Ring | Ring |
prime = 18705
decomp(prime)
func decomp nr
x = ""
for i = 1 to nr
if isPrime(i) and nr % i = 0
x = x + string(i) + " * " ok
if i = nr
x2 = substr(x,1,(len(x)-2))
see string(nr) + " = " + x2 + nl ok
next
func isPrime num
if (num <= 1) return 0 ok
if (num % 2 = 0) and num != 2 return 0 ok
for i = 3 to floor(num / 2) -1 step 2
if (num % i = 0) return 0 ok
next
return 1
|
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Sidef | Sidef | func population_count(n) { n.as_bin.count('1') }
say "#{0..29 «**« 3 «call« population_count -> join(' ')}"
var numbers = 60.of { |i|
[i, population_count(i)]
}
say "Evil: #{numbers.grep{_[1] %% 2}.map{.first}.join(' ')}"
say "Odious: #{numbers.grep{_[1] & 1}.map{.first}.join(' ')}" |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Smalltalk | Smalltalk | Collection extend [
power [
^(0 to: (1 bitShift: self size) - 1) readStream collect: [ :each || i |
i := 0.
self select: [ :elem | (each bitAt: (i := i + 1)) = 1 ] ]
]
]. |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #M2000_Interpreter | M2000 Interpreter |
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
if exist(Known1, x) then =1=1 : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
Break}
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 4: if d<= x1 else Append Known1, x : =1=1: exit
loop}
}
i=2
While Len(Known1)<20 {
dummy=Isprime(i)
i++
}
Print "first ";len(known1);" primes"
Print Known1
Print "From 110 to 130"
count=0
For i=110 to 130 {
If isPrime(i) Then Print i, : count++
}
Print
Print "Found ";count;" primes"
|
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Ruby | Ruby | irb(main):001:0> require 'prime'
=> true
irb(main):003:0> 2543821448263974486045199.prime_division
=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]] |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Swift | Swift | func populationCount(n: Int) -> Int {
guard n >= 0 else { fatalError() }
return String(n, radix: 2).filter({ $0 == "1" }).count
}
let pows = (0...)
.lazy
.map({ Int(pow(3, Double($0))) })
.map(populationCount)
.prefix(30)
let evils = (0...)
.lazy
.filter({ populationCount(n: $0) & 1 == 0 })
.prefix(30)
let odious = (0...)
.lazy
.filter({ populationCount(n: $0) & 1 == 1 })
.prefix(30)
print("Powers:", Array(pows))
print("Evils:", Array(evils))
print("Odious:", Array(odious)) |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Standard_ML | Standard ML | fun subsets xs = foldr (fn (x, rest) => rest @ map (fn ys => x::ys) rest) [[]] xs |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Swift | Swift | func powersetFrom<T>(_ elements: Set<T>) -> Set<Set<T>> {
guard elements.count > 0 else {
return [[]]
}
var powerset: Set<Set<T>> = [[]]
for element in elements {
for subset in powerset {
powerset.insert(subset.union([element]))
}
}
return powerset
}
// Example:
powersetFrom([1, 2, 4]) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #M4 | M4 | define(`testnext',
`ifelse(eval($2*$2>$1),1,
1,
`ifelse(eval($1%$2==0),1,
0,
`testnext($1,eval($2+2))')')')
define(`isprime',
`ifelse($1,2,
1,
`ifelse(eval($1<=1 || $1%2==0),1,
0,
`testnext($1,3)')')')
isprime(9)
isprime(11) |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Rust | Rust | [package]
name = "prime_decomposition"
version = "0.1.1"
edition = "2018"
[dependencies]
num-bigint = "0.3.0"
num-traits = "0.2.12"
|
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Symsyn | Symsyn |
| Pop Count 3^i
i
if i < 30
(3^i) x
popcount x 63 x
~ x $r
+ $r $s
+ ' ' $s
+ i
goif
endif
"' Pop Count 3^i : ' $s " []
| Evil Numbers
i
cnt
if cnt < 30
popcount i 7 x
x:0:1 y
if y <> 1
+ cnt
~ i $r
+ $r $e
+ ' ' $e
endif
+ i
goif
endif
"' Evil Numbers : ' $e " []
| Odious Numbers
i
cnt
if cnt < 30
popcount i 7 x
x:0:1 y
if y = 1
+ cnt
~ i $r
+ $r $o
+ ' ' $o
endif
+ i
goif
endif
"' Odious Numbers : ' $o " []
|
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Tcl | Tcl | package require Tcl 8.6
proc hammingWeight {n} {
tcl::mathop::+ {*}[split [format %llb $n] ""]
}
for {set n 0;set l {}} {$n<30} {incr n} {
lappend l [hammingWeight [expr {3**$n}]]
}
puts "p3: $l"
for {set n 0;set e [set o {}]} {[llength $e]<30||[llength $o]<30} {incr n} {
lappend [expr {[hammingWeight $n]&1 ? "o" : "e"}] $n
}
puts "evil: [lrange $e 0 29]"
puts "odious: [lrange $o 0 29]" |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Tcl | Tcl | proc subsets {l} {
set res [list [list]]
foreach e $l {
foreach subset $res {lappend res [lappend subset $e]}
}
return $res
}
puts [subsets {a b c d}] |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Maple | Maple | TrialDivision := proc( n :: integer )
if n <= 1 then
false
elif n = 2 then
true
elif type( n, 'even' ) then
false
else
for local i from 3 by 2 while i * i <= n do
if irem( n, i ) = 0 then
return false
end if
end do;
true
end if
end proc: |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #S-BASIC | S-BASIC |
rem - compute p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)
dim integer factors(16) rem log2(maxint) is sufficiently large
comment
Find the prime factors of n and store in global array factors
(arrays cannot be passed as parameters) and return the number
found. If n is prime, it will be stored as the one and only
factor.
end
function primefactors(n = integer) = integer
var p, count = integer
p = 2
count = 1
while n >= (p * p) do
begin
if mod(n, p) = 0 then
begin
factors(count) = p
count = count + 1
n = n / p
end
else
p = p + 1
end
factors(count) = n
end = count
rem -- exercise the routine by checking odd numbers from 77 to 99
var i, k, nfound = integer
for i = 77 to 99 step 2
nfound = primefactors(i)
print i;"; ";
for k = 1 to nfound
print factors(k);
next k
print
next i
end
|
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #UNIX_Shell | UNIX Shell | popcount() {
local -i n=$1
(( n < 0 )) && return 1
local ones=0
while (( n > 0 )); do
(( ones += n%2 ))
(( n /= 2 ))
done
echo $ones
}
popcount_3s=()
n=1
for (( i=0; i<30; i++ )); do
popcount_3s+=( $(popcount $n) )
(( n *= 3 ))
done
echo "powers of 3 popcounts: ${popcount_3s[*]}"
evil=()
odious=()
n=0
while (( ${#evil[@]} < 30 || ${#odious[@]} < 30 )); do
p=$( popcount $n )
if (( $p%2 == 0 )); then
evil+=( $n )
else
odious+=( $n )
fi
(( n++ ))
done
echo "evil nums: ${evil[*]:0:30}"
echo "odious nums: ${odious[*]:0:30}" |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #TXR | TXR | (defun power-set (s)
(mappend* (op comb s) (range 0 (length s)))) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | IsPrime[n_Integer] := Block[{},
If[n <= 1, Return[False]];
If[n == 2, Return[True]]; If[Mod[n, 2] == 0, Return[False]];
For[k = 3, k <= Sqrt[n], k += 2, If[Mod[n, k] == 0, Return[False]]];
Return[True]] |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Scala | Scala | import annotation.tailrec
import collection.parallel.mutable.ParSeq
object PrimeFactors extends App {
def factorize(n: Long): List[Long] = {
@tailrec
def factors(tuple: (Long, Long, List[Long], Int)): List[Long] = {
tuple match {
case (1, _, acc, _) => acc
case (n, k, acc, _) if (n % k == 0) => factors((n / k, k, acc ++ ParSeq(k), Math.sqrt(n / k).toInt))
case (n, k, acc, sqr) if (k < sqr) => factors(n, k + 1, acc, sqr)
case (n, k, acc, sqr) if (k >= sqr) => factors((1, k, acc ++ ParSeq(n), 0))
}
}
factors((n, 2, List[Long](), Math.sqrt(n).toInt))
}
def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1
def sieve(nums: Stream[Int]): Stream[Int] =
Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
// An infinite stream of primes, lazy evaluation and memo-ized
val oddPrimes = sieve(Stream.from(3, 2))
def primes = sieve(2 #:: oddPrimes)
oddPrimes takeWhile (_ <= 59) foreach { p =>
{ // Needs some intermediate results for nice formatting
val numM = s"M${p}"
val nMersenne = mersenne(p).toLong
val lit = f"${nMersenne}%30d"
val datum = System.nanoTime
val result = factorize(nMersenne)
val mSec = ((System.nanoTime - datum) / 1.0e+6).round
def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" }
def sPrime = { if (result.isEmpty) " is a prime number." else "" }
println(
f"$numM%4s = 2^$p%03d - 1 = ${lit}%s${sPrime} ($mSec%,4d msec) composed of ${result.mkString(" × ")}")
}
}
} |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #VBA | VBA | Sub Population_count()
nmax = 30
b = 3
n = 0: List = "": bb = 1
For i = 0 To nmax - 1
List = List & " " & popcount(bb)
bb = bb * b
Next 'i
Debug.Print "popcounts of the powers of " & b
Debug.Print List
For j = 0 To 1
If j = 0 Then c = "evil numbers" Else c = "odious numbers"
n = 0: List = "": i = 0
While n < nmax
If (popcount(i) Mod 2) = j Then
n = n + 1
List = List & " " & i
End If
i = i + 1
Wend
Debug.Print c
Debug.Print List
Next 'j
End Sub 'Population_count
Private Function popcount(x)
Dim y, xx, xq, xr
xx = x
While xx > 0
xq = Int(xx / 2)
xr = xx - xq * 2
If xr = 1 Then y = y + 1
xx = xq
Wend
popcount = y
End Function 'popcount |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #UNIX_Shell | UNIX Shell | p() { [ $# -eq 0 ] && echo || (shift; p "$@") | while read r ; do echo -e "$1 $r\n$r"; done } |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #MATLAB | MATLAB | function isPrime = primalityByTrialDivision(n)
if n == 2
isPrime = true;
return
elseif (mod(n,2) == 0) || (n <= 1)
isPrime = false;
return
end
%First n mod (3 to sqrt(n)) is taken. This will be a vector where the
%first element is equal to n mod 3 and the last element is equal to n
%mod sqrt(n). Then the all function is applied to that vector. If all
%of the elements of this vector are non-zero (meaning n is prime) then
%all() returns true. Otherwise, n is composite, so it returns false.
%This return value is then assigned to the variable isPrime.
isPrime = all(mod(n, (3:round(sqrt(n))) ));
end |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Scheme | Scheme | (define (factor number)
(define (*factor divisor number)
(if (> (* divisor divisor) number)
(list number)
(if (= (modulo number divisor) 0)
(cons divisor (*factor divisor (/ number divisor)))
(*factor (+ divisor 1) number))))
(*factor 2 number))
(display (factor 111111111111))
(newline) |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #VBScript | VBScript | ' Population count - VBScript - 10/05/2019
nmax=30
b=3
n=0: list="": bb=1
For i=0 To nmax-1
list=list & " " & popcount(bb)
bb=bb*b
Next 'i
Msgbox list,,"popcounts of the powers of " & b
For j=0 to 1
If j=0 Then c="evil numbers": Else c="odious numbers"
n=0: list="": i=0
While n<nmax
If (popcount(i) Mod 2)=j Then
n=n+1
list=list & " " & i
End If
i=i+1
Wend
Msgbox list,,c
Next 'j
Function popcount(x)
Dim y,xx,xq,xr
xx=x
While xx>0
xq=Int(xx/2)
xr=xx-xq*2
If xr=1 Then y=y+1
xx=xq
Wend
popcount=y
End Function 'popcount |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #UnixPipes | UnixPipes |
| cat A
a
b
c
| cat A |\
xargs -n 1 ksh -c 'echo \{`cat A`\}' |\
xargs |\
sed -e 's; ;,;g' \
-e 's;^;echo ;g' \
-e 's;\},;}\\ ;g' |\
ksh |unfold `wc -l A` |\
xargs -n1 -I{} ksh -c 'echo {} |\
unfold 1 |sort -u |xargs' |sort -u
a
a b
a b c
a c
b
b c
c
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Maxima | Maxima | isprme(n):= catch(
for k: 2 thru sqrt(n) do if mod(n, k)=0 then throw(false),
true);
map(isprme, [2, 3, 4, 65, 100, 181, 901]);
/* [true, true, false, false, false, true, false] */ |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Seed7 | Seed7 | const func array integer: factorise (in var integer: number) is func
result
var array integer: result is 0 times 0;
local
var integer: checker is 2;
begin
while checker * checker <= number do
if number rem checker = 0 then
result &:= [](checker);
number := number div checker;
else
incr(checker);
end if;
end while;
if number <> 1 then
result &:= [](number);
end if;
end func; |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Console, System.Diagnostics
Module Module1
Dim i As Integer, eo As Boolean
Function PopCnt(n As Long) As Integer
Return Convert.ToString(n, 2).ToCharArray().Where(Function(x) x = "1").Count()
End Function
Sub Aline(a As List(Of Integer), title As String)
WriteLine("{0,-8}{1}", title, String.Join(" ", a.Take(30)))
End Sub
Sub Main(ByVal args As String())
WriteLine("Population Counts:") : Dim t, e, o As New List(Of Integer)
For c As Integer = 0 To 99
If (PopCnt(c) And 1) = 0 Then e.Add(c) Else o.Add(c)
If c < 30 Then t.Add(PopCnt(CLng(Math.Pow(3, c))))
Next
Aline(t, "3^n :") : Aline(e, "Evil:") : Aline(o, "Odious:")
' Extra:
WriteLine(vbLf & "Pattern:{0}", Pattern(e, o))
If Debugger.IsAttached Then ReadKey()
End Sub
' support routines for pattern output
Function Same(a As List(Of Integer)) As Boolean
Return a(i) + 1 = a(i + 1)
End Function
Function Odd(a As List (Of Integer), b As List (Of Integer)) As Boolean
eo = Not eo : If a(i) = b(i) + 1 Then i -= 1 : Return True
Return False
End Function
Function SoO(a As List (Of Integer), b As List (Of Integer), c As String) As String
Return If(Same(a), c(0), If(Odd(b, a), c(1), c(2)))
End Function
Function Either(a As List(Of Integer), b As List(Of Integer)) As String
Return If(eo, SoO(a, b, "⌢↓↘"), SoO(b, a, "⌣↑↗"))
End Function
Function Pattern(a As List(Of Integer), b As List(Of Integer)) As String
eo = a.Contains(0) : Dim res As New Text.StringBuilder
For i = 0 To a.Count - 2 : res.Append(Either(a, b)) : Next
Return res.ToString()
End Function
End Module |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Ursala | Ursala | powerset = ~&NiC+ ~&i&& ~&at^?\~&aNC ~&ahPfatPRXlNrCDrT |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #min | min | (
:n 3 :i n sqrt :m true :p
(i m <=) (
(n i mod 0 ==) (m @i false @p) when
i 2 + @i
) while p
) :_prime? ; helper function
(
(
((2 <) (false))
((dup even?) (2 ==))
((true) (_prime?))
) case
) :prime? |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #SequenceL | SequenceL | isPrime(n) := n = 2 or (n > 1 and none(n mod ([2]++((1...floor(sqrt(n)/2))*2+1)) = 0));
primeFactorization(num) := primeFactorizationHelp(num, []);
primeFactorizationHelp(num, current(1)) :=
let
primeFactors[i] := i when num mod i = 0 and isPrime(i) foreach i within 2 ... num;
in
current when size(primeFactors) = 0
else
primeFactorizationHelp(num / product(primeFactors), current ++ primeFactors); |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var popCount = Fn.new { |n|
var count = 0
while (n != 0) {
n = n & (n - 1)
count = count + 1
}
return count
}
System.print("The population count of the first 30 powers of 3 is:")
var p3 = 1
for (i in 0..29) {
System.write("%(popCount.call(p3)) ")
p3 = p3 * 3
if (i == 20) p3 = BigInt.new(p3)
}
var odious = []
System.print("\n\nThe first 30 evil numbers are:")
var count = 0
var n = 0
while (count < 30) {
var pc = popCount.call(n)
if (pc%2 == 0) {
System.write("%(n) ")
count = count + 1
} else {
odious.add(n)
}
n = n + 1
}
odious.add(n)
System.print("\n\nThe first 30 odious numbers are:")
Fmt.print("$d", odious) |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #V | V | [A C E] powerlist
=[[A C E] [A C] [A E] [A] [C E] [C] [E] []] |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 1 - x#0 34 2 - /-/ x<0 32
ИП0 2 / {x} x#0 34
3 П4 ИП0 ИП4 / {x} x#0 34 КИП4 КИП4
ИП0 КвКор ИП4 - x<0 16 1 С/П 0 С/П |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Sidef | Sidef | say factor(536870911) #=> [233, 1103, 2089]
say factor_exp(536870911) #=> [[233, 1], [1103, 1], [2089, 1]] |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #Yabasic | Yabasic | print "Pop count (3^x): "
for i = 0 to 29
print population(3^i);
next
print "\n"
print "Evil: "
EvilOdious(30)
print "\n"
print "Odious: "
EvilOdious(30, 1)
print "\n"
sub EvilOdious(limit, type)
local i, count, eo
repeat
eo = mod(population(i), 2)
if (type and eo) or (not type and not eo) count = count + 1 : print i;
i = i + 1
until(count = limit)
end sub
sub population(number)
local i, binary$, popul
binary$ = bin$(number)
for i = 1 to len(binary$)
popul = popul + val(mid$(binary$, i, 1))
next
return popul
end sub |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| #zkl | zkl | n:=1; do(30){ print(n.num1s,","); n*=3 } println();
println("evil: ",[0..].filter(30,fcn(n){ n.num1s.isEven }).concat(","));
// now, as an iterator aka lazy:
println("odious: ",(0).walker(*).tweak( // 0,1,2,3,4... iterator
fcn(n){ if(n.num1s.isEven) Void.Skip else n }).walk(30).concat(",")); |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #VBA | VBA | Option Base 1
Private Function power_set(ByRef st As Collection) As Collection
Dim subset As Collection, pwset As New Collection
For i = 0 To 2 ^ st.Count - 1
Set subset = New Collection
For j = 1 To st.Count
If i And 2 ^ (j - 1) Then subset.Add st(j)
Next j
pwset.Add subset
Next i
Set power_set = pwset
End Function
Private Function print_set(ByRef st As Collection) As String
'assume st is a collection of collections, holding integer variables
Dim s() As String, t() As String
ReDim s(st.Count)
'Debug.Print "{";
For i = 1 To st.Count
If st(i).Count > 0 Then
ReDim t(st(i).Count)
For j = 1 To st(i).Count
Select Case TypeName(st(i)(j))
Case "Integer": t(j) = CStr(st(i)(j))
Case "Collection": t(j) = "{}" 'assumes empty
End Select
Next j
s(i) = "{" & Join(t, ", ") & "}"
Else
s(i) = "{}"
End If
Next i
print_set = "{" & Join(s, ", ") & "}"
End Function
Public Sub rc()
Dim rcset As New Collection, result As Collection
For i = 1 To 4
rcset.Add i
Next i
Debug.Print print_set(power_set(rcset))
Set rcset = New Collection
Debug.Print print_set(power_set(rcset))
Dim emptyset As New Collection
rcset.Add emptyset
Debug.Print print_set(power_set(rcset))
Debug.Print
End Sub |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Ada | Ada | with Ada.Text_IO;
with PDF_Out;
procedure Pinstripe_Printer
is
use PDF_Out;
package Point_IO
is new Ada.Text_Io.Float_IO (Real);
procedure Pinstripe (Doc : in out Pdf_Out_File;
Line_Width : Real;
Line_Height : Real;
Screen_Width : Real;
Y : Real)
is
Count : constant Natural
:= Natural (Real'Floor (Screen_Width / (2.0 * Line_Width)));
Corner : constant Point := (Doc.Left_Margin, Doc.Bottom_Margin);
Corner_Box : constant Point := Corner + (10.0, 10.0);
Corner_Text : constant Point := Corner_Box + (10.0, 10.0);
Light_Gray : constant Color_Type := (0.9, 0.9, 0.9);
Image : String (1 .. 4);
begin
-- Pinstripes
Doc.Color (Black);
for A in 0 .. Count loop
Doc.Draw (What => Corner +
Rectangle'(X_Min => 2.0 * Real (A) * Line_Width,
Y_Min => Y,
Width => Line_Width,
Height => Line_Height),
Rendering => Fill);
end loop;
-- Box
Doc.Stroking_Color (Black);
Doc.Color (Light_Gray);
Doc.Line_Width (3.0);
Doc.Draw (What => Corner_Box + (0.0, Y, 120.0, 26.0),
Rendering => Fill_Then_Stroke);
-- Text
Doc.Color (Black);
Doc.Text_Rendering_Mode (Fill);
Point_Io.Put (Image, Line_Width, Aft => 1, Exp => 0);
Doc.Put_XY (Corner_Text.X, Corner_Text.Y + Y,
Image & " point pinstripe");
end Pinstripe;
Doc : PDF_Out_File;
begin
Doc.Create ("pinstripe.pdf");
Doc.Page_Setup (A4_Portrait);
Doc.Margins (Margins_Type'(Left => Cm_2_5,
others => One_cm));
declare
Width : constant Real
:= A4_Portrait.Width - Doc.Left_Margin - Doc.Right_Margin;
Height : constant Real
:= A4_Portrait.Height - Doc.Top_Margin - Doc.Bottom_Margin;
begin
Pinstripe (Doc, 1.0, One_Inch, Width, Height - 1.0 * One_Inch);
Pinstripe (Doc, 2.0, One_Inch, Width, Height - 2.0 * One_Inch);
Pinstripe (Doc, 3.0, One_Inch, Width, Height - 3.0 * One_Inch);
Pinstripe (Doc, 4.0, One_inch, Width, Height - 4.0 * One_Inch);
Pinstripe (Doc, 5.0, One_Inch, Width, Height - 5.0 * One_Inch);
Pinstripe (Doc, 6.0, One_Inch, Width, Height - 6.0 * One_Inch);
Pinstripe (Doc, 7.0, One_Inch, Width, Height - 7.0 * One_Inch);
Pinstripe (Doc, 8.0, One_Inch, Width, Height - 8.0 * One_Inch);
Pinstripe (Doc, 9.0, One_Inch, Width, Height - 9.0 * One_Inch);
Pinstripe (Doc, 10.0, One_Inch, Width, Height - 10.0 * One_Inch);
Pinstripe (Doc, 11.0, One_Inch, Width, Height - 11.0 * One_Inch);
end;
Doc.Close;
end Pinstripe_Printer; |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #MUMPS | MUMPS | ISPRIME(N)
QUIT:(N=2) 1
NEW I,R
SET R=N#2
IF R FOR I=3:2:(N**.5) SET R=N#I Q:'R
KILL I
QUIT R |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Simula | Simula |
EXTERNAL CLASS BIGNUM;
BIGNUM
BEGIN
CLASS TEXTLIST;
BEGIN
CLASS TEXTARRAY(N); INTEGER N;
BEGIN
TEXT ARRAY DATA(1:N);
END TEXTARRAY;
PROCEDURE EXPAND(N); INTEGER N;
BEGIN
REF(TEXTARRAY) NEWARR;
INTEGER I;
NEWARR :- NEW TEXTARRAY(N);
FOR I := 1 STEP 1 UNTIL SIZE DO BEGIN
NEWARR.DATA(I) :- ARR.DATA(I);
END;
ARR :- NEWARR;
END EXPAND;
PROCEDURE APPEND(T); TEXT T;
BEGIN
IF SIZE = ARR.N THEN
EXPAND(2*ARR.N);
SIZE := SIZE+1;
ARR.DATA(SIZE) :- T;
END EXPAND;
TEXT PROCEDURE GET(I); INTEGER I;
GET :- ARR.DATA(I);
REF(TEXTARRAY) ARR;
INTEGER SIZE;
EXPAND(20);
END TEXTLIST;
REF(TEXTLIST) PROCEDURE PRIME_FACTORS(N); TEXT N;
BEGIN
REF(TEXTLIST) FACTORS;
REF(DIVMOD) DM;
TEXT P;
FACTORS :- NEW TEXTLIST;
IF TCMP(N, "1") < 0 THEN
GOTO RETURN;
P :- "2";
FOR DM :- TDIVMOD(N,P) WHILE TISZERO(DM.MOD) DO BEGIN
N :- DM.DIV;
FACTORS.APPEND(P);
END;
P :- "3";
WHILE TCMP(N,"1") > 0 AND THEN TCMP(TMUL(P,P),N) <= 0 DO BEGIN
FOR DM :- TDIVMOD(N, P) WHILE TISZERO(DM.MOD) DO BEGIN
N :- DM.DIV;
FACTORS.APPEND(P);
END;
P :- TADD(P,"2");
END;
IF TCMP(N,"1") > 0 THEN
FACTORS.APPEND(N);
RETURN:
PRIME_FACTORS :- FACTORS;
END PRIME_FACTORS;
REF(TEXTLIST) FACTORS;
TEXT INP;
INTEGER I;
FOR INP :- "536870911", "6768768", "1957", "64865899369365843" DO BEGIN
FACTORS :- PRIME_FACTORS(INP);
OUTTEXT("PRIME FACTORS OF ");
OUTTEXT(INP);
OUTTEXT(" => [");
FOR I := 1 STEP 1 UNTIL FACTORS.SIZE DO BEGIN
IF I > 1 THEN
OUTTEXT(", ");
OUTTEXT(FACTORS.GET(I));
END;
OUTTEXT("]");
OUTIMAGE;
END;
END;
|
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #VBScript | VBScript | Function Dec2Bin(n)
q = n
Dec2Bin = ""
Do Until q = 0
Dec2Bin = CStr(q Mod 2) & Dec2Bin
q = Int(q / 2)
Loop
Dec2Bin = Right("00000" & Dec2Bin,6)
End Function
Function PowerSet(s)
arrS = Split(s,",")
PowerSet = "{"
For i = 0 To 2^(UBound(arrS)+1)-1
If i = 0 Then
PowerSet = PowerSet & "{},"
Else
binS = Dec2Bin(i)
PowerSet = PowerSet & "{"
c = 0
For j = Len(binS) To 1 Step -1
If CInt(Mid(binS,j,1)) = 1 Then
PowerSet = PowerSet & arrS(c) & ","
End If
c = c + 1
Next
PowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & "},"
End If
Next
PowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & "}"
End Function
WScript.StdOut.Write PowerSet("1,2,3,4") |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Wren | Wren | import "./perm" for Powerset
var sets = [ [1, 2, 3, 4], [], [[]] ]
for (set in sets) {
System.print("The power set of %(set) is:")
System.print(Powerset.list(set))
System.print()
} |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #BBC_BASIC | BBC BASIC | PD_RETURNDC = 256
_LOGPIXELSY = 90
DIM pd{lStructSize%, hwndOwner%, hDevMode%, hDevNames%, \
\ hdc%, flags%, nFromPage{l&,h&}, nToPage{l&,h&}, \
\ nMinPage{l&,h&}, nMaxPage{l&,h&}, nCopies{l&,h&}, \
\ hInstance%, lCustData%, lpfnPrintHook%, lpfnSetupHook%, \
\ lpPrintTemplateName%, lpSetupTemplateName%, \
\ hPrintTemplate%, hSetupTemplate%}
pd.lStructSize% = DIM(pd{})
pd.hwndOwner% = @hwnd%
pd.flags% = PD_RETURNDC
SYS "PrintDlg", pd{} TO ok%
IF ok%=0 THEN QUIT
SYS "DeleteDC", @prthdc%
@prthdc% = pd.hdc%
*MARGINS 0,0,0,0
dx% = @vdu%!236-@vdu%!232
dy% = @vdu%!244-@vdu%!240
SYS "GetDeviceCaps", @prthdc%, _LOGPIXELSY TO dpi%
DIM rc{l%,t%,r%,b%}
SYS "CreateSolidBrush", 0 TO brush%
VDU 2,1,32,3
pitch% = 2
FOR y% = 0 TO dy% STEP dpi%
FOR x% = 0 TO dx%-pitch% STEP pitch%
rc.l% = x% : rc.r% = x% + pitch%/2
rc.t% = y% : rc.b% = y% + dpi%
SYS "FillRect", @prthdc%, rc{}, brush%
NEXT
pitch% += 2
NEXT y%
VDU 2,1,12,3 |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"log"
"os/exec"
"runtime"
)
var palette = [2]string{
"FFFFFF", // white
"000000", // black
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 7
for b := 1; b <= 11; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%2])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(842, 595)
pinstripe(dc)
fileName := "w_pinstripe.png"
dc.SavePNG(fileName)
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("mspaint", "/pt", fileName)
} else {
cmd = exec.Command("lp", fileName)
}
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
parse arg nbr rangeBegin rangeEnd .
if nbr = '' | nbr = '.' then do
if rangeBegin = '' | rangeBegin = '.' then rangeBegin = 1
if rangeEnd = '' | rangeEnd = '.' then rangeEnd = 100
if rangeEnd > rangeBegin then direction = 1
else direction = -1
say 'List of prime numbers from' rangeBegin 'to' rangeEnd':'
primes = ''
loop nn = rangeBegin to rangeEnd by direction
if isPrime(nn) then primes = primes nn
end nn
primes = primes.strip
say ' 'primes.changestr(' ', ',')
say ' Total number of primes:' primes.words
end
else do
if isPrime(nbr) then say nbr.right(20) 'is prime'
else say nbr.right(20) 'is not prime'
end
return
method isPrime(nbr = long) public static binary returns boolean
ip = boolean
select
when nbr < 2 then do
ip = isFalse
end
when '2 3 5 7'.wordpos(Rexx(nbr)) \= 0 then do
-- crude shortcut ripped from the Rexx example
ip = isTrue
end
when nbr // 2 == 0 | nbr // 3 == 0 then do
-- another shortcut permitted by the one above
ip = isFalse
end
otherwise do
nn = long
nnStartTerm = long 3 -- a reasonable start term - nn <= 2 is never prime
nnEndTerm = long Math.ceil(Math.sqrt(nbr)) -- a reasonable end term
ip = isTrue -- prime the pump (pun intended)
loop nn = nnStartTerm to nnEndTerm by 2
-- Note: in Rexx and NetRexx "//" is the 'remainder of division operator' (which is not the same as modulo)
if nbr // nn = 0 then do
ip = isFalse
leave nn
end
end nn
end
end
return ip
method isTrue public static returns boolean
return 1 == 1
method isFalse public static returns boolean
return \isTrue |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Slate | Slate | n@(Integer traits) primesDo: block
"Decomposes the Integer into primes, applying the block to each (in increasing
order)."
[| div next remaining |
div: 2.
next: 3.
remaining: n.
[[(remaining \\ div) isZero]
whileTrue:
[block applyTo: {div}.
remaining: remaining // div].
remaining = 1] whileFalse:
[div: next.
next: next + 2] "Just look at the next odd integer."
]. |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #XPL0 | XPL0 | func PowSet(Set, Size);
int Set, Size;
int N, M, Mask, DoComma;
[ChOut(0, ^{);
for N:= 0 to 1<<Size -1 do
[if N>0 then ChOut(0, ^,);
ChOut(0, ^{);
Mask:= 1; DoComma:= false;
for M:= 0 to Size-1 do
[if Mask & N then
[if DoComma then ChOut(0, ^,);
IntOut(0, Set(M));
DoComma:= true;
];
Mask:= Mask << 1;
];
ChOut(0, ^});
];
Text(0, "}^m^j");
];
[PowSet([2, 3, 5, 7], 4);
PowSet([1], 1);
PowSet(0, 0);
] |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #zkl | zkl | fcn pwerSet(list){
(0).pump(list.len(),List, Utils.Helpers.pickNFrom.fp1(list),
T(Void.Write,Void.Write) ) .append(list)
} |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Julia | Julia | using FileIO, ImageIO
function getnumberwithprompt(prompt, t::Type)
s = ""
while (x = tryparse(t, s)) == nothing
print("\n", prompt, ": -> ")
s = strip(readline())
end
return x
end
dpi = getnumberwithprompt("Printer DPI (dots per inch)", Int)
pwidth = getnumberwithprompt("Printer width (inches)", Float64)
plength = 10.0
imgwidth, imgheight = Int(round(pwidth * dpi)), Int(round(plength * dpi))
img = zeros(UInt8, Int(round(imgheight)), Int(round(imgwidth)))
for row in 1:imgheight, col in 1:imgwidth
stripewidth = div(row, dpi) + 1
img[row, col] = rem(col, stripewidth * 2) < stripewidth ? 0 : 255
end
save("temp.png", img)
run(`print temp.png`) # the run statement may need to be set up for the installed device
|
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Liberty_BASIC | Liberty BASIC |
nomainwin
'paperW = 8.5 ' for US letter paper
'paperH = 11
paperW = 8.2677165 ' for A4 paper
paperH = 11.6929134
dpi= 300
prompt "Enter your printer DPI" +chr$( 13) + "(300 is OK for laser one, 360 likely for inkjet)"; dpi
w = paperW *dpi 'pixel size of paper
h = paperH *dpi
graphicbox #main.gr, 0, 0, 300, 300 'picture could be bigger
open "Pinstripe/Printer" for window as #main
#main "trapclose [quit]"
#main.gr "autoresize" 'now we can maximize window with picture
#main.gr "down"
#main.gr "horizscrollbar on 0 "; w -300 'so we can scroll it
#main.gr "vertscrollbar on 0 "; h -300
#main.gr "place 0 0"
#main.gr "color white"
#main.gr "boxfilled "; w; " ";h
#main.gr "color black"
#main.gr "backcolor black"
for i = 0 to int( paperH)
ww = i + 1
yy =( i + 1) * dpi
if yy > h then yy = h
for x = ww to w step ww * 2 'start with white strip
x1 = x + ww
if x1 >= w then x1 = w
#main.gr "place "; x; " "; i * dpi
#main.gr "boxfilled "; x1; " "; yy
next
next
#main.gr "flush"
#main.gr "print "; w
wait
[quit]
close #main
end
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #newLISP | newLISP | ; Here are some simpler functions to help us:
(define (divisible? larger-number smaller-number)
(zero? (% larger-number smaller-number)))
(define (int-root number)
(floor (sqrt number)))
(define (even-prime? number)
(= number 2))
; Trial division for odd numbers
(define (find-odd-factor? odd-number)
(catch
(for (possible-factor 3 (int-root odd-number) 2)
(if (divisible? odd-number possible-factor)
(throw true)))))
(define (odd-prime? number)
(and
(odd? number)
(or
(= number 3)
(and
(> number 3)
(not (find-odd-factor? number))))))
; Now for the final overall Boolean function.
(define (is-prime? possible-prime)
(or
(even-prime? possible-prime)
(odd-prime? possible-prime)))
; Let's use this to actually find some prime numbers.
(println (filter is-prime? (sequence 1 100)))
(exit) |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Smalltalk | Smalltalk | Integer extend [
primesDo: aBlock [
| div next rest |
div := 2. next := 3.
rest := self.
[ [ rest \\ div == 0 ]
whileTrue: [
aBlock value: div.
rest := rest // div ].
rest = 1] whileFalse: [
div := next. next := next + 2 ]
]
]
123456 primesDo: [ :each | each printNl ] |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #AutoHotkey | AutoHotkey | SoundPlay, %A_WinDir%\Media\tada.wav, wait
SoundPlay, %A_WinDir%\Media\Windows XP Startup.wav, wait
; simulaneous play may require a second script
SoundPlay, %A_WinDir%\Media\tada.wav
SoundPlay, Nonexistent ; stop before finishing
SoundSet +10 ; increase volume by 10%
Loop, 2
SoundPlay, %A_WinDir%\Media\tada.wav, wait |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const Colors = [[255.0, 255.0, 255.0], [0.0, 0.0, 0.0]]
#---------------------------------------------------------------------------------------------------
proc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) =
## Process signal "begin_print", that is set the number of pages to print.
op.setNPages(1)
#---------------------------------------------------------------------------------------------------
proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) =
## Draw a page.
let context = printContext.getCairoContext()
let lineHeight = printContext.height / 4
var y = 0.0
for lineWidth in [1.0, 2.0, 3.0, 4.0]:
context.setLineWidth(lineWidth)
var x = 0.0
var colorIndex = 0
while x < printContext.width:
context.setSource(Colors[colorIndex])
context.moveTo(x, y)
context.lineTo(x, y + lineHeight)
context.stroke()
colorIndex = 1 - colorIndex
x += lineWidth
y += lineHeight
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
# Launch a print operation.
let op = newPrintOperation()
op.connect("begin_print", beginPrint, pointer(nil))
op.connect("draw_page", drawPage, pointer(nil))
# Run the print dialog.
discard op.run(printDialog)
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.Pinstripe")
discard app.connect("activate", activate)
discard app.run() |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Phix | Phix | (load "@lib/ps.l")
(call 'lpr
(pdf "pinstripes"
(a4) # 595 x 842 dots
(for X 595
(gray (if (bit? 1 X) 0 100)
(vline X 0 842) ) )
(page) ) ) |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #PicoLisp | PicoLisp | (load "@lib/ps.l")
(call 'lpr
(pdf "pinstripes"
(a4) # 595 x 842 dots
(for X 595
(gray (if (bit? 1 X) 0 100)
(vline X 0 842) ) )
(page) ) ) |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Racket | Racket |
#lang racket/gui
(define parts 4)
(define dc (new printer-dc%))
(send* dc (start-doc "Pinstripe") (start-page))
(define-values [W H] (send dc get-size))
(send dc set-pen "black" 0 'solid)
(send dc set-brush "black" 'solid)
(define H* (round (/ H parts)))
(for ([row parts])
(define Y (* row H*))
(for ([X (in-range 0 W (* (add1 row) 2))])
(send dc draw-rectangle X Y (add1 row) H*)))
(send* dc (end-page) (end-doc))
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Nim | Nim | import sequtils, math
proc prime(a: int): bool =
if a == 2: return true
if a < 2 or a mod 2 == 0: return false
for i in countup(3, sqrt(a.float).int, 2):
if a mod i == 0:
return false
return true
proc prime2(a: int): bool =
result = not (a < 2 or any(toSeq(2 .. sqrt(a.float).int), a mod it == 0))
proc prime3(a: int): bool =
if a == 2: return true
if a < 2 or a mod 2 == 0: return false
return not any(toSeq countup(3, sqrt(a.float).int, 2), a mod it == 0)
for i in 2..30:
echo i, " ", prime(i) |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #SPAD | SPAD |
(1) -> factor 102400
12 2
(1) 2 5
Type: Factored(Integer)
(2) -> factor 23193931893819371
(2) 83 3469 71341 1129153
Type: Factored(Integer)
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Batch_File | Batch File | @echo off
:main
cls
echo Drag a .wav file there and press enter
set /p file1=
sndrec32 /embedding /play /close %file1%
cls
echo Drag a second .wav file and both will play together
set /p file2=
sndrec32 /embedding /play /close %file1% | sndrec32 /embedding /play /close %file2%
echo Thanks
pause>nul
exit
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #BBC_BASIC | BBC BASIC | SND_LOOP = 8
SND_ASYNC = 1
SND_FILENAME = &20000
PRINT "Playing a MIDI file..."
*PLAY C:\windows\media\canyon.mid
WAIT 300
PRINT "Playing the Windows TADA sound quietly..."
wave$ = "\windows\media\tada.wav"
volume% = 10000
SYS "waveOutSetVolume", -1, volume% + (volume% << 16)
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC
WAIT 300
PRINT "Playing the Windows TADA sound loudly on the left channel..."
volume% = 65535
SYS "waveOutSetVolume", -1, volume%
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC
WAIT 300
PRINT "Playing the Windows TADA sound loudly on the right channel..."
volume% = 65535
SYS "waveOutSetVolume", -1, volume% << 16
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC
WAIT 300
PRINT "Looping the Windows TADA sound on both channels..."
volume% = 65535
SYS "waveOutSetVolume", -1, volume% + (volume% << 16)
SYS "PlaySound", wave$, 0, SND_FILENAME + SND_ASYNC + SND_LOOP
WAIT 300
SYS "PlaySound", 0, 0, 0
PRINT "Stopped looping..."
WAIT 300
SOUND OFF
PRINT "Stopped MIDI."
END |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #C.23 | C# | using System;
using System.Threading;
using System.Media;
class Program
{
static void Main(string[] args)
{
//load sound file
SoundPlayer s1 = new SoundPlayer(); //
s1.SoundLocation = file; // or "s1 = new SoundPlayer(file)"
//play
s1.Play();
//play for 0.1 seconds
s1.Play();
Thread.Sleep(100);
s1.Stop();
//loops
s1.PlayLooping();
}
} |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Raku | Raku | unit sub MAIN ($dpi = 300, $size = 'letter');
my $filename = './Pinstripe-printer-perl6.png';
my %paper = (
'letter' => { :width(8.5), :height(11.0) }
'A4' => { :width(8.2677), :height(11.6929)}
);
my ($w, $h) = %paper{$size}<width height> »*» $dpi;
# Black. It's all black
my @color = (0,0,0),;
my $gap = floor $w % ($dpi * 8) / 2;
my $rows = (1, * * 2 … * > 8 * $dpi).elems;
my $height = $dpi * .8;
use Cairo;
my @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) };
given Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image {
given Cairo::Context.new($image) {
my Cairo::Pattern::Solid $bg .= create(1,1,1);
.rectangle(0, 0, $w, $h);
.pattern($bg);
.fill;
$bg.destroy;
my $y = $gap;
for ^$rows -> $row {
my $x = $gap;
my $width = 8 * $dpi / (2 ** $row);
for @colors -> $this {
my $v = 0;
while $x < ($dpi * 8) {
given Cairo::Context.new($image) -> $block {
$block.rectangle($x, $y, $width, $height);
$block.pattern($this);
$block.fill;
$block.destroy;
}
$x += $width * 2;
}
}
$y += $height;
}
}
$image.write_png($filename);
}
# Uncomment next line if you actually want to print it
#run('lp', $filename) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Objeck | Objeck | function : IsPrime(n : Int) ~ Bool {
if(n <= 1) {
return false;
};
for(i := 2; i * i <= n; i += 1;) {
if(n % i = 0) {
return false;
};
};
return true;
} |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Standard_ML | Standard ML |
val factor = fn n :IntInf.int =>
let
val unfactored = fn (u,_,_) => u
val factors = fn (_,f,_) => f
val try = fn (_,_,i) => i
fun getresult t = unfactored t::(factors t)
fun until done change x =
if done x
then getresult x
else until done change (change x); (* iteration *)
fun lastprime t = unfactored t < (try t)*(try t)
fun trymore t = if unfactored t mod (try t) = 0
then (unfactored t div (try t) , try t::(factors t) , try t )
else (unfactored t , factors t , try t + 1)
in
until lastprime trymore (n,[],2)
end;
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Delphi | Delphi | program PlayRecordedSounds;
{$APPTYPE CONSOLE}
uses MMSystem;
begin
sndPlaySound('SoundFile.wav', SND_NODEFAULT OR SND_ASYNC);
end. |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Go | Go | package main
import (
"log"
"os"
"os/exec"
)
func main() {
args := []string{
"-m", "-v", "0.75", "a.wav", "-v", "0.25", "b.wav",
"-d",
"trim", "4", "6",
"repeat", "5",
}
cmd := exec.Command("sox", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #GUISS | GUISS | Start,Programs,Accessories,Media Player,Menu:File,Open,
Doubleclick:Icon:Sound.WAV,Button:OK,Button:Play |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Tcl | Tcl | package require Tk
# Allocate a temporary drawing surface
canvas .c
# Draw the output we want
for {set y 0;set dx 1} {$y < 11*72} {incr y 72;incr dx} {
for {set x 0;set c 0} {$x < 8.5*72} {incr x $dx;set c [expr {!$c}]} {
.c create rectangle $x $y [expr {$x+$dx+1}] [expr {$y+73}] \
-fill [lindex {black white} $c] -outline {}
}
}
# Send postscript to default printer, scaled 1 pixel -> 1 point
exec lp - << [.c postscript -height $y -width $x -pageheight $y -pagewidth $x]
# Explicit exit; no GUI desired
exit |
http://rosettacode.org/wiki/Pinstripe/Printer | Pinstripe/Printer | The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing graphics in terms of points, pixels may be substituted in this task.)
After the first inch of printing, we switch to a wider 2 point wide vertical pinstripe pattern. alternating two points white, two points black. We then switch to 3 points wide for the next inch, and then 4 points wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Wren | Wren | /* gcc -O3 -std=c11 -shared -o printer.so -fPIC -I./include printer.c */
#include <stdlib.h>
#include <string.h>
#include "dome.h"
static DOME_API_v0* core;
static WREN_API_v0* wren;
static const char* source = ""
"class Printer {\n"
"foreign static printFile(name) \n"
"} \n";
void C_printFile(WrenVM* vm) {
const char *arg = wren->getSlotString(vm, 1);
char command[strlen(arg) + 4];
strcpy(command, "lp ");
strcat(command, arg);
int res = system(command);
}
DOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) {
core = DOME_getAPI(API_DOME, DOME_API_VERSION);
wren = DOME_getAPI(API_WREN, WREN_API_VERSION);
core->registerModule(ctx, "printer", source);
core->registerClass(ctx, "printer", "Printer", NULL, NULL);
core->registerFn(ctx, "printer", "static Printer.printFile(_)", C_printFile);
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #OCaml | OCaml | let is_prime n =
if n = 2 then true
else if n < 2 || n mod 2 = 0 then false
else
let rec loop k =
if k * k > n then true
else if n mod k = 0 then false
else loop (k+2)
in loop 3 |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Stata | Stata | function factor(n_) {
n = n_
a = J(0,2,.)
if (n<2) {
return(a)
}
else if (n<4) {
return((n,1))
}
else {
if (mod(n,2)==0) {
for (i=0; mod(n,2)==0; i++) n = floor(n/2)
a = a\(2,i)
}
for (k=3; k*k<=n; k=k+2) {
if (mod(n,k)==0) {
for (i=0; mod(n,k)==0; i++) n = floor(n/k)
a = a\(k,i)
}
}
if (n>1) a = a\(n,1)
return(a)
}
} |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Liberty_BASIC | Liberty BASIC | 'Supports .mid and .wav natively
'Midi may be played simultaneously
'with .wav but only one .wav voice
'is supported. Multiple voices can
'be achieved via API or Dlls such
'as FMOD or Wavemix
'to play a .mid and return its length
playmidi "my.mid", midiLength
'check where we are in .mid
if midipos()<midiLength then
print "Midi still playing"
else
print "Midi ended"
end if
'to stop a playing .mid
stopmidi
'to play a .wav and wait for it to end
playwave "my.wav"
'to play a .wav and continue procesing
playwave "my.wav", async
'to loop a .wav and continue processing
playwave "my.wav",loop
'to silence any .wav
playwave ""
or
playwave "next.wav"
'to adjust .wav vol
'set left and right full on
left =65535
right=65535
dwVol=right*65536+left
calldll #winmm, "waveOutSetVolume", 0 as long, _
dwVol as long, ret as long
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Julia | Julia | using Distributed, Gtk, LibSndFile, MP3
using FileIO: load
function recordingplayerapp(numfiles=2)
# create window and widgets
win = GtkWindow("Recorded Sound Player", 400, 400) |> (GtkFrame() |> (vbox = GtkBox(:v)))
playprocess = @async(0)
filenames = fill("", numfiles)
filedurations = zeros(numfiles)
filebutton = GtkButton[]
for i in 1:numfiles
push!(filebutton, GtkButton("Select File $i"))
push!(vbox, filebutton[i])
end
sequencebutton = GtkButton("Play In Sequence")
simulbutton = GtkButton("Play Simultaneously")
seqhandlerid = zero(UInt32)
simulhandlerid = zero(UInt32)
stopbutton = GtkButton("Stop Play")
labelstart = GtkLabel("Start Position")
startcontrol = GtkScale(false, 1:100)
set_gtk_property!(startcontrol, :hexpand, true)
adj = GtkAdjustment(startcontrol)
labelstop = GtkLabel("Stop Position")
endcontrol = GtkScale(false, 1:100)
set_gtk_property!(endcontrol, :hexpand, true)
adj = GtkAdjustment(endcontrol)
labelrepeat = GtkLabel("Repeats")
repeats = GtkScale(false, 0:8)
set_gtk_property!(repeats, :hexpand, true)
set_gtk_property!(GtkAdjustment(repeats), :value, 0)
foreach(x -> push!(vbox, x), [sequencebutton, simulbutton, stopbutton, labelstart,
startcontrol, labelstop, endcontrol, labelrepeat, repeats])
twobox = GtkBox(:h)
push!(vbox, twobox)
fboxes = GtkBox[]
volumecontrols = GtkScale[]
startcontrols = GtkScale[]
endcontrols = GtkScale[]
loopcontrols = GtkScale[]
for i in 1:numfiles
push!(fboxes, GtkBox(:v))
push!(twobox, fboxes[i])
push!(volumecontrols, GtkScale(false, 0.0:0.05:1.0))
set_gtk_property!(volumecontrols[i], :hexpand, true)
adj = GtkAdjustment(volumecontrols[i])
set_gtk_property!(adj, :value, 0.5)
push!(fboxes[i], GtkLabel("Volume Stream $i"), volumecontrols[i])
signal_connect(filebutton[i], :clicked) do widget
filenames[i] = open_dialog("Pick a sound or music file")
filenames[i] = replace(filenames[i], "\\" => "/")
set_gtk_property!(filebutton[i], :label, filenames[i])
if count(x -> x != "", filenames) > 0
signal_handler_unblock(sequencebutton, seqhandlerid)
end
if count(x -> x != "", filenames) > 1
signal_handler_unblock(simulbutton, simulhandlerid)
end
if occursin(r"\.mp3$", filenames[i])
buf = load(filenames[i])
filedurations[i] = MP3.nframes(buf) / MP3.samplerate(buf)
else
buf = load(filenames[i])
filedurations[i] = LibSndFile.nframes(buf) / LibSndFile.samplerate(buf)
end
adj = GtkAdjustment(startcontrol)
set_gtk_property!(adj, :lower, 0.0)
set_gtk_property!(adj, :upper, maximum(filedurations))
set_gtk_property!(adj, :value, 0.0)
adj = GtkAdjustment(endcontrol)
set_gtk_property!(adj, :lower, 0.0)
set_gtk_property!(adj, :upper, maximum(filedurations))
set_gtk_property!(adj, :value, maximum(filedurations))
end
end
# run play after getting parameters from widgets
function play(simul::Bool)
args = simul ? String["-m"] : String[]
tstart = Gtk.GAccessor.value(startcontrol)
tend = Gtk.GAccessor.value(endcontrol)
for i in 1:numfiles
if filenames[i] != ""
volume = Gtk.GAccessor.value(volumecontrols[i])
push!(args, "-v", string(volume), filenames[i])
end
end
repeat = Gtk.GAccessor.value(repeats)
if repeat != 0
push!(args, "repeat", string(repeat))
end
if !(tstart ≈ 0.0 && tend ≈ maximum(filedurations))
push!(args, "trim", string(tstart), string(tend))
end
playprocess = run(`play $args`; wait=false)
clearfornew()
end
function clearfornew()
signal_handler_block(sequencebutton, seqhandlerid)
if count(x -> x != "", filenames) > 1
signal_handler_block(simulbutton, simulhandlerid)
end
filenames = fill("", numfiles)
filedurations = zeros(numfiles)
foreach(i -> set_gtk_property!(filebutton[i], :label, "Select File $i"), 1:numfiles)
set_gtk_property!(GtkAdjustment(repeats), :value, 0)
showall(win)
end
killplay(w) = kill(playprocess)
playsimul(w) = play(true)
playsequential(w) = play(false)
seqhandlerid = signal_connect(playsequential, sequencebutton, :clicked)
signal_handler_block(sequencebutton, seqhandlerid)
simulhandlerid = signal_connect(playsimul, simulbutton, :clicked)
signal_handler_block(simulbutton, simulhandlerid)
signal_connect(killplay, stopbutton, :clicked)
cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
showall(win)
wait(cond)
end
recordingplayerapp()
|
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | a = Import["sound1.flac","FLAC"]; b = Import["sound2.flac","FLAC"];
ListPlay[a, {t, 0, 10}]; ListPlay[b, {t, 0, 10}];
ListPlay[{a,b}, {t, 0, 10}];
Stopping before the end can be done using the GUI or by reducing the parameter range of the ListPlay function.
While[True,ListPlay[{a,b}, {t, 0, 10}];]
ListPlay[{0.5*a, 0.3*b}, {t, 0, 10}]; |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #11l | 11l | F lcm(m, n)
R m I/ gcd(m, n) * n
F get_primes(=n)
[Int] r
L(d) 2 .. n
V q = n I/ d
V m = n % d
L m == 0
r.append(d)
n = q
q = n I/ d
m = n % d
R r
F is_prime(a)
I a == 2
R 1B
I a < 2 | a % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
F pisano_period(m)
V p = 0
V c = 1
L(i) 0 .< m * m
p = (p + c) % m
swap(&p, &c)
I p == 0 & c == 1
R i + 1
R 1
F pisano_prime(p, k)
R I is_prime(p) {p ^ (k - 1) * pisano_period(p)} E 0
F pisano(m)
V primes = get_primes(m)
DefaultDict[Int, Int] prime_powers
L(p) primes
prime_powers[p]++
[Int] pps
L(k, v) prime_powers
pps.append(pisano_prime(k, v))
I pps.empty
R 1
V result = pps[0]
L(i) 1 .< pps.len
result = lcm(result, pps[i])
R result
L(p) 2..14
V pp = pisano_prime(p, 2)
I pp > 0
print(‘pisano_prime(#2, 2) = #.’.format(p, pp))
print()
L(p) 2..179
V pp = pisano_prime(p, 1)
I pp > 0
print(‘pisano_prime(#3, 1) = #.’.format(p, pp))
print()
print(‘pisano(n) for integers 'n' from 1 to 180 are:’)
L(n) 1..180
print(‘#3’.format(pisano(n)), end' I n % 15 == 0 {"\n"} E ‘ ’) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Octave | Octave | function b = isthisprime(n)
for r = 1:rows(n)
for c = 1:columns(n)
b(r,c) = false;
if ( n(r,c) == 2 )
b(r,c) = true;
elseif ( (n(r,c) < 2) || (mod(n(r,c),2) == 0) )
b(r,c) = false;
else
b(r,c) = true;
for i = 3:2:sqrt(n(r,c))
if ( mod(n(r,c), i) == 0 )
b(r,c) = false;
break;
endif
endfor
endif
endfor
endfor
endfunction
% as test, print prime numbers from 1 to 100
p = [1:100];
pv = isthisprime(p);
disp(p( pv )); |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Swift | Swift | func primeDecomposition<T: BinaryInteger>(of n: T) -> [T] {
guard n > 2 else { return [] }
func step(_ x: T) -> T {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = T(Double(n).squareRoot())
var d: T = 1
var q: T = n % 2 == 0 ? 2 : 3
while q <= maxQ && n % q != 0 {
q = step(d)
d += 1
}
return q <= maxQ ? [q] + primeDecomposition(of: n / q) : [n]
}
for prime in Eratosthenes(upTo: 60) {
let m = Int(pow(2, Double(prime))) - 1
let decom = primeDecomposition(of: m)
print("2^\(prime) - 1 = \(m) => \(decom)")
} |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Nim | Nim | import osproc
let args = ["-m", "-v", "0.75", "a.wav", "-v", "0.25", "b.wav",
"-d",
"trim", "4", "6",
"repeat", "5"]
echo execProcess("sox", args = args, options = {poStdErrToStdOut, poUsePath}) |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #Phix | Phix | integer xPlaySound = 0
procedure play_sound()--string filename)
if platform()=WINDOWS then
string filename = join_path({getenv("SYSTEMROOT"),"Media","chord.wav"})
if xPlaySound=0 then
atom winmm = open_dll("winmm.dll")
xPlaySound = define_c_proc(winmm,"sndPlaySoundA",{C_PTR,C_INT})
end if
c_proc(xPlaySound,{filename,1})
elsif platform()=LINUX then
system("paplay chimes.wav")
system("paplay chord.wav")
end if
end procedure
play_sound() |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #PicoLisp | PicoLisp | (call 'sox
"-m" "-v" "0.75" "a.wav" "-v" "0.25" "b.wav"
"-d"
"trim" 4 6
"repeat" 5 ) |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times in the sound arrive
Describe:
The supported audio formats, briefly.
Whether it is suitable for game sound effects (low-latency start, resource efficiency, supports many simultaneous sounds, etc.)
Whether it is suitable for playing music (long duration ).
[Note: If it seems to be a good idea, this task may be revised to specify a particular timeline rather than just 'demonstrate these features'.]
Where applicable, please categorize examples primarily by the audio facility used (library/API/program/platform) rather than the language if the language is incidental (e.g. "Mac OS X CoreAudio" or "mplayer" rather than "C" or "bash").
| #PureBasic | PureBasic | InitSound()
; We need this to use Sound functions
UseOGGSoundDecoder()
; Now we can not only load wav sound files, but also ogg encoded ones.
; With movie library more formats can be played (depends on system) but you cannot
; handle them with Sound functions
If Not LoadSound(1,"Path/to/Sound/1.ogg") Or Not LoadSound(2,"Path/to/Sound/2.wav")
MessageRequester("Error","One of our sounds could not be loaded"+Chr(10)+"Use Debugger to check which one")
EndIf
;- simultaneous playing
PlaySound(1)
PlaySound(2)
;- manipulating sounds
Delay(1000)
; pause for one second, to let user hear something
SoundVolume(1,90)
SoundVolume(2,60)
; reduce volume of the sounds a bit
SoundPan(1,-80)
SoundPan(2,100)
; Sound 1 mostly left speaker, sound 2 only right speaker
SoundFrequency(1,30000)
; play sound one faster
Delay(1000)
; pause for one second, to let user hear effects of previous actions
;- stopping while playing
StopSound(-1)
; value -1 stops all playing sounds
PlaySound(1,#PB_Sound_Loop)
; continous looping without glitch
;suitable for 2D games and music playing.
; TODO: There is a Sound3D library for 3D Games, needs to be decribed here too |
http://rosettacode.org/wiki/Pisano_period | Pisano period | The Fibonacci sequence taken modulo 2 is a periodic sequence of period 3 : 0, 1, 1, 0, 1, 1, ...
For any integer n, the Fibonacci sequence taken modulo n is periodic and the length of the periodic cycle is referred to as the Pisano period.
Prime numbers are straightforward; the Pisano period of a prime number p is simply: pisano(p). The Pisano period of a composite number c may be found in different ways. It may be calculated directly: pisano(c), which works, but may be time consuming to find, especially for larger integers, or, it may be calculated by finding the least common multiple of the Pisano periods of each composite component.
E.G.
Given a Pisano period function: pisano(x), and a least common multiple function lcm(x, y):
pisano(m × n) is equivalent to lcm(pisano(m), pisano(n)) where m and n are coprime
A formulae to calculate the pisano period for integer powers k of prime numbers p is:
pisano(pk) == p(k-1)pisano(p)
The equation is conjectured, no exceptions have been seen.
If a positive integer i is split into its prime factors, then the second and first equations above can be applied to generate the pisano period.
Task
Write 2 functions: pisanoPrime(p,k) and pisano(m).
pisanoPrime(p,k) should return the Pisano period of pk where p is prime and k is a positive integer.
pisano(m) should use pisanoPrime to return the Pisano period of m where m is a positive integer.
Print pisanoPrime(p,2) for every prime lower than 15.
Print pisanoPrime(p,1) for every prime lower than 180.
Print pisano(m) for every integer from 1 to 180.
Related tasks
Fibonacci sequence
Prime decomposition
Least common multiple
| #Factor | Factor | USING: formatting fry grouping io kernel math math.functions
math.primes math.primes.factors math.ranges sequences ;
: pisano-period ( m -- n )
[ 0 1 ] dip [ sq <iota> ] [ ] bi
'[ drop tuck + _ mod 2dup [ zero? ] [ 1 = ] bi* and ]
find 3nip [ 1 + ] [ 1 ] if* ;
: pisano-prime ( p k -- n )
over prime? [ "p must be prime." throw ] unless
^ pisano-period ;
: pisano ( m -- n )
group-factors [ first2 pisano-prime ] [ lcm ] map-reduce ;
: show-pisano ( upto m -- )
[ primes-upto ] dip
[ 2dup pisano-prime "%d %d pisano-prime = %d\n" printf ]
curry each nl ;
15 2 show-pisano
180 1 show-pisano
"n pisano for integers 'n' from 2 to 180:" print
2 180 [a,b] [ pisano ] map 15 group
[ [ "%3d " printf ] each nl ] each |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.