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/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Raven | Raven | define getScaleFactor use $v
[ 0.1 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62 0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.0 ] as $vals
$v 100 * 1 - 5 / 20 min 0 max 1 prefer dup $v "val: %g indx: %d\n" print $vals swap get
0 100 9 range each
100.0 / dup getScaleFactor swap "%.2g -> %.2g\n" print |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #REXX | REXX | /*REXX program re─scales a (decimal fraction) price (in the range of: 0¢ ──► $1). */
pad= ' ' /*for inserting spaces into a message. */
do j=0 to 1 by .01 /*process the prices from 0¢ to ≤ $1 */
if j==0 then j= 0.00 /*handle the special case of zero cents*/
say pad 'original price ──►' j pad adjPrice(j) " ◄── adjusted price"
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
adjPrice: procedure; parse arg ? /*a table is used to facilitate changes*/
select
when ?<0.06 then ?= 0.10
when ?<0.11 then ?= 0.18
when ?<0.16 then ?= 0.26
when ?<0.21 then ?= 0.32
when ?<0.26 then ?= 0.38
when ?<0.31 then ?= 0.44
when ?<0.36 then ?= 0.50
when ?<0.41 then ?= 0.54
when ?<0.46 then ?= 0.58
when ?<0.51 then ?= 0.62
when ?<0.56 then ?= 0.66
when ?<0.61 then ?= 0.70
when ?<0.66 then ?= 0.74
when ?<0.71 then ?= 0.78
when ?<0.76 then ?= 0.82
when ?<0.81 then ?= 0.86
when ?<0.86 then ?= 0.90
when ?<0.91 then ?= 0.94
when ?<0.96 then ?= 0.98
when ?<1.01 then ?= 1.00
otherwise nop
end /*select*/
return ? |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #Swift | Swift | func properDivs1(n: Int) -> [Int] {
return filter (1 ..< n) { n % $0 == 0 }
} |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #XLISP | XLISP | (define-class priority-queue
(instance-variables queue lowest-priority most-urgent) )
(define-method (priority-queue 'initialize limit)
(defun setup (x)
(vector-set! queue x nil)
(if (< x limit)
(setup (+ x 1)) ) )
(setq lowest-priority limit)
(setq most-urgent limit)
(setq queue (make-vector (+ limit 1)))
(setup 0)
self )
(define-method (priority-queue 'push item priority)
(if (and (integerp priority) (>= priority 0) (<= priority lowest-priority))
(progn
(setq most-urgent (min priority most-urgent))
(vector-set! queue priority (nconc (vector-ref queue priority) (cons item nil))) ) ) )
(define-method (priority-queue 'pop)
(defun find-next (q)
(if (or (= q lowest-priority) (not (null (vector-ref queue q))))
q
(find-next (+ q 1)) ) )
(define item (car (vector-ref queue most-urgent)))
(vector-set! queue most-urgent (cdr (vector-ref queue most-urgent)))
(setq most-urgent (find-next most-urgent))
item )
(define-method (priority-queue 'peek)
(car (vector-ref queue most-urgent)) )
(define-method (priority-queue 'emptyp)
(and (= most-urgent lowest-priority) (null (vector-ref queue most-urgent))) ) |
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
| #Oforth | Oforth | : factors(n) // ( aInteger -- aList )
| k p |
ListBuffer new
2 ->k
n nsqrt ->p
while( k p <= ) [
n k /mod swap ifZero: [
dup ->n nsqrt ->p
k over add continue
]
drop k 1+ ->k
]
n 1 > ifTrue: [ n over add ]
dup freeze ; |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Sidef | Sidef | class Point(x=0, y=0) {
}
class Circle(x=0, y=0, r=0) {
}
func pp(Point obj) {
say "Point at #{obj.x},#{obj.y}";
}
func pp(Circle obj) {
say "Circle at #{obj.x},#{obj.y} with radius #{obj.r}";
} |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #SIMPOL | SIMPOL | type mypoint(mypoint) embed export
embed
integer x
integer y
reference
function copy
function print
end type
function mypoint.new(mypoint me, integer x=0, integer y=0)
me.x = x
me.y = y
end function me
function mypoint.copy(mypoint me)
mypoint p
p =@ mypoint.new(me.x, me.y)
end function p
function mypoint.print(mypoint me)
end function "mypoint"
type circle(mypoint) embed export
reference
mypoint midpoint resolve
embed
integer radius
reference
function copy
function print
end type
function circle.new(circle me, integer x=0, integer y=0, integer radius=0, mypoint midpoint)
if midpoint =@= .nul
me.midpoint =@ mypoint.new(x, y)
else
me.x = midpoint.x
me.y = midpoint.y
end if
me.radius = radius
end function me
function circle.copy(circle me)
circle c
c =@ circle.new(radius=me.radius, midpoint=me.midpoint)
end function c
function circle.print(circle me)
end function "circle"
function main()
type(mypoint) p, c
string result
p =@ mypoint.new()
c =@ circle.new()
result = p.print() + "{d}{a}" + c.print() + "{d}{a}"
end function result |
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.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub evil {
my $i = 0;
sub { $i++ while population_count($i) % 2; $i++ }
}
sub odious {
my $i = 0;
sub { $i++ until population_count($i) % 2; $i++ }
}
sub population_count {
my $n = shift;
my $c;
for ($c = 0; $n; $n >>= 1) { $c += $n & 1 }
$c
}
say join ' ', map { population_count 3**$_ } 0 .. 30 - 1;
my (@evil, @odious);
my ($evil, $odious) = (evil, odious);
push( @evil, $evil->() ), push @odious, $odious->() for 1 .. 30;
say "Evil @evil";
say "Odious @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.
| #PHP | PHP |
<?php
function get_subset($binary, $arr) {
// based on true/false values in $binary array, include/exclude
// values from $arr
$subset = array();
foreach (range(0, count($arr)-1) as $i) {
if ($binary[$i]) {
$subset[] = $arr[count($arr) - $i - 1];
}
}
return $subset;
}
function print_array($arr) {
if (count($arr) > 0) {
echo join(" ", $arr);
} else {
echo "(empty)";
}
echo '<br>';
}
function print_power_sets($arr) {
echo "POWER SET of [" . join(", ", $arr) . "]<br>";
foreach (power_set($arr) as $subset) {
print_array($subset);
}
}
function power_set($arr) {
$binary = array();
foreach (range(1, count($arr)) as $i) {
$binary[] = false;
}
$n = count($arr);
$powerset = array();
while (count($binary) <= count($arr)) {
$powerset[] = get_subset($binary, $arr);
$i = 0;
while (true) {
if ($binary[$i]) {
$binary[$i] = false;
$i += 1;
} else {
$binary[$i] = true;
break;
}
}
$binary[$i] = true;
}
return $powerset;
}
print_power_sets(array());
print_power_sets(array('singleton'));
print_power_sets(array('dog', 'c', 'b', 'a'));
?>
|
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
| #Groovy | Groovy | def isPrime = {
it == 2 ||
it > 1 &&
(2..Math.max(2, (int) Math.sqrt(it))).every{ k -> it % k != 0 }
}
(0..20).grep(isPrime) |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Ring | Ring |
see pricefraction(0.5)
func pricefraction n
if n < 0.06 return 0.10 ok
if n < 0.11 return 0.18 ok
if n < 0.16 return 0.26 ok
if n < 0.21 return 0.32 ok
if n < 0.26 return 0.38 ok
if n < 0.31 return 0.44 ok
if n < 0.36 return 0.50 ok
if n < 0.41 return 0.54 ok
if n < 0.46 return 0.58 ok
if n < 0.51 return 0.62 ok
if n < 0.56 return 0.66 ok
if n < 0.61 return 0.70 ok
if n < 0.66 return 0.74 ok
if n < 0.71 return 0.78 ok
if n < 0.76 return 0.82 ok
if n < 0.81 return 0.86 ok
if n < 0.86 return 0.90 ok
if n < 0.91 return 0.94 ok
if n < 0.96 return 0.98 ok
return 1
|
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Ruby | Ruby | def rescale_price_fraction(value)
raise ArgumentError, "value=#{value}, must have: 0 <= value < 1.01" if value < 0 || value >= 1.01
if value < 0.06 then 0.10
elsif value < 0.11 then 0.18
elsif value < 0.16 then 0.26
elsif value < 0.21 then 0.32
elsif value < 0.26 then 0.38
elsif value < 0.31 then 0.44
elsif value < 0.36 then 0.50
elsif value < 0.41 then 0.54
elsif value < 0.46 then 0.58
elsif value < 0.51 then 0.62
elsif value < 0.56 then 0.66
elsif value < 0.61 then 0.70
elsif value < 0.66 then 0.74
elsif value < 0.71 then 0.78
elsif value < 0.76 then 0.82
elsif value < 0.81 then 0.86
elsif value < 0.86 then 0.90
elsif value < 0.91 then 0.94
elsif value < 0.96 then 0.98
elsif value < 1.01 then 1.00
end
end |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #tbas | tbas |
dim _proper_divisors(100)
sub proper_divisors(n)
dim i
dim _proper_divisors_count = 0
if n <> 1 then
for i = 1 to (n \ 2)
if n %% i = 0 then
_proper_divisors_count = _proper_divisors_count + 1
_proper_divisors(_proper_divisors_count) = i
end if
next
end if
return _proper_divisors_count
end sub
sub show_proper_divisors(n, tabbed)
dim cnt = proper_divisors(n)
print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) ";
dim j
for j = 1 to cnt
if tabbed then
print str$(_proper_divisors(j)),
else
print str$(_proper_divisors(j));
end if
if (j < cnt) then print ",";
next
print
end sub
dim i
for i = 1 to 10
show_proper_divisors(i, false)
next
dim c
dim maxindex = 0
dim maxlength = 0
for t = 1 to 20000
c = proper_divisors(t)
if c > maxlength then
maxindex = t
maxlength = c
end if
next
print "A maximum at ";
show_proper_divisors(maxindex, false)
|
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #Zig | Zig |
const std = @import("std");
const PriorityQueue = std.PriorityQueue;
const Allocator = std.mem.Allocator;
const testing = std.testing;
/// wrapper for the task - stores task priority
/// along with the task name
const Task = struct {
const Self = @This();
priority: i32,
name: []const u8,
pub fn init(priority: i32, name: []const u8) Self {
return Self{
.priority = priority,
.name = name,
};
}
};
/// Simple wrapper for the comparator function.
/// Each comparator function has the following signature:
///
/// fn(T, T) bool
const Comparator = struct {
fn maxCompare(a: Task, b: Task) bool {
return a.priority > b.priority;
}
fn minCompare(a: Task, b: Task) bool {
return a.priority < b.priority;
}
};
test "priority queue (max heap)" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
var pq = PriorityQueue(Task).init(allocator, Comparator.maxCompare);
defer pq.deinit();
try pq.add(Task.init(3, "Clear drains"));
try pq.add(Task.init(4, "Feed Cat"));
try pq.add(Task.init(5, "Make tea"));
try pq.add(Task.init(1, "Solve RC tasks"));
try pq.add(Task.init(2, "Tax returns"));
testing.expectEqual(pq.count(), 5);
std.debug.print("\n", .{});
// execute the tasks in decreasing order of priority
while (pq.count() != 0) {
const task = pq.remove();
std.debug.print("Executing: {} (priority {})\n", .{ task.name, task.priority });
}
std.debug.print("\n", .{});
}
test "priority queue (min heap)" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
var pq = PriorityQueue(Task).init(allocator, Comparator.minCompare);
defer pq.deinit();
try pq.add(Task.init(3, "Clear drains"));
try pq.add(Task.init(4, "Feed Cat"));
try pq.add(Task.init(5, "Make tea"));
try pq.add(Task.init(1, "Solve RC tasks"));
try pq.add(Task.init(2, "Tax returns"));
testing.expectEqual(pq.count(), 5);
std.debug.print("\n", .{});
// execute the tasks in increasing order of priority
while (pq.count() != 0) {
const task = pq.remove();
std.debug.print("Executing: {} (priority {})\n", .{ task.name, task.priority });
}
std.debug.print("\n", .{});
}
|
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
| #PARI.2FGP | PARI/GP | pd(n)={
my(f=factor(n),v=f[,1]~);
for(i=1,#v,
while(f[i,2]--,
v=concat(v,f[i,1])
)
);
vecsort(v)
}; |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Smalltalk | Smalltalk | !Object subclass: #Point
instanceVariableNames: 'x y'
classVariableNames: ''
poolDictionaries: ''
category: 'polymorphism' !
!Point class methodsFor: 'instance creation'!
new
^self newBasic x := 0; y := 0 ! !
!Point class methodsFor: 'instance creation'!
x: x y: y
^self newBasic x := x; y := y ! !
!Point methodsFor: 'member access'!
x
^x ! !
!Point methodsFor: 'member access'!
y
^y ! !
!Point methodsFor: 'member access'!
x: x
^self x := x ! !
!Point methodsFor: 'member access'!
y: y
^self y := y ! !
!Point methodsFor: 'member access'!
x: x y: y
^self x := x; y := y ! !
!Point methodsFor: 'polymorphism test'!
print
Transcript show: x; space; show: y ! !
!Object subclass: #Circle
instanceVariableNames: 'center r'
classVariableNames: ''
poolDictionaries: ''
category: 'polymorphism' !
!Circle class methodsFor: 'instance creation'!
new
^self newBasic center := Point new; r := 0 ! !
!Circle class methodsFor: 'instance creation'!
radius: radius
^self newBasic center := Point new; r := radius ! !
!Circle class methodsFor: 'instance creation'!
at: point radius: r
^self newBasic center := point; r := r ! !
!Circle methodsFor: 'member access'!
center
^center ! !
!Circle methodsFor: 'member access'!
x: x y: y
^self center x: x y: y ! !
!Circle methodsFor: 'member access'!
radius
^r ! !
!Circle methodsFor: 'member access'!
radius: radius
^self r := radius ! !
!Circle methodsFor: 'polymorphism test'!
print
Transcript show: center; space; show: radius ! ! |
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.
| #Phix | Phix | with javascript_semantics
function pop_count(atom n)
if n<0 then ?9/0 end if
integer res = 0
while n!=0 do
res += and_bits(n,1)
n = floor(n/2)
end while
return res
end function
printf(1,"3^x pop_counts:%v\n",{apply(apply(true,power,{3,tagset(29,0)}),pop_count)})
procedure eo(integer b0, string name)
sequence s = repeat(0,30)
integer k=0, l=1
while l<=30 do
if and_bits(pop_count(k),1)=b0 then
s[l] = k
l += 1
end if
k += 1
end while
printf(1,"%s numbers:%v\n",{name,s})
end procedure
eo(0," evil")
eo(1,"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.
| #PicoLisp | PicoLisp | (de powerset (Lst)
(ifn Lst
(cons)
(let L (powerset (cdr Lst))
(conc
(mapcar '((X) (cons (car Lst) X)) L)
L ) ) ) ) |
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.
| #PL.2FI | PL/I | *process source attributes xref or(!);
/*--------------------------------------------------------------------
* 06.01.2014 Walter Pachl translated from REXX
*-------------------------------------------------------------------*/
powerset: Proc Options(main);
Dcl (hbound,index,left,substr) Builtin;
Dcl sysprint Print;
Dcl s(4) Char(5) Var Init('one','two','three','four');
Dcl ps Char(1000) Var;
Dcl (n,chunk,p) Bin Fixed(31);
n=hbound(s); /* number of items in the list. */
ps='{} '; /* start with a null power set. */
Do chunk=1 To n; /* loop through the ... . */
ps=ps!!combn(chunk); /* a CHUNK at a time. */
End;
Do While(ps>'');
p=index(ps,' ');
Put Edit(left(ps,p-1))(Skip,a);
ps=substr(ps,p+1);
End;
combn: Proc(y) Returns(Char(1000) Var);
/*--------------------------------------------------------------------
* returns the list of subsets with y elements of set s
*-------------------------------------------------------------------*/
Dcl (y,base,bbase,ym,p,j,d,u) Bin Fixed(31);
Dcl (z,l) Char(1000) Var Init('');
Dcl a(20) Bin Fixed(31) Init((20)0);
Dcl i Bin Fixed(31);
base=hbound(s)+1;
bbase=base-y;
ym=y-1;
Do p=1 To y;
a(p)=p;
End;
Do j=1 By 1;
l='';
Do d=1 To y;
u=a(d);
l=l!!','!!s(u);
End;
z=z!!'{'!!substr(l,2)!!'} ';
a(y)=a(y)+1;
If a(y)=base Then
If combu(ym) Then
Leave;
End;
/* Put Edit('combn',y,z)(Skip,a,f(2),x(1),a); */
Return(z);
combu: Proc(d) Recursive Returns(Bin Fixed(31));
Dcl (d,u) Bin Fixed(31);
If d=0 Then
Return(1);
p=a(d);
Do u=d To y;
a(u)=p+1;
If a(u)=bbase+u Then
Return(combu(u-1));
p=a(u);
End;
Return(0);
End;
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
| #Haskell | Haskell | isPrime n = n==2 || n>2 && all ((> 0).rem n) (2:[3,5..floor.sqrt.fromIntegral $ n+1]) |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Run_BASIC | Run BASIC | data .06, .1,.11,.18,.16,.26,.21,.32,.26,.38,.31,.44,.36,.50,.41,.54,.46,.58,.51,.62
data .56,.66,.61,.70,.66,.74,.71,.78,.76,.82,.81,.86,.86,.90,.91,.94,.96,.98
dim od(100)
dim nd(100)
for i = 1 to 19
read oldDec
read newDec
j = j + 1
for j = j to oldDec * 100
nd(j) = newDec
next j
next i
[loop]
input "Gimme a number";numb
decm = val(using("##",(numb mod 1) * 100))
print numb;" -->";nd(decm)
goto [loop] |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Rust | Rust | fn fix_price(num: f64) -> f64 {
match num {
0.96...1.00 => 1.00,
0.91...0.96 => 0.98,
0.86...0.91 => 0.94,
0.81...0.86 => 0.90,
0.76...0.81 => 0.86,
0.71...0.76 => 0.82,
0.66...0.71 => 0.78,
0.61...0.66 => 0.74,
0.56...0.61 => 0.70,
0.51...0.56 => 0.66,
0.46...0.51 => 0.62,
0.41...0.46 => 0.58,
0.36...0.41 => 0.54,
0.31...0.36 => 0.50,
0.26...0.31 => 0.44,
0.21...0.26 => 0.38,
0.16...0.21 => 0.32,
0.11...0.16 => 0.26,
0.06...0.11 => 0.18,
0.00...0.06 => 0.10,
// panics on invalid value
_ => unreachable!(),
}
}
fn main() {
let mut n: f64 = 0.04;
while n <= 1.00 {
println!("{:.2} => {}", n, fix_price(n));
n += 0.04;
}
}
// and a unit test to check that we haven't forgotten a branch, use 'cargo test' to execute test.
//
// typically this could be included in the match as those check for exhaustiveness already
// by explicitly listing all remaining ranges / values instead of a catch-all underscore (_)
// but f64::NaN, f64::INFINITY and f64::NEG_INFINITY can't be matched like this
#[test]
fn exhaustiveness_check() {
let mut input_price = 0.;
while input_price <= 1. {
fix_price(input_price);
input_price += 0.01;
}
} |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #Tcl | Tcl | proc properDivisors {n} {
if {$n == 1} return
set divs 1
for {set i 2} {$i*$i <= $n} {incr i} {
if {!($n % $i)} {
lappend divs $i
if {$i*$i < $n} {
lappend divs [expr {$n / $i}]
}
}
}
return $divs
}
for {set i 1} {$i <= 10} {incr i} {
puts "$i => {[join [lsort -int [properDivisors $i]] ,]}"
}
set maxI [set maxC 0]
for {set i 1} {$i <= 20000} {incr i} {
set c [llength [properDivisors $i]]
if {$c > $maxC} {
set maxI $i
set maxC $c
}
}
puts "max: $maxI => (...$maxC…)" |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #zkl | zkl | class PQ{
fcn init(numLevels=10){ // 0..numLevels, bigger # == lower priorty
var [const] queue=(1).pump(numLevels+1,List.createLong(numLevels).write,L().copy);
}
fcn add(item,priorty){ queue[priorty].append(item); }
fcn peek{ if(q:=queue.filter1()) return(q[-1]); Void }// -->Void if empty
fcn pop { if(q:=queue.filter1()) return(q.pop()); Void }// -->Void if empty
var [private] state=L();
fcn [private] next{ // iterate
qi,ii:=state;
foreach n in ([qi..queue.len()-1]){
q:=queue[n];
if(ii>=q.len()) ii=0;
else{ state.clear().append(n,ii+1); return(q[ii]) }
}
Void.Stop
}
fcn walker{ state.clear().append(0,0); Walker(next) } // iterator front end
fcn toString{ "PQ(%d) items".fmt(queue.reduce(fcn(sum,q){ sum+q.len() },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
| #Pascal | Pascal | Program PrimeDecomposition(output);
type
DynArray = array of integer;
procedure findFactors(n: Int64; var d: DynArray);
var
divisor, next, rest: Int64;
i: integer;
begin
i := 0;
divisor := 2;
next := 3;
rest := n;
while (rest <> 1) do
begin
while (rest mod divisor = 0) do
begin
setlength(d, i+1);
d[i] := divisor;
inc(i);
rest := rest div divisor;
end;
divisor := next;
next := next + 2;
end;
end;
var
factors: DynArray;
j: integer;
begin
setlength(factors, 1);
findFactors(1023*1024, factors);
for j := low(factors) to high(factors) do
writeln (factors[j]);
end. |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Swift | Swift | class RCPoint : Printable {
var x: Int
var y: Int
init(x: Int = 0, y: Int = 0) {
self.x = x
self.y = y
}
convenience init(p: RCPoint) {
self.init(x:p.x, y:p.y)
}
var description: String {
return "<RCPoint x: \(self.x) y: \(self.y)>"
}
}
class RCCircle : RCPoint {
var r: Int
init(p: RCPoint, r: Int = 0) {
self.r = r
super.init(x:p.x, y:p.y)
}
init(x: Int = 0, y: Int = 0, r: Int = 0) {
self.r = r
super.init(x:x, y:y)
}
convenience init(c: RCCircle) {
self.init(x:c.x, y:c.y, r:c.r)
}
override var description: String {
return "<RCCircle x: \(x) y: \(y) r: \(r)>"
}
}
println(RCPoint())
println(RCPoint(x:3))
println(RCPoint(x:3, y:4))
println(RCCircle())
println(RCCircle(x:3))
println(RCCircle(x:3, y:4))
println(RCCircle(x:3, y:4, r:7))
let p = RCPoint(x:1, y:2)
println(RCCircle(p:p))
println(RCCircle(p:p, r:7))
println(p.x) // 1
p.x = 8
println(p.x) // 8 |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Tcl | Tcl | package require TclOO
oo::class create Point {
variable X Y
constructor {x y} {
set X $x
set Y $y
}
method x args {
set X {*}$args
}
method y args {
set Y {*}$args
}
method print {} {
puts "Point($X,$Y)"
}
method copy {} {
set copy [oo::copy [self]]
$copy x $X
$copy y $Y
return $copy
}
}
oo::class create Circle {
superclass Point
variable R
constructor {x y radius} {
next $x $y
set R $radius
}
method radius args {
set R {*}$args
}
method print {} {
puts "Circle([my x],[my y],$R)"
}
method copy {} {
set copy [next]
$copy radius $R
return $copy
}
}
# No destructors: unneeded by these classes
set p [Point new 1.0 2.0]
set c [Circle new 3.0 4.0 5.0]
set cCopy [$c copy]
puts "$p is at ([$p x],[$p y])"
$c radius 1.5
set objects [list $p $c $cCopy]
foreach o $objects {
$o print
} |
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.
| #PHP | PHP |
function convertToBinary($integer) {
$binary = "";
do {
$quotient = (int) ($integer / 2);
$binary .= $integer % 2;
$integer = $quotient;
} while ($quotient > 0);
return $binary;
}
function getPopCount($integer) {
$binary = convertToBinary($integer);
$offset = 0;
$popCount = 0;
do {
$pos = strpos($binary, "1", $offset);
if($pos !== FALSE) $popCount++;
$offset = $pos + 1;
} while ($pos !== FALSE);
return $popCount;
}
function print3PowPopCounts() {
for ($p = 0; $p < 30; $p++) {
echo " " . getPopCount(3 ** $p);
}
}
function printFirst30Evil() {
$counter = 0;
$pops = 0;
while ($pops < 30) {
$popCount = getPopCount($counter);
if ($popCount % 2 == 0) {
echo " " . $counter;
$pops++;
}
$counter++;
}
}
function printFirst30Odious() {
$counter = 1;
$pops = 0;
while ($pops < 30) {
$popCount = getPopCount($counter);
if ($popCount % 2 != 0) {
echo " " . $counter;
$pops++;
}
$counter++;
}
}
echo "3 ^ x pop counts:";
print3PowPopCounts();
echo "\nfirst 30 evil numbers:";
printFirst30Evil();
echo "\nfirst 30 odious numbers:";
printFirst30Odious();
|
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.
| #PowerShell | PowerShell |
function power-set ($array) {
if($array) {
$n = $array.Count
function state($set, $i){
if($i -gt -1) {
state $set ($i-1)
state ($set+@($array[$i])) ($i-1)
} else {
"$($set | sort)"
}
}
$set = state @() ($n-1)
$power = 0..($set.Count-1) | foreach{@(0)}
$i = 0
$set | sort | foreach{$power[$i++] = $_.Split()}
$power | sort {$_.Count}
} else {@()}
}
$OFS = " "
$setA = power-set @(1,2,3,4)
"number of sets in setA: $($setA.Count)"
"sets in setA:"
$OFS = ", "
$setA | foreach{"{"+"$_"+"}"}
$setB = @()
"number of sets in setB: $($setB.Count)"
"sets in setB:"
$setB | foreach{"{"+"$_"+"}"}
$setC = @(@(), @(@()))
"number of sets in setC: $($setC.Count)"
"sets in setC:"
$setC | foreach{"{"+"$_"+"}"}
$OFS = " "
|
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
| #HicEst | HicEst | DO n = 1, 1E6
Euler = n^2 + n + 41
IF( Prime(Euler) == 0 ) WRITE(Messagebox) Euler, ' is NOT prime for n =', n
ENDDO ! e.g. 1681 = 40^2 + 40 + 41 is NOT prime
END
FUNCTION Prime(number)
Prime = number == 2
IF( (number > 2) * MOD(number,2) ) THEN
DO i = 3, number^0.5, 2
IF(MOD(number,i) == 0) THEN
Prime = 0
RETURN
ENDIF
ENDDO
Prime = 1
ENDIF
END |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Scala | Scala | def priceFraction(x:Double)=x match {
case n if n>=0 && n<0.06 => 0.10
case n if n<0.11 => 0.18
case n if n<0.36 => ((((n*100).toInt-11)/5)*6+26)/100.toDouble
case n if n<0.96 => ((((n*100).toInt-31)/5)*4+50)/100.toDouble
case _ => 1.00
}
def testPriceFraction()=
for(n <- 0.00 to (1.00, 0.01)) println("%.2f %.2f".format(n, priceFraction(n))) |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #VBA | VBA | Public Sub Proper_Divisor()
Dim t() As Long, i As Long, l As Long, j As Long, c As Long
For i = 1 To 10
Debug.Print "Proper divisor of " & i & " : " & Join(S(i), ", ")
Next
For i = 2 To 20000
l = UBound(S(i)) + 1
If l > c Then c = l: j = i
Next
Debug.Print "Number in the range 1 to 20,000 with the most proper divisors is : " & j
Debug.Print j & " count " & c & " proper divisors"
End Sub
Private Function S(n As Long) As String()
'returns the proper divisors of n
Dim j As Long, t() As String, c As Long
't = list of proper divisor of n
If n > 1 Then
For j = 1 To n \ 2
If n Mod j = 0 Then
ReDim Preserve t(c)
t(c) = j
c = c + 1
End If
Next
End If
S = t
End Function |
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
| #Perl | Perl | sub prime_factors {
my ($n, $d, @out) = (shift, 1);
while ($n > 1 && $d++) {
$n /= $d, push @out, $d until $n % $d;
}
@out
}
print "@{[prime_factors(1001)]}\n"; |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Wollok | Wollok |
class Point {
var x
var y
new(ax, ay) {
this.x = ax
this.y = ay
}
new(point) {
this(point.x, point.y)
}
method getX() { return x }
method setX(newX) { x = newX }
method getY() { return y }
method setY(newY) { y = newY }
method print() {
console.println("Point")
}
}
class Circle extends Point {
var r
new() { this(0,0,0) }
new(point, aR) { super(point) ; r = aR }
new(aX, aY, aR) { super(aX, aY); r = aR }
method getR() { return r }
method setR(newR) { r = newR }
method print() {
console.println("Circle")
}
}
program polymorphism {
val p = new Point()
val c = new Circle()
p.print()
c.print()
}
|
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Wren | Wren | class Point {
construct new(x, y) {
_x = x
_y = y
}
static new(x) { new(x, 0) }
static new() { new(0, 0) }
static fromPoint(p) { new(p.x, p.y) }
x { _x }
y { _y }
print() { System.print("Point at (%(_x), %(_y))") }
}
class Circle is Point {
construct new(x, y, r) {
super(x, y)
_r = r
}
static new(x, r) { new(x, 0, r) }
static new(x) { new(x, 0, 0) }
static new() { new(0, 0, 0) }
static fromCircle(c) { new(c.x, c.y, c.r) }
r { _r }
print() { System.print("Circle at center(%(x), %(y)), radius %(_r)") }
}
var points = [Point.new(), Point.new(1), Point.new(2, 3), Point.fromPoint(Point.new(3, 4))]
for (point in points) point.print()
var circles = [
Circle.new(), Circle.new(1), Circle.new(2, 3),
Circle.new(4, 5, 6), Circle.fromCircle(Circle.new(7, 8, 9))
]
for (circle in circles) circle.print() |
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.
| #Picat | Picat | go =>
println(powers_of_three=[pop_count(3**I) : I in 0..29]),
println('evil_numbers '=take_n($evil_number, 30,0)),
println('odious_numbers '=take_n($odious_number, 30,0)),
nl.
% Get the first N numbers that satisfies function F, starting with S
take_n(F,N,S) = L =>
I = S,
C = 0,
L = [],
while(C < N)
if call(F,I) then
L := L ++ [I],
C := C + 1
end,
I := I + 1
end.
evil_number(N) => pop_count(N) mod 2 == 0.
odious_number(N) => pop_count(N) mod 2 == 1.
pop_count(N) = sum([1: I in N.to_binary_string(), I = '1']). |
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.
| #Prolog | Prolog | powerset(X,Y) :- bagof( S, subseq(S,X), Y).
subseq( [], []).
subseq( [], [_|_]).
subseq( [X|Xs], [X|Ys] ) :- subseq(Xs, Ys).
subseq( [X|Xs], [_|Ys] ) :- append(_, [X|Zs], Ys), subseq(Xs, Zs).
|
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
| #Icon_and_Unicon | Icon and Unicon | procedure isprime(n) #: return n if prime (using trial division) or fail
if not n = integer(n) | n < 2 then fail # ensure n is an integer greater than 1
every if 0 = (n % (2 to sqrt(n))) then fail
return n
end |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: computePrice (in float: x) is func
result
var float: price is 0.0;
begin
if x >= 0.0 and x < 0.06 then
price := 0.10;
elsif x < 0.11 then
price := 0.18;
elsif x < 0.36 then
price := flt(((trunc(x * 100.0) - 11) div 5) * 6 + 26) / 100.0;
elsif x < 0.96 then
price := flt(((trunc(x * 100.0) - 31) div 5) * 4 + 50) / 100.0;
else
price := 1.0;
end if;
end func;
const proc: main is func
local
var integer: i is 0;
begin
for i range 0 to 100 do
writeln(flt(i) / 100.0 digits 2 <& " " <& computePrice(flt(i) / 100.0) digits 2);
end for;
end func; |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Sidef | Sidef | var table = <<'EOT'.lines.map { .words.grep{.is_numeric}.map{.to_n} }
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
EOT
func price(money) {
table.each { |row|
(row[0] <= money) ->
&& (row[1] > money) ->
&& return row[2];
}
die "Out of range";
}
for n in %n(0.3793 0.4425 0.0746 0.6918 0.2993 0.5486 0.7848 0.9383 0.2292) {
say price(n);
} |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function ProperDivisors(number As Integer) As IEnumerable(Of Integer)
Return Enumerable.Range(1, number / 2).Where(Function(divisor As Integer) number Mod divisor = 0)
End Function
Sub Main()
For Each number In Enumerable.Range(1, 10)
Console.WriteLine("{0}: {{{1}}}", number, String.Join(", ", ProperDivisors(number)))
Next
Dim record = Enumerable.Range(1, 20000).Select(Function(number) New With {.Number = number, .Count = ProperDivisors(number).Count()}).OrderByDescending(Function(currentRecord) currentRecord.Count).First()
Console.WriteLine("{0}: {1}", record.Number, record.Count)
End Sub
End Module |
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
| #Phix | Phix | with javascript_semantics
requires("1.0.0")
include mpfr.e
atom t0 = time()
mpz z = mpz_init()
for i=1 to 25 do
integer pi = get_prime(i)
mpz_ui_pow_ui(z,2,pi)
mpz_sub_ui(z,z,1)
string zs = mpz_get_str(z),
fs = mpz_factorstring(mpz_pollard_rho(z))
if fs!=zs then zs &= " = "&fs end if
printf(1,"2^%d-1 = %s\n",{pi,zs})
end for
string s = "600851475143"
for i=1 to 2 do
mpz_set_str(z,s)
printf(1,"%s = %s\n",{s,mpz_factorstring(mpz_pollard_rho(z))})
s = "100000000000000000037"
end for
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #zkl | zkl | class Point{var x,y;
fcn init(xyOrPoint=0,_=0){
if(Point.isInstanceOf(xyOrPoint)) set(xyOrPoint);
else x,y=vm.arglist.apply("toFloat")}
fcn set(p){x=p.x;y=p.y}
fcn toString{"(%d,%d)".fmt(x,y)}
}
class Circle{var center, radius;
fcn init(a=0.0,b=0.0,r=1.0){
switch [arglist]{
case(Circle){ center=Point(a.center); radius=a.radius }
case(Point) { center=Point(a); radius=b.toFloat(); }
else { center=Point(a,b); radius=r.toFloat(); }
}
}
fcn copy{self(self)}
fcn toString{"(%s,%d)".fmt(center.toString(),radius)}
}
// see if various constructors work
Point(); Point(1); Point(1,2), Point(Point());
Circle(); Circle(1); Circle(1,2); Circle(1,2,3);
Circle(Point()); Circle(Point(),1);
Circle(Circle());
c:=Circle(1,2,3);
c.println(); c.center.println();
c.copy().println(); |
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.
| #PicoLisp | PicoLisp | (de popz (N)
(cnt
'((N) (= "1" N))
(chop (bin N)) ) )
(println
'pops:
(mapcar
'((N) (popz (** 3 N)))
(range 0 29) ) )
(setq N -1)
(println
'evil:
(make
(for (C 0 (> 30 C))
(unless (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) )
(setq N -1)
(println
'odio:
(make
(for (C 0 (> 30 C))
(when (bit? 1 (popz (inc 'N)))
(link N)
(inc 'C) ) ) ) ) |
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.
| #PureBasic | PureBasic | If OpenConsole()
Define argc=CountProgramParameters()
If argc>=(SizeOf(Integer)*8) Or argc<1
PrintN("Set out of range.")
End 1
Else
Define i, j, text$
Define.q bset=1<<argc
Print("{")
For i=0 To bset-1 ; check all binary combinations
If Not i: text$= "{"
Else : text$=", {"
EndIf
k=0
For j=0 To argc-1 ; step through each bit
If i&(1<<j)
If k: text$+", ": EndIf ; pad the output
text$+ProgramParameter(j): k+1 ; append each matching bit
EndIf
Next j
Print(text$+"}")
Next i
PrintN("}")
EndIf
EndIf |
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
| #J | J | isprime=: 3 : 'if. 3>:y do. 1<y else. 0 *./@:< y|~2+i.<.%:y end.' |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Smalltalk | Smalltalk | "Table driven rescale"
Object subclass: PriceRescale [
|table|
PriceRescale class >> new: theTable [
^ self basicNew initialize: theTable
]
initialize: theTable [
table := theTable asOrderedCollection.
^self
]
rescale: aPrice [ |v1 v2|
1 to: (table size - 1) do: [:i|
v1 := table at: i.
v2 := table at: (i+1).
((aPrice >= (v1 x)) & (aPrice < (v2 x)))
ifTrue: [ ^ v1 y ]
].
(aPrice < ((v1:=(table first)) x)) ifTrue: [ ^ v1 y ].
(aPrice >= ((v1:=(table last)) x)) ifTrue: [ ^ v1 y ]
]
].
|pr|
pr := PriceRescale
new: { 0.00@0.10 .
0.06@0.18 .
0.11@0.26 .
0.16@0.32 .
0.21@0.38 .
0.26@0.44 .
0.31@0.50 .
0.36@0.54 .
0.41@0.58 .
0.46@0.62 .
0.51@0.66 .
0.56@0.70 .
0.61@0.74 .
0.66@0.78 .
0.71@0.82 .
0.76@0.86 .
0.81@0.90 .
0.86@0.94 .
0.91@0.98 .
0.96@1.00 .
1.01@1.00
}.
"get a price"
(pr rescale: ( (Random between: 0 and: 100)/100 )) displayNl. |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
for (i in 1..10) System.print("%(Fmt.d(2, i)) -> %(Int.properDivisors(i))")
System.print("\nThe number in the range [1, 20000] with the most proper divisors is:")
var number = 1
var maxDivs = 0
for (i in 2..20000) {
var divs = Int.properDivisors(i).count
if (divs > maxDivs) {
number = i
maxDivs = divs
}
}
System.print("%(number) which has %(maxDivs) proper divisors.") |
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
| #Picat | Picat | go =>
% Checking 2**prime-1
foreach(P in primes(60))
Factors = factors(2**P-1),
println([n=2**P-1,factors=Factors])
end,
nl,
% Testing a larger number
println(factors(1361129467683753853853498429727072845823)),
nl.
%
% factors of N
%
factors(N) = Factors =>
Factors = [],
M = N,
while (M mod 2 == 0)
Factors := Factors ++ [2],
M := M div 2
end,
T = 3,
while (M > 1, T < 1+(sqrt(M)))
if M mod T == 0 then
[Divisors, NewM] = alldivisorsM(M, T),
Factors := Factors ++ Divisors,
M := NewM
end,
T := T + 2
end,
if M > 1 then Factors := Factors ++ [M] end.
alldivisorsM(N,Div) = [Divisors,M] =>
M = N,
Divisors = [],
while (M mod Div == 0)
Divisors := Divisors ++ [Div],
M := M div Div
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.
| #PowerShell | PowerShell |
function pop-count($n) {
(([Convert]::ToString($n, 2)).toCharArray() | where {$_ -eq '1'}).count
}
"pop_count 3^n: $(1..29 | foreach -Begin {$n = 1; (pop-count $n)} -Process {$n = 3*$n; (pop-count $n)} )"
"even pop_count: $($m = $n = 0; while($m -lt 30) {if(0 -eq ((pop-count $n)%2)) {$m += 1; $n}; $n += 1} )"
"odd pop_count: $($m = $n = 0; while($m -lt 30) {if(1 -eq ((pop-count $n)%2)) {$m += 1; $n}; $n += 1} )"
|
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.
| #Python | Python | def list_powerset(lst):
# the power set of the empty set has one element, the empty set
result = [[]]
for x in lst:
# for every additional element in our set
# the power set consists of the subsets that don't
# contain this element (just take the previous power set)
# plus the subsets that do contain the element (use list
# comprehension to add [x] onto everything in the
# previous power set)
result.extend([subset + [x] for subset in result])
return result
# the above function in one statement
def list_powerset2(lst):
return reduce(lambda result, x: result + [subset + [x] for subset in result],
lst, [[]])
def powerset(s):
return frozenset(map(frozenset, list_powerset(list(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
| #Java | Java | public static boolean prime(long a){
if(a == 2){
return true;
}else if(a <= 1 || a % 2 == 0){
return false;
}
long max = (long)Math.sqrt(a);
for(long n= 3; n <= max; n+= 2){
if(a % n == 0){ return false; }
}
return true;
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Swift | Swift | let ranges = [
(0.00..<0.06, 0.10),
(0.06..<0.11, 0.18),
(0.11..<0.16, 0.26),
(0.16..<0.21, 0.32),
(0.21..<0.26, 0.38),
(0.26..<0.31, 0.44),
(0.31..<0.36, 0.50),
(0.36..<0.41, 0.54),
(0.41..<0.46, 0.58),
(0.46..<0.51, 0.62),
(0.51..<0.56, 0.66),
(0.56..<0.61, 0.70),
(0.61..<0.66, 0.74),
(0.66..<0.71, 0.78),
(0.71..<0.76, 0.82),
(0.76..<0.81, 0.86),
(0.81..<0.86, 0.90),
(0.86..<0.91, 0.94),
(0.91..<0.96, 0.98),
(0.96..<1.01, 1.00)
]
func adjustDouble(_ val: Double, accordingTo ranges: [(Range<Double>, Double)]) -> Double? {
return ranges.first(where: { $0.0.contains(val) })?.1
}
for val in stride(from: 0.0, through: 1, by: 0.01) {
let strFmt = { String(format: "%.2f", $0) }
print("\(strFmt(val)) -> \(strFmt(adjustDouble(val, accordingTo: ranges) ?? val))")
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Tcl | Tcl | # Used once to turn the table into a "nice" form
proc parseTable table {
set map {}
set LINE_RE {^ *>= *([0-9.]+) *< *([0-9.]+) *:= *([0-9.]+) *$}
foreach line [split $table \n] {
if {[string trim $line] eq ""} continue
if {[regexp $LINE_RE $line -> min max target]} {
lappend map $min $max $target
} else {
error "invalid table format: $line"
}
}
return $map
}
# How to apply the "nice" table to a particular value
proc priceFraction {map value} {
foreach {minimum maximum target} $map {
if {$value >= $minimum && $value < $maximum} {return $target}
}
# Failed to map; return the input
return $value
} |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #XPL0 | XPL0 | func PropDiv(N, Show); \Count and optionally show proper divisors of N
int N, Show, D, C;
[C:= 0;
if N > 1 then
[D:= 1;
repeat if rem(N/D) = 0 then
[C:= C+1;
if Show then
[if D > 1 then ChOut(0, ^ );
IntOut(0, D);
];
];
D:= D+1;
until D >= N;
];
return C;
];
int N, SN, Cnt, Max;
[for N:= 1 to 10 do
[ChOut(0, ^[); PropDiv(N, true); ChOut(0, ^]);
ChOut(0, ^ );
];
CrLf(0);
Max:= 0;
for N:= 1 to 20000 do
[Cnt:= PropDiv(N, false);
if Cnt > Max then
[Max:= Cnt; SN:= N];
];
IntOut(0, SN); ChOut(0, ^ ); IntOut(0, Max); CrLf(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
| #PicoLisp | PicoLisp | (de factor (N)
(make
(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N))
(while (>= M D)
(if (=0 (% N D))
(setq M (sqrt (setq N (/ N (link D)))))
(inc 'D (pop 'L)) ) )
(link N) ) ) )
(factor 1361129467683753853853498429727072845823) |
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.
| #PureBasic | PureBasic | Procedure.i PopCount(n.i) : ProcedureReturn CountString(Bin(Pow(3,n)),"1") : EndProcedure
Procedure PutR(v.i) : Print(RSet(Str(v),3)) : EndProcedure
If OpenConsole()
NewList ne() : NewList no()
i=0
While ListSize(ne())+ListSize(no())<60
If CountString(Bin(i),"1")%2=0 : AddElement(ne()) : ne()=i
Else : AddElement(no()) : no()=i : EndIf
i+1
Wend
Print("3^i [i=0..29]") : For i=0 To 29 : PutR(PopCount(i)) : Next : PrintN("")
Print("Evil numbers ") : ForEach ne() : PutR(ne()) : Next : PrintN("")
Print("Odious numb..") : ForEach no() : PutR(no()) : Next : Input()
EndIf |
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.
| #Qi | Qi |
(define powerset
[] -> [[]]
[A|As] -> (append (map (cons A) (powerset As))
(powerset As)))
|
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
| #JavaScript | JavaScript | function isPrime(n) {
if (n == 2 || n == 3 || n == 5 || n == 7) {
return true;
} else if ((n < 2) || (n % 2 == 0)) {
return false;
} else {
for (var i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #uBasic.2F4tH | uBasic/4tH | For i = 0 To 100 Step 5
Print Using "+?.##"; i, Using "+?.##"; FUNC(_Normalize (FUNC(_Classify (i))))
Next
End
_Normalize ' normalize the price
Param (1) ' class
Local (4) ' accumulator, increment, switch and iterator
b@ = 0 : c@ = 10 : d@ = 2 ' setup accumulator, increment and switch
For e@ = 0 to a@ ' from zero to class
If And(e@ + 1, d@) Then d@ = And(d@ + d@, 15) : c@ = c@ - 2
b@ = b@ + c@ ' switch increment if needed
Next ' accumulate price
Return (Min(b@, 100)) ' clip top of price in accumulator
' calculate class
_Classify Param (1) : Return ((a@ - (a@>0)) / 5) |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #zkl | zkl | fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) } |
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
| #PL.2FI | PL/I |
test: procedure options (main, reorder);
declare (n, i) fixed binary (31);
get list (n);
put edit ( n, '[' ) (x(1), a);
restart:
if is_prime(n) then
do;
put edit (trim(n), ']' ) (x(1), a);
stop;
end;
do i = n/2 to 2 by -1;
if is_prime(i) then
if (mod(n, i) = 0) then
do;
put edit ( trim(i) ) (x(1), a);
n = n / i;
go to restart;
end;
end;
put edit ( ' ]' ) (a);
is_prime: procedure (n) options (reorder) returns (bit(1));
declare n fixed binary (31);
declare i fixed binary (31);
if n < 2 then return ('0'b);
if n = 2 then return ('1'b);
if mod(n, 2) = 0 then return ('0'b);
do i = 3 to sqrt(n) by 2;
if mod(n, i) = 0 then return ('0'b);
end;
return ('1'b);
end is_prime;
end test;
|
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.
| #Python | Python | >>> def popcount(n): return bin(n).count("1")
...
>>> [popcount(3**i) for i in range(30)]
[1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25]
>>> evil, odious, i = [], [], 0
>>> while len(evil) < 30 or len(odious) < 30:
... p = popcount(i)
... if p % 2: odious.append(i)
... else: evil.append(i)
... i += 1
...
>>> evil[:30]
[0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58]
>>> odious[:30]
[1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59]
>>> |
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.
| #Quackery | Quackery | [ stack ] is (ps).stack
[ stack ] is (ps).items
[ stack ] is (ps).result
[ 1 - (ps).items put
0 (ps).stack put
[] (ps).result put
[ (ps).result take
(ps).stack behead
drop nested join
(ps).result put
(ps).stack take
dup (ps).items share
= iff
[ drop
(ps).stack size 1 > iff
[ 1 (ps).stack tally ] ]
else
[ dup (ps).stack put
1+ (ps).stack put ]
(ps).stack size 1 = until ]
(ps).items release
(ps).result take ] is (ps) ( n --> )
[ dup size dip
[ witheach
[ over swap peek swap ] ]
nip pack ] is arrange ( [ [ --> [ )
[ dup [] = iff
nested done
dup size (ps)
' [ [ ] ] swap join
[] unrot witheach
[ dip dup arrange
nested
rot swap join swap ]
drop ] is powerset ( [ --> [ )
' [ [ 1 2 3 4 ] [ ] [ [ ] ] ]
witheach
[ say "The powerset of "
dup echo cr
powerset witheach [ echo cr ]
cr ] |
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.
| #R | R | for each element in the set:
for each subset constructed so far:
new subset = (subset + element)
|
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
| #Joy | Joy | DEFINE prime ==
2
[ [dup * >] nullary [rem 0 >] dip and ]
[ succ ]
while
dup * < . |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Ursala | Ursala | #import flo
le = <0.06,.11,.16,.21,.26,.31,.36,.41,.46,.51,.56,.61,.66,.71,.76,.81,.86,.91,.96,1.01>
out = <0.10,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.90,.94,.98,1.>
price_fraction = fleq@rlPlX*|rhr\~&p(le,out) |
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
| #PowerShell | PowerShell |
function eratosthenes ($n) {
if($n -gt 1){
$prime = @(1..($n+1) | foreach{$true})
$prime[1] = $false
$m = [Math]::Floor([Math]::Sqrt($n))
function multiple($i) {
for($j = $i*$i; $j -le $n; $j += $i) {
$prime[$j] = $false
}
}
multiple 2
for($i = 3; $i -le $m; $i += 2) {
if($prime[$i]) {multiple $i}
}
1..$n | where{$prime[$_]}
} else {
Write-Error "$n is not greater than 1"
}
}
function prime-decomposition ($n) {
$array = eratosthenes $n
$prime = @()
foreach($p in $array) {
while($n%$p -eq 0) {
$n /= $p
$prime += @($p)
}
}
$prime
}
"$(prime-decomposition 12)"
"$(prime-decomposition 100)"
|
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.
| #Quackery | Quackery | [ 0 swap
[ dup while
dup 1 &
rot + swap
1 >>
again ]
drop ] is popcount ( n --> n )
[ 1 & ] is odd ( n --> b )
[ odd not ] is even ( n --> b )
[ ]'[ temp put 0
[ over while
[ dup popcount
temp share do
if [ dup echo sp
dip [ 1 - ] ]
1+ ]
again ]
2drop temp release ] is echopopwith ( n --> )
say "Population counts of the first thirty powers of 3." cr
30 times
[ 3 i^ ** popcount echo sp ] cr
cr
say "The first thirty evil numbers." cr
30 echopopwith even cr
cr
say "The first thirty odious numbers." cr
30 echopopwith odd cr |
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.
| #Racket | Racket |
;;; Direct translation of 'functional' ruby method
(define (powerset s)
(for/fold ([outer-set (set(set))]) ([element s])
(set-union outer-set
(list->set (set-map outer-set
(λ(inner-set) (set-add inner-set element)))))))
|
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.
| #Raku | Raku | sub powerset(Set $s) { $s.combinations.map(*.Set).Set }
say powerset set <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
| #jq | jq | if . == 2 then true
else 2 < . and . % 2 == 1 and
. as $in
| (($in + 1) | sqrt) as $m
| (((($m - 1) / 2) | floor) + 1) as $max
| all( range(1; $max) ; $in % ((2 * .) + 1) > 0 )
end;
|
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #VBA | VBA |
Option Explicit
Sub Main()
Dim test, i As Long
test = Array(0.34, 0.070145, 0.06, 0.05, 0.50214, 0.56, 1#, 0.99, 0#, 0.7388727)
For i = 0 To UBound(test)
Debug.Print test(i) & " := " & Price_Fraction(CSng(test(i)))
Next i
End Sub
Private Function Price_Fraction(n As Single) As Single
Dim Vin, Vout, i As Long
Vin = Array(0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01)
Vout = Array(0.1, 0.18, 0.26, 0.32, 0.38, 0.44, 0.5, 0.54, 0.58, 0.62, 0.66, 0.7, 0.74, 0.78, 0.82, 0.86, 0.9, 0.94, 0.98, 1#)
For i = 0 To UBound(Vin)
If n < Vin(i) Then Price_Fraction = Vout(i): Exit For
Next i
End Function |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #VBScript | VBScript |
Function pf(p)
If p < 0.06 Then
pf = 0.10
ElseIf p < 0.11 Then
pf = 0.18
ElseIf p < 0.16 Then
pf = 0.26
ElseIf p < 0.21 Then
pf = 0.32
ElseIf p < 0.26 Then
pf = 0.38
ElseIf p < 0.31 Then
pf = 0.44
ElseIf p < 0.36 Then
pf = 0.50
ElseIf p < 0.41 Then
pf = 0.54
ElseIf p < 0.46 Then
pf = 0.58
ElseIf p < 0.51 Then
pf = 0.62
ElseIf p < 0.56 Then
pf = 0.66
ElseIf p < 0.61 Then
pf = 0.70
ElseIf p < 0.66 Then
pf = 0.74
ElseIf p < 0.71 Then
pf = 0.78
ElseIf p < 0.76 Then
pf = 0.82
ElseIf p < 0.81 Then
pf = 0.86
ElseIf p < 0.86 Then
pf = 0.90
ElseIf p < 0.91 Then
pf = 0.94
ElseIf p < 0.96 Then
pf = 0.98
Else
pf = 1.00
End If
End Function
WScript.Echo pf(0.7388727)
WScript.Echo pf(0.8593103)
WScript.Echo pf(0.826687)
WScript.Echo pf(0.3444635)
|
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
| #Prolog | Prolog | prime_decomp(N, L) :-
SN is sqrt(N),
prime_decomp_1(N, SN, 2, [], L).
prime_decomp_1(1, _, _, L, L) :- !.
% Special case for 2, increment 1
prime_decomp_1(N, SN, D, L, LF) :-
( 0 is N mod D ->
Q is N / D,
SQ is sqrt(Q),
prime_decomp_1(Q, SQ, D, [D |L], LF)
;
D1 is D+1,
( D1 > SN ->
LF = [N |L]
;
prime_decomp_2(N, SN, D1, L, LF)
)
).
% General case, increment 2
prime_decomp_2(1, _, _, L, L) :- !.
prime_decomp_2(N, SN, D, L, LF) :-
( 0 is N mod D ->
Q is N / D,
SQ is sqrt(Q),
prime_decomp_2(Q, SQ, D, [D |L], LF);
D1 is D+2,
( D1 > SN ->
LF = [N |L]
;
prime_decomp_2(N, SN, D1, L, LF)
)
). |
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.
| #R | R | library(bit64)
popCount <- function(x) sum(as.numeric(strsplit(as.bitstring(as.integer64(x)), "")[[1]]))
finder <- function()
{
odious <- evil <- integer(0)
x <- odiousLength <- evilLength <- 0
while(evilLength + odiousLength != 60)#We could be smarter, but this condition suffices.
{
if(popCount(x) %% 2 == 0) evil[evilLength + 1] <- x else odious[odiousLength + 1] <- x
x <- x + 1
evilLength <- length(evil)
odiousLength <- length(odious)
}
cat("The pop count of the 1st 30 powers of 3 are:", sapply(3^(0:29), popCount), "\n")
cat("The first 30 evil numbers are:", evil, "\n")
cat("The first 30 odious numbers are:", odious)
}
finder() |
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.
| #Rascal | Rascal |
import Set;
public set[set[&T]] PowerSet(set[&T] s) = power(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
| #Julia | Julia | function isprime_trialdivision{T<:Integer}(n::T)
1 < n || return false
n != 2 || return true
isodd(n) || return false
for i in 3:isqrt(n)
n%i != 0 || return false
end
return true
end
n = 100
a = filter(isprime_trialdivision, [1:n])
if all(a .== primes(n))
println("The primes <= ", n, " are:\n ", a)
else
println("The function does not accurately calculate primes.")
end |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Wren | Wren | import "/fmt" for Fmt
var rescale = Fn.new { |v|
return (v < 0.06) ? 0.10 :
(v < 0.11) ? 0.18 :
(v < 0.16) ? 0.26 :
(v < 0.21) ? 0.32 :
(v < 0.26) ? 0.38 :
(v < 0.31) ? 0.44 :
(v < 0.36) ? 0.50 :
(v < 0.41) ? 0.54 :
(v < 0.46) ? 0.58 :
(v < 0.51) ? 0.62 :
(v < 0.56) ? 0.66 :
(v < 0.61) ? 0.70 :
(v < 0.66) ? 0.74 :
(v < 0.71) ? 0.78 :
(v < 0.76) ? 0.82 :
(v < 0.81) ? 0.86 :
(v < 0.86) ? 0.90 :
(v < 0.91) ? 0.94 :
(v < 0.96) ? 0.98 : 1.00
}
var tests = [0.49, 0.79, 1.00, 0.83, 0.99, 0.23, 0.12, 0.28, 0.72, 0.37, 0.95, 0.51, 0.43, 0.52, 0.84, 0.89, 0.48, 0.48, 0.30, 0.01]
for (test in tests) {
Fmt.print("$4.2f -> $4.2f", test, rescale.call(test))
} |
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
| #Pure | Pure | factor n = factor 2 n with
factor k n = k : factor k (n div k) if n mod k == 0;
= if n>1 then [n] else [] if k*k>n;
= factor (k+1) n if k==2;
= factor (k+2) n otherwise;
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.
| #Racket | Racket | #lang racket
;; Positive version from "popcount_4" in:
;; https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
;; negative version follows R6RS definition documented in:
;; http://docs.racket-lang.org/r6rs/r6rs-lib-std/r6rs-lib-Z-H-12.html?q=bitwise-bit#node_idx_1074
(define (population-count n)
(if (negative? n)
(bitwise-not (population-count (bitwise-not n)))
(let inr ((x n) (rv 0))
(if (= x 0) rv (inr (bitwise-and x (sub1 x)) (add1 rv))))))
(define (evil? x)
(and (not (negative? x))
(even? (population-count x))))
(define (odious? x)
(and (positive? x)
(odd? (population-count x))))
(define tasks
(list
"display the pop count of the 1st thirty powers of 3 (3^0, 3^1, 3^2, 3^3, 3^4, ...)."
(for/list ((i (in-range 30))) (population-count (expt 3 i)))
"display the 1st thirty evil numbers."
(for/list ((_ (in-range 30)) (e (sequence-filter evil? (in-naturals)))) e)
"display the 1st thirty odious numbers."
(for/list ((_ (in-range 30)) (o (sequence-filter odious? (in-naturals)))) o)))
(for-each displayln tasks)
(module+ test
(require rackunit)
(check-equal?
(for/list ((p (sequence-map population-count (in-range 16)))) p)
'(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4))
(check-true (evil? 0) "0 has just *got* to be evil")
(check-true (evil? #b011011011) "six bits... truly evil")
(check-false (evil? #b1011011011) "seven bits, that's odd!")
(check-true (odious? 1) "the least odious number")
(check-true (odious? #b1011011011) "seven (which is odd) bits")
(check-false (odious? #b011011011) "six bits... is evil")) |
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.
| #REXX | REXX | /*REXX program displays a power set; items may be anything (but can't have blanks).*/
parse arg S /*allow the user specify optional set. */
if S='' then S= 'one two three four' /*Not specified? Then use the default.*/
@= '{}' /*start process with a null power set. */
N= words(S); do chunk=1 for N /*traipse through the items in the set.*/
@=@ combN(N, chunk) /*take N items, a CHUNK at a time. */
end /*chunk*/
w= length(2**N) /*the number of items in the power set.*/
do k=1 for words(@) /* [↓] show combinations, 1 per line.*/
say right(k, w) word(@, k) /*display a single combination to term.*/
end /*k*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
combN: procedure expose S; parse arg x,y; base= x + 1; bbase= base - y
!.= 0
do p=1 for y; !.p= p
end /*p*/
$= /* [↓] build powerset*/
do j=1; L=
do d=1 for y; L= L','word(S, !.d)
end /*d*/
$= $ '{'strip(L, "L", ',')"}"; !.y= !.y + 1
if !.y==base then if .combU(y - 1) then leave
end /*j*/
return strip($) /*return with a partial power set chunk*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
.combU: procedure expose !. y bbase; parse arg d; if d==0 then return 1
p= !.d
do u=d to y; !.u= p + 1; if !.u==bbase+u then return .combU(u-1)
p= !.u /* ↑ */
end /*u*/ /*recurse──►───┘ */
return 0 |
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
| #K | K | isprime:{(x>1)&&/x!'2_!1+_sqrt x}
&isprime'!100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func real Price(V); \Convert to standard value
real V;
[V:= V + 0.001; \avoids possible rounding error i.e. 0.059999999
case of
V < 0.06: ret 0.10;
V < 0.11: ret 0.18;
V < 0.16: ret 0.26;
V < 0.21: ret 0.32;
V < 0.26: ret 0.38;
V < 0.31: ret 0.44;
V < 0.36: ret 0.50;
V < 0.41: ret 0.54;
V < 0.46: ret 0.58;
V < 0.51: ret 0.62;
V < 0.56: ret 0.66;
V < 0.61: ret 0.70;
V < 0.66: ret 0.74;
V < 0.71: ret 0.78;
V < 0.76: ret 0.82;
V < 0.81: ret 0.86;
V < 0.86: ret 0.90;
V < 0.91: ret 0.94;
V < 0.96: ret 0.98
other ret 1.00;
];
[Format(1,2);
RlOut(0, Price(0.0599)); CrLf(0);
RlOut(0, Price(0.10)); CrLf(0);
RlOut(0, Price(1.0)); CrLf(0);
] |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #zkl | zkl | fcn convert(price){ // float --> float
// < -->, increments of 0.05 but tables are easier to update
var vert=T( T(0.06, 0.10), T(0.11, 0.18), T(0.16, 0.26),
T(0.21, 0.32), T(0.26, 0.38), T(0.31, 0.44),
T(0.36, 0.50), T(0.41, 0.54), T(0.46, 0.58),
T(0.51, 0.62), T(0.56, 0.66), T(0.61, 0.70),
T(0.66, 0.74), T(0.71, 0.78), T(0.76, 0.82),
T(0.81, 0.86), T(0.86, 0.90), T(0.91, 0.94),
T(0.96, 0.98), T(1.01, 1.00), );
vert.filter1('wrap([(a,_)]){ price<a })[1]
} |
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
| #PureBasic | PureBasic |
CompilerIf #PB_Compiler_Debugger
CompilerError "Turn off the debugger if you want reasonable speed in this example."
CompilerEndIf
Define.q
Procedure Factor(Number, List Factors())
Protected I = 3
While Number % 2 = 0
AddElement(Factors())
Factors() = 2
Number / 2
Wend
Protected Max = Number
While I <= Max And Number > 1
While Number % I = 0
AddElement(Factors())
Factors() = I
Number/I
Wend
I + 2
Wend
EndProcedure
Number = 9007199254740991
NewList Factors()
time = ElapsedMilliseconds()
Factor(Number, Factors())
time = ElapsedMilliseconds()-time
S.s = "Factored " + Str(Number) + " in " + StrD(time/1000, 2) + " seconds."
ForEach Factors()
S + #CRLF$ + Str(Factors())
Next
MessageRequester("", S) |
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.
| #Raku | Raku | sub population-count(Int $n where * >= 0) { [+] $n.base(2).comb }
say map &population-count, 3 «**« ^30;
say "Evil: ", (grep { population-count($_) %% 2 }, 0 .. *)[^30];
say "Odious: ", (grep { population-count($_) % 2 }, 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.
| #Ring | Ring |
# Project : Power set
list = ["1", "2", "3", "4"]
see powerset(list)
func powerset(list)
s = "{"
for i = 1 to (2 << len(list)) - 1 step 2
s = s + "{"
for j = 1 to len(list)
if i & (1 << j)
s = s + list[j] + ","
ok
next
if right(s,1) = ","
s = left(s,len(s)-1)
ok
s = s + "},"
next
return left(s,len(s)-1) + "}"
|
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.
| #Ruby | Ruby | # Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
# See the link if you want a shorter version.
# This was intended to show the reader how the method works.
class Array
# Adds a power_set method to every array, i.e.: [1, 2].power_set
def power_set
# Injects into a blank array of arrays.
# acc is what we're injecting into
# you is each element of the array
inject([[]]) do |acc, you|
ret = [] # Set up a new array to add into
acc.each do |i| # For each array in the injected array,
ret << i # Add itself into the new array
ret << i + [you] # Merge the array with a new array of the current element
end
ret # Return the array we're looking at to inject more.
end
end
# A more functional and even clearer variant.
def func_power_set
inject([[]]) { |ps,item| # for each item in the Array
ps + # take the powerset up to now and add
ps.map { |e| e + [item] } # it again, with the item appended to each element
}
end
end
#A direct translation of the "power array" version above
require 'set'
class Set
def powerset
inject(Set[Set[]]) do |ps, item|
ps.union ps.map {|e| e.union (Set.new [item])}
end
end
end
p [1,2,3,4].power_set
p %w(one two three).func_power_set
p Set[1,2,3].powerset |
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
| #Kotlin | Kotlin | // version 1.1.2
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
val limit = Math.sqrt(n.toDouble()).toInt()
return (3..limit step 2).none { n % it == 0 }
}
fun main(args: Array<String>) {
// test by printing all primes below 100 say
(2..99).filter { isPrime(it) }.forEach { print("$it ") }
} |
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
| #Python | Python | from __future__ import print_function
import sys
from itertools import islice, cycle, count
try:
from itertools import compress
except ImportError:
def compress(data, selectors):
"""compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"""
return (d for d, s in zip(data, selectors) if s)
def is_prime(n):
return list(zip((True, False), decompose(n)))[-1][0]
class IsPrimeCached(dict):
def __missing__(self, n):
r = is_prime(n)
self[n] = r
return r
is_prime_cached = IsPrimeCached()
def croft():
"""Yield prime integers using the Croft Spiral sieve.
This is a variant of wheel factorisation modulo 30.
"""
# Copied from:
# https://code.google.com/p/pyprimes/source/browse/src/pyprimes.py
# Implementation is based on erat3 from here:
# http://stackoverflow.com/q/2211990
# and this website:
# http://www.primesdemystified.com/
# Memory usage increases roughly linearly with the number of primes seen.
# dict ``roots`` stores an entry x:p for every prime p.
for p in (2, 3, 5):
yield p
roots = {9: 3, 25: 5} # Map d**2 -> d.
primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29))
selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)
for q in compress(
# Iterate over prime candidates 7, 9, 11, 13, ...
islice(count(7), 0, None, 2),
# Mask out those that can't possibly be prime.
cycle(selectors)
):
# Using dict membership testing instead of pop gives a
# 5-10% speedup over the first three million primes.
if q in roots:
p = roots[q]
del roots[q]
x = q + 2*p
while x in roots or (x % 30) not in primeroots:
x += 2*p
roots[x] = p
else:
roots[q*q] = q
yield q
primes = croft
def decompose(n):
for p in primes():
if p*p > n: break
while n % p == 0:
yield p
n //=p
if n > 1:
yield n
if __name__ == '__main__':
# Example: calculate factors of Mersenne numbers to M59 #
import time
for m in primes():
p = 2 ** m - 1
print( "2**{0:d}-1 = {1:d}, with factors:".format(m, p) )
start = time.time()
for factor in decompose(p):
print(factor, end=' ')
sys.stdout.flush()
print( "=> {0:.2f}s".format( time.time()-start ) )
if m >= 59:
break |
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.
| #REXX | REXX | /*REXX program counts the number of "one" bits in the binary version of a decimal number*/
/*─────────────────── and also generates a specific number of EVIL and ODIOUS numbers.*/
parse arg N B . /*get optional arguments from the C.L. */
if N=='' | N=="," then N= 30 /*N not specified? Then use default. */
if B=='' | B=="," then B= 3 /*B " " " " " */
numeric digits 2000 /*be able to handle gihugeic numbers.*/
numeric digits max(20, length(B**N) ) /*whittle the precision down to size.*/
$= /* [↑] a little calculation for sizing*/
do j=0 for N; $= $ popCount(B**j) /*generate N popCounts for some powers.*/
end /*j*/ /* [↑] append popCount to the $ list. */
/* [↓] display popCounts of "3" powers*/
call showList 'popCounts of the powers of' B /*display the list with a header/title.*/
do j=0 until #>=N /*generate N evil numbers. */
if popCount(j) // 2 then iterate /*if odd population count, skip it. */
#= # + 1; $= $ j /*bump evil # count; add it to $ list.*/
end /*j*/ /* [↑] build a list of evil numbers. */
/* [↓] display the evil number list. */
call showList 'evil numbers' /*display the $ list with a header. */
do j=0 until #>=N /*generate N odious numbers. */
if popCount(j) // 2 ==0 then iterate /*if even population count, then skip. */
#= # + 1; $=$ j /*bump odious # count; add to $ list. */
end /*j*/ /* [↑] build a list of odious numbers.*/
/* [↓] display the odious number list.*/
call showList 'odious numbers' /*display the $ list with a header. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
d2b: return word( strip( x2b( d2x( arg(1) ) ), 'L', 0) 0, 1) /*dec ──► bin.*/
popCount: return length( space( translate( d2b(arg(1) ), , 0), 0) ) /*count ones. */
showList: say; say 'The 1st' N arg(1)":"; say strip($); #= 0; $=; return |
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.
| #Rust | Rust | use std::collections::BTreeSet;
fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> {
if set.is_empty() {
let mut powerset = BTreeSet::new();
powerset.insert(set);
return powerset;
}
// Access the first value. This could be replaced with `set.pop_first().unwrap()`
// But this is an unstable feature
let entry = set.iter().nth(0).unwrap().clone();
set.remove(&entry);
let mut powerset = powerset(set);
for mut set in powerset.clone().into_iter() {
set.insert(entry.clone());
powerset.insert(set);
}
powerset
}
fn main() {
let set = (1..5).collect();
let set = powerset(set);
println!("{:?}", set);
let set = ["a", "b", "c", "d"].iter().collect();
let set = powerset(set);
println!("{:?}", set);
}
|
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.
| #SAS | SAS |
options mprint mlogic symbolgen source source2;
%macro SubSets (FieldCount = );
data _NULL_;
Fields = &FieldCount;
SubSets = 2**Fields;
call symput ("NumSubSets", SubSets);
run;
%put &NumSubSets;
data inital;
%do j = 1 %to &FieldCount;
F&j. = 1;
%end;
run;
data SubSets;
set inital;
RowCount =_n_;
call symput("SetCount",RowCount);
run;
%put SetCount ;
%do %while (&SetCount < &NumSubSets);
data loop;
%do j=1 %to &FieldCount;
if rand('GAUSSIAN') > rand('GAUSSIAN') then F&j. = 1;
%end;
data SubSets_ ;
set SubSets loop;
run;
proc sort data=SubSets_ nodupkey;
by F1 - F&FieldCount.;
run;
data Subsets;
set SubSets_;
RowCount =_n_;
run;
proc sql noprint;
select max(RowCount) into :SetCount
from SubSets;
quit;
run;
%end;
%Mend SubSets;
|
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
| #langur | langur | val .isPrime = f(.i) {
val .n = abs(.i)
if .n <= 2: return .n == 2
val .chkdiv = f(.n, .i) {
if .i x .i <= .n {
return .n ndiv .i and self(.n, .i+2)
}
return true
}
return .n ndiv 2 and .chkdiv(.n, 3)
}
writeln where .isPrime, series 100 |
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
| #Quackery | Quackery | [ [] swap
dup times
[ [ dup i^ 2 + /mod
0 = while
nip dip
[ i^ 2 + join ]
again ]
drop
dup 1 = if conclude ]
drop ] is primefactors ( n --> [ )
1047552 primefactors echo |
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.
| #Ring | Ring | # Project : Population count
odds = []
evens = []
pows = []
for n = 0 to 59
if n < 30 add(pows, onesCount(pow(3, n))) ok
num = onesCount(n)
if num & 1 = 0 add(evens, n) else add(odds, n) ok
next
showOne("3^x:", pows)
showOne("Evil numbers:", evens)
showOne("Odious numbers:", odds)
func onesCount(b)
c = 0 m = 50
while b > 0
p = pow(2, m)
if b >= p b -= p c++ ok
m--
end return c
func arrayToStr(ary)
res = "[" s = ", "
for n = 1 to len(ary)
if ary[n] < 10 res += " " ok
if n = len(ary) s = "]" ok
res += "" + ary[n] + s
next return res
func showOne(title, ary)
? title
? arrayToStr(ary) + nl |
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.
| #Scala | Scala | import scala.compat.Platform.currentTime
object Powerset extends App {
def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)}
assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4),
Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
} |
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
| #Liberty_BASIC | Liberty BASIC | print "Rosetta Code - Primality by trial division"
print
[start]
input "Enter an integer: "; x
if x=0 then print "Program complete.": end
if isPrime(x) then print x; " is prime" else print x; " is not prime"
goto [start]
function isPrime(p)
p=int(abs(p))
if p=2 or then isPrime=1: exit function 'prime
if p=0 or p=1 or (p mod 2)=0 then exit function 'not prime
for i=3 to sqr(p) step 2
if (p mod i)=0 then exit function 'not prime
next i
isPrime=1
end function |
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
| #R | R | findfactors <- function(num) {
x <- NULL
firstprime<- 2; secondprime <- 3; everyprime <- num
while( everyprime != 1 ) {
while( everyprime%%firstprime == 0 ) {
x <- c(x, firstprime)
everyprime <- floor(everyprime/ firstprime)
}
firstprime <- secondprime
secondprime <- secondprime + 2
}
x
}
print(findfactors(1027*4)) |
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.