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/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Scheme | Scheme | (define ranks
(quote (ace 2 3 4 5 6 7 8 9 10 jack queen king)))
(define suits
(quote (clubs diamonds hearts spades)))
(define new-deck
(apply append
(map (lambda (suit)
(map (lambda (rank)
(cons rank suit))
ranks))
suits)))
(define (shuffle deck)
(define (remove-card deck index)
(if (zero? index)
(cdr deck)
(cons (car deck) (remove-card (cdr deck) (- index 1)))))
(if (null? deck)
(list)
(let ((index (random (length deck))))
(cons (list-ref deck index) (shuffle (remove-card deck index))))))
(define-syntax deal!
(syntax-rules ()
((deal! deck hand)
(begin (set! hand (cons (car deck) hand)) (set! deck (cdr deck)))))) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Rust | Rust | use num_bigint::BigInt;
fn main() {
calc_pi();
}
fn calc_pi() {
let mut q = BigInt::from(1);
let mut r = BigInt::from(0);
let mut t = BigInt::from(1);
let mut k = BigInt::from(1);
let mut n = BigInt::from(3);
let mut l = BigInt::from(3);
let mut first = true;
loop {
if &q * 4 + &r - &t < &n * &t {
print!("{}", n);
if first {
print!(".");
first = false;
}
let nr = (&r - &n * &t) * 10;
n = (&q * 3 + &r) * 10 / &t - &n * 10;
q *= 10;
r = nr;
} else {
let nr = (&q * 2 + &r) * &l;
let nn = (&q * &k * 7 + 2 + &r * &l) / (&t * &l);
q *= &k;
t *= &l;
l += 2;
k += 1;
n = nn;
r = nr;
}
}
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #MATLAB | MATLAB | function perf = isPerfect(n)
total = 0;
for k = 1:n-1
if ~mod(n, k)
total = total+k;
end
end
perf = total == n;
end |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Lambdatalk | Lambdatalk |
{def inject
{lambda {:x :a}
{if {A.empty? :a}
then {A.new {A.new :x}}
else {let { {:c {{lambda {:a :b} {A.cons {A.first :a} :b}} :a}}
{:d {inject :x {A.rest :a}}}
{:e {A.cons :x :a}}
} {A.cons :e {A.map :c :d}}}}}}
-> inject
{def permut
{lambda {:a}
{if {A.empty? :a}
then {A.new :a}
else {let { {:c {{lambda {:a :b} {inject {A.first :a} :b}} :a}}
{:d {permut {A.rest :a}}}
} {A.reduce A.concat {A.map :c :d}}}}}}
-> permut
{permut {A.new 1 2 3}}
-> [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
{permut {A.new 1 2 3 4}}
->
[[1,2,3,4],[2,1,3,4],[2,3,1,4],[2,3,4,1],[1,3,2,4],[3,1,2,4],[3,2,1,4],[3,2,4,1],[1,3,4,2],[3,1,4,2],[3,4,1,2],[3,4,2,1],[1,2,4,3],[2,1,4,3],[2,4,1,3],[2,4,3,1],[1,4,2,3],[4,1,2,3],[4,2,1,3],[4,2,3,1],[1,4,3,2],[4,1,3,2],[4,3,1,2],[4,3,2,1]]
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #SenseTalk | SenseTalk | properties
cards: []
end properties
to initialize
set pips to (2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace")
set suits to ("Clubs", "Spades", "Diamonds", "Hearts")
repeat for each suit in suits
repeat for each pip in pips
set card to pip && "of" && suit
insert card into my cards
end repeat
end repeat
put "New deck created, number of cards in deck:" && the number of items in my cards
end initialize
to shuffle
sort my cards by random of a million
put "Deck shuffled"
end shuffle
to deal
pull from my cards into card
put "Card dealt:" && card
put "Cards in deck remaining:" && the number of items in my cards
end deal
to handle asText
return my cards joined by return
end asText |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Scala | Scala | object Pi {
class PiIterator extends Iterable[BigInt] {
var r: BigInt = 0
var q, t, k: BigInt = 1
var n, l: BigInt = 3
def iterator: Iterator[BigInt] = new Iterator[BigInt] {
def hasNext = true
def next(): BigInt = {
while ((4 * q + r - t) >= (n * t)) {
val nr = (2 * q + r) * l
val nn = (q * (7 * k) + 2 + (r * l)) / (t * l)
q = q * k
t = t * l
l = l + 2
k = k + 1
n = nn
r = nr
}
val ret = n
val nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) / t) - (10 * n)
q = q * 10
r = nr
ret
}
}
}
def main(args: Array[String]): Unit = {
val it = new PiIterator
println("" + (it.head) + "." + (it.take(300).mkString))
}
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Maxima | Maxima | ".."(a, b) := makelist(i, i, a, b)$
infix("..")$
perfectp(n) := is(divsum(n) = 2*n)$
sublist(1 .. 10000, perfectp);
/* [6, 28, 496, 8128] */ |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #MAXScript | MAXScript | fn isPerfect n =
(
local sum = 0
for i in 1 to (n-1) do
(
if mod n i == 0 then
(
sum += i
)
)
sum == n
) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #langur | langur | val .factorial = f if(.x < 2: 1; .x x self(.x - 1))
val .permute = f(.arr) {
if not isArray(.arr): throw "expected array"
val .limit = 10
if len(.arr) > .limit: throw $"permutation limit exceeded (currently \.limit;)"
var .elements = .arr
var .ordinals = pseries len .elements
val .n = len(.ordinals)
var .i, .j
for[.p=[.arr]] of .factorial(len .arr)-1 {
.i = .n - 1
.j = .n
while .ordinals[.i] > .ordinals[.i+1] {
.i -= 1
}
while .ordinals[.j] < .ordinals[.i] {
.j -= 1
}
.ordinals[.i], .ordinals[.j] = .ordinals[.j], .ordinals[.i]
.elements[.i], .elements[.j] = .elements[.j], .elements[.i]
.i += 1
for .j = .n; .i < .j ; .i, .j = .i+1, .j-1 {
.ordinals[.i], .ordinals[.j] = .ordinals[.j], .ordinals[.i]
.elements[.i], .elements[.j] = .elements[.j], .elements[.i]
}
.p = more .p, .elements
}
}
for .e in .permute([1, 3.14, 7]) {
writeln .e
} |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Sidef | Sidef | define Pip = <A 2 3 4 5 6 7 8 9 10 J Q K>;
define Suit = <♦ ♣ ♥ ♠>;
class Card(pip, suit) {
method to_s { pip + suit }
}
class Deck(cards=[]) {
method init {
cards = gather {
Pip.each { |p| Suit.each { |s| take(Card(p, s)) } }
}
}
method shuffle {
cards.shuffle!;
}
method deal { cards.shift };
method to_s { cards.join(" ") };
}
var d = Deck();
say "Deck: #{d}";
var top = d.deal;
say "Top card: #{top}";
d.shuffle;
say "Deck, shuffled: #{d}"; |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Scheme | Scheme |
(import (rnrs))
(define (calc-pi yield)
(let loop ((q 1) (r 0) (t 1) (k 1) (n 3) (l 3))
(if (< (- (+ (* 4 q) r) t) (* n t))
(begin
(yield n)
(loop (* q 10)
(* 10 (- r (* n t)))
t
k
(- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))
l))
(begin
(loop (* q k)
(* (+ (* 2 q) r) l)
(* t l)
(+ k 1)
(div (+ (* q (* 7 k)) 2 (* r l)) (* t l))
(+ l 2))))))
(let ((i 0))
(calc-pi
(lambda (d)
(display d)
(set! i (+ i 1))
(if (= 40 i)
(begin
(newline)
(set! i 0))))))
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Microsoft_Small_Basic | Microsoft Small Basic |
For n = 2 To 10000 Step 2
VerifyIfPerfect()
If isPerfect = 1 Then
TextWindow.WriteLine(n)
EndIf
EndFor
Sub VerifyIfPerfect
s = 1
sqrN = Math.SquareRoot(n)
If Math.Remainder(n, 2) = 0 Then
s = s + 2 + Math.Floor(n / 2)
EndIf
i = 3
while i <= sqrN - 1
If Math.Remainder(n, i) = 0 Then
s = s + i + Math.Floor(n / i)
EndIf
i = i + 1
EndWhile
If i * i = n Then
s = s + i
EndIf
If n = s Then
isPerfect = 1
Else
isPerfect = 0
EndIf
EndSub
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Modula-2 | Modula-2 |
MODULE PerfectNumbers;
FROM SWholeIO IMPORT
WriteCard;
FROM STextIO IMPORT
WriteLn;
FROM RealMath IMPORT
sqrt;
VAR
N: CARDINAL;
PROCEDURE IsPerfect(N: CARDINAL): BOOLEAN;
VAR
S, I: CARDINAL;
SqrtN: REAL;
BEGIN
S := 1;
SqrtN := sqrt(FLOAT(N));
IF N REM 2 = 0 THEN
S := S + 2 + N / 2;
END;
I := 3;
WHILE FLOAT(I) <= SqrtN - 1.0 DO
IF N REM I = 0 THEN
S := S + I + N / I;
END;
I := I + 1;
END;
IF I * I = N THEN
S := S + I;
END;
RETURN (N = S);
END IsPerfect;
BEGIN
FOR N := 2 TO 10000 BY 2 DO
IF IsPerfect(N) THEN
WriteCard(N, 5);
WriteLn;
END;
END;
END PerfectNumbers.
|
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #LFE | LFE |
(defun permute
(('())
'(()))
((l)
(lc ((<- x l)
(<- y (permute (-- l `(,x)))))
(cons x y))))
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Smalltalk | Smalltalk | Object subclass: #Card
instanceVariableNames: 'thePip theSuit'
classVariableNames: 'pips suits'
poolDictionaries: ''
category: nil !
!Card class methods!
initialize
suits ifNil: [ suits := 'clubs,hearts,spades,diamonds' subStrings: $, ].
pips ifNil: [ pips := '2,3,4,5,6,7,8,9,10,jack,queen,king,ace' subStrings: $, ]
!
new
| o |
o := super new.
^o
!
new: card
| o |
o := self new.
o initWithPip: (card at: 1) andSuit: (card at: 2).
^o
!!
!Card class methods !
pips
Card initialize.
^pips
!
suits
Card initialize.
^suits
!!
!Card methods!
initWithPip: aPip andSuit: aSuit
( (pips includes: aPip asLowercase) &
(suits includes: aSuit asLowercase) )
ifTrue: [
thePip := aPip copy.
theSuit := aSuit copy
] ifFalse: [ 'Unknown pip or suit' displayOn: stderr .
Character nl displayOn: stderr ].
^self
!
asString
^('(%1,%2)' % { thePip . theSuit })
!
display
self asString display
!
displayNl
self display.
Character nl display
!!
Object subclass: #Deck
instanceVariableNames: 'deck'
classVariableNames: ''
poolDictionaries: ''
category: nil !
!Deck class methods !
new
|d|
d := super new.
d init.
^d
!!
!Deck methods !
init
deck := OrderedCollection new.
Card suits do: [ :suit |
Card pips do: [ :pip |
deck add: (Card new: { pip . suit })
]
]
!
deck
^deck
!
shuffle
1 to: self deck size do: [ :i |
|r2 o|
r2 := Random between: 1 and: self deck size.
o := self deck at: i.
self deck at: i put: (self deck at: r2).
self deck at: r2 put: o
].
^self
!
display
self deck do: [ :card |
card displayNl
]
!
deal
^self deck removeFirst
!!
"create a deck, shuffle it, remove the first card and display it"
Deck new shuffle deal displayNl. |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const proc: main is func
local
var bigInteger: q is 1_;
var bigInteger: r is 0_;
var bigInteger: t is 1_;
var bigInteger: k is 1_;
var bigInteger: n is 3_;
var bigInteger: l is 3_;
var bigInteger: nn is 0_;
var bigInteger: nr is 0_;
var boolean: first is TRUE;
begin
while TRUE do
if 4_ * q + r - t < n * t then
write(n);
if first then
write(".");
first := FALSE;
end if;
nr := 10_ * (r - n * t);
n := 10_ * (3_ * q + r) div t - 10_ * n;
q *:= 10_;
r := nr;
flush(OUT);
else
nr := (2_ * q + r) * l;
nn := (q * (7_ * k + 2_) + r * l) div (t * l);
q *:= k;
t *:= l;
l +:= 2_;
incr(k);
n := nn;
r := nr;
end if;
end while;
end func; |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Nanoquery | Nanoquery | def perf(n)
sum = 0
for i in range(1, n - 1)
if (n % i) = 0
sum += i
end
end
return sum = n
end |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Nim | Nim | import math
proc isPerfect(n: int): bool =
var sum: int = 1
for d in 2 .. int(n.toFloat.sqrt):
if n mod d == 0:
inc sum, d
let q = n div d
if q != d: inc sum, q
result = n == sum
for n in 2..10_000:
if n.isPerfect:
echo n |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Liberty_BASIC | Liberty BASIC |
n=3
dim a(n+1) '+1 needed due to bug in LB that checks loop condition
' until (i=0) or (a(i)<a(i+1))
'before executing i=i-1 in loop body.
for i=1 to n: a(i)=i: next
do
for i=1 to n: print a(i);: next: print
i=n
do
i=i-1
loop until (i=0) or (a(i)<a(i+1))
j=i+1
k=n
while j<k
'swap a(j),a(k)
tmp=a(j): a(j)=a(k): a(k)=tmp
j=j+1
k=k-1
wend
if i>0 then
j=i+1
while a(j)<a(i)
j=j+1
wend
'swap a(i),a(j)
tmp=a(j): a(j)=a(i): a(i)=tmp
end if
loop until i=0
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Swift | Swift |
import Foundation
// extend any Indexed collection to be able to shuffle (see http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift)
extension CollectionType where Index == Int {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
// now the model structs
enum CardColor : Int {
case Red
case Black
}
extension CardColor : CustomStringConvertible {
var description : String {
switch self {
case .Red:
return "Red"
case .Black:
return "Black"
}
}
}
enum Suit : Int {
case Hearts = 1
case Diamonds
case Spades
case Clubs
var color : CardColor {
switch self {
case .Hearts, .Diamonds:
return .Red
case .Spades, .Clubs:
return .Black
}
}
}
enum Pip : Int {
case Ace = 1
case Two = 2
case Three = 3
case Four = 4
case Five = 5
case Six = 6
case Seven = 7
case Eight = 8
case Nine = 9
case Ten = 10
case Jack = 11
case Queen = 12
case King = 13
}
struct Card {
let pip : Pip
let suit : Suit
var isFaceCard : Bool {
return pip.rawValue > 10
}
var color : CardColor {
return suit.color
}
}
extension Card : Equatable {}
func == (l:Card, r:Card) -> Bool {
return l.pip == r.pip &&
l.suit == r.suit
}
extension Card : CustomStringConvertible {
var description : String {
return "\(pip) of \(suit)"
}
}
struct Deck {
var cards : [Card]
var count : Int {
return cards.count
}
init(shuffling:Bool=true) {
var startcards = [Card]()
for suit in (Suit.Hearts.rawValue...Suit.Clubs.rawValue) {
for pip in (Pip.Ace.rawValue...Pip.King.rawValue) {
startcards.append(Card(pip: Pip(rawValue: pip)!, suit: Suit(rawValue: suit)!))
}
}
cards = startcards
if shuffling {
shuffle()
}
}
mutating func shuffle() {
cards.shuffleInPlace()
}
mutating func deal() -> Card {
let out = cards.removeFirst()
return out
}
}
extension Deck : CustomStringConvertible {
var description : String {
return "\(count) cards: \(cards.description)"
}
}
// test some cards
let kh = Card(pip: .King, suit: .Hearts)
let ad = Card(pip: .Ace, suit: .Diamonds)
let tc = Card(pip: .Two, suit: .Clubs)
let fc = Card(pip: Pip(rawValue:4)!, suit: .Spades)
// create an unshuffled deck
var efg = Deck(shuffling: false)
// create a shuffled deck and print its contents
var d = Deck()
print(d)
// deal three cards
d.deal()
d.deal()
d.deal()
d
// deal a couple more cards and check their color
let c = d.deal()
c.color
let cc = d.deal()
cc.color
// deal out the rest of the deck, leaving just one card
while d.count > 1 {
d.deal()
}
d
// test equality of a couple cards
if kh == Card(pip: Pip.King, suit: Suit.Clubs) {
let a = true
}
else {
let a = false
}
kh != Card(pip: Pip.King, suit: Suit.Clubs)
kh.isFaceCard
fc.isFaceCard
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Sidef | Sidef | func pi(callback) {
var (q, r, t, k, n, l) = (1, 0, 1, 1, 3, 3)
loop {
if ((4*q + r - t) < n*t) {
callback(n)
static _dot = callback('.')
var nr = 10*(r - n*t)
n = ((10*(3*q + r)) // t - 10*n)
q *= 10
r = nr
}
else {
var nr = ((2*q + r) * l)
var nn = ((q*(7*k + 2) + r*l) // (t*l))
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
}
}
}
STDOUT.autoflush(true)
pi(func(digit){ print digit }) |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Objeck | Objeck | bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
"Perfect numbers from 1 to 33550337:"->PrintLine();
for(num := 1 ; num < 33550337; num += 1;) {
if(IsPerfect(num)) {
num->PrintLine();
};
};
}
function : native : IsPerfect(number : Int) ~ Bool {
sum := 0 ;
for(i := 1; i < number; i += 1;) {
if (number % i = 0) {
sum += i;
};
};
return sum = number;
}
}
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Lobster | Lobster |
// Lobster implementation of the (very fast) Go example
// http://rosettacode.org/wiki/Permutations#Go
// implementing the plain changes (bell ringers) algorithm, using a recursive function
// https://en.wikipedia.org/wiki/Steinhaus–Johnson–Trotter_algorithm
def permr(s, f):
if s.length == 0:
f(s)
return
def rc(np: int):
if np == 1:
f(s)
return
let np1 = np - 1
let pp = s.length - np1
rc(np1) // recurs prior swaps
var i = pp
while i > 0:
// swap s[i], s[i-1]
let t = s[i]
s[i] = s[i-1]
s[i-1] = t
rc(np1) // recurs swap
i -= 1
let w = s[0]
for(pp): s[_] = s[_+1]
s[pp] = w
rc(s.length)
// Heap's recursive method https://en.wikipedia.org/wiki/Heap%27s_algorithm
def permh(s, f):
def rc(k: int):
if k <= 1:
f(s)
else:
// Generate permutations with kth unaltered
// Initially k == length(s)
rc(k-1)
// Generate permutations for kth swapped with each k-1 initial
for(k-1) i:
// Swap choice dependent on parity of k (even or odd)
// zero-indexed, the kth is at k-1
if (k & 1) == 0:
let t = s[i]
s[i] = s[k-1]
s[k-1] = t
else:
let t = s[0]
s[0] = s[k-1]
s[k-1] = t
rc(k-1)
rc(s.length)
// iterative Boothroyd method
import std
def permi(xs, f):
var d = 1
let c = map(xs.length): 0
f(xs)
while true:
while d > 1:
d -= 1
c[d] = 0
while c[d] >= d:
d += 1
if d >= xs.length:
return
let i = if (d & 1) == 1: c[d] else: 0
let t = xs[i]
xs[i] = xs[d]
xs[d] = t
f(xs)
c[d] = c[d] + 1
// next lexicographical permutation
// to get all permutations the initial input `a` must be in sorted order
// returns false when input `a` is in reverse sorted order
def next_lex_perm(a):
def swap(i, j):
let t = a[i]
a[i] = a[j]
a[j] = t
let n = a.length
/* 1. Find the largest index k such that a[k] < a[k + 1]. If no such
index exists, the permutation is the last permutation. */
var k = n - 1
while k > 0 and a[k-1] >= a[k]: k--
if k == 0: return false
k -= 1
/* 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is
such an index, l is well defined */
var l = n - 1
while a[l] <= a[k]: l--
/* 3. Swap a[k] with a[l] */
swap(k, l)
/* 4. Reverse the sequence from a[k + 1] to the end */
k += 1
l = n - 1
while l > k:
swap(k, l)
l -= 1
k += 1
return true
var se = [0, 1, 2, 3] //, 4, 5, 6, 7, 8, 9, 10]
print "Iterative lexicographical permuter"
print se
while next_lex_perm(se): print se
print "Recursive plain changes iterator"
se = [0, 1, 2, 3]
permr(se): print(_)
print "Recursive Heap\'s iterator"
se = [0, 1, 2, 3]
permh(se): print(_)
print "Iterative Boothroyd iterator"
se = [0, 1, 2, 3]
permi(se): print(_)
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Tcl | Tcl | package require Tcl 8.5
namespace eval playing_cards {
variable deck
#variable suits {C D H S}
variable suits {\u2663 \u2662 \u2661 \u2660}
variable pips {2 3 4 5 6 7 8 9 10 J Q K A}
proc new_deck {} {
variable deck
set deck [list]
for {set i 0} {$i < 52} {incr i} {
lappend deck $i
}
}
proc shuffle {} {
variable deck
# shuffle in place
for {set i 51} {$i > 0} {incr i -1} {
set n [expr {int($i * rand())}]
set card [lindex $deck $n]
lset deck $n [lindex $deck $i]
lset deck $i $card
}
}
proc deal {{num 1}} {
variable deck
incr num -1
set cards [lrange $deck 0 $num]
set deck [lreplace $deck 0 $num]
return $cards
}
proc card2string {card} {
variable suits
variable pips
set suit [expr {$card / 13}]
set pip [expr {$card % 13}]
return [format "%2s %s" [lindex $pips $pip] [lindex $suits $suit]]
}
proc print {cards args} {
array set opts [concat -sort false $args]
if {$opts(-sort)} {
set cards [lsort -integer $cards]
}
foreach card $cards {
puts [card2string $card]
}
}
proc print_deck {} {
variable deck
print $deck
}
}
playing_cards::new_deck
playing_cards::shuffle
set hand [playing_cards::deal 5]
puts "my hand:"
playing_cards::print $hand -sort true
puts "\nthe deck:"
playing_cards::print_deck |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Simula | Simula | CLASS BIGNUM;
BEGIN
BOOLEAN PROCEDURE TISZERO(T); TEXT T;
TISZERO := T = "0";
TEXT PROCEDURE TSHL(T); TEXT T;
TSHL :- IF TISZERO(T) THEN T ELSE T & "0";
TEXT PROCEDURE TSHR(T); TEXT T;
TSHR :- IF T.LENGTH = 1 THEN "0" ELSE T.SUB(1, T.LENGTH - 1);
INTEGER PROCEDURE TSIGN(T); TEXT T;
TSIGN := IF TISZERO(T) THEN 0
ELSE IF T.SUB(1, 1) = "-" THEN -1
ELSE 1;
TEXT PROCEDURE TABS(T); TEXT T;
TABS :- IF TSIGN(T) < 0 THEN T.SUB(2, T.LENGTH - 1) ELSE T;
TEXT PROCEDURE TNEGATE(T); TEXT T;
TNEGATE :- IF TSIGN(T) <= 0 THEN TABS(T) ELSE ("-" & T);
TEXT PROCEDURE TREVERSE(T); TEXT T;
BEGIN
INTEGER I, J;
I := 1; J := T.LENGTH;
WHILE I < J DO
BEGIN CHARACTER C1, C2;
T.SETPOS(I); C1 := T.GETCHAR;
T.SETPOS(J); C2 := T.GETCHAR;
T.SETPOS(I); T.PUTCHAR(C2);
T.SETPOS(J); T.PUTCHAR(C1);
I := I + 1;
J := J - 1;
END;
TREVERSE :- T;
END TREVERSE;
INTEGER PROCEDURE TCMPUNSIGNED(A, B); TEXT A, B;
BEGIN
INTEGER ALEN, BLEN, RESULT;
ALEN := A.LENGTH; BLEN := B.LENGTH;
IF ALEN < BLEN THEN
RESULT := -1
ELSE IF ALEN > BLEN THEN
RESULT := 1
ELSE BEGIN
INTEGER CMP, I; BOOLEAN DONE;
A.SETPOS(1);
B.SETPOS(1);
I := 1;
WHILE I <= ALEN AND NOT DONE DO
BEGIN
I := I + 1;
CMP := RANK(A.GETCHAR) - RANK(B.GETCHAR);
IF NOT (CMP = 0) THEN
DONE := TRUE;
END;
RESULT := CMP;
END;
TCMPUNSIGNED := RESULT;
END TCMPUNSIGNED;
INTEGER PROCEDURE TCMP(A, B); TEXT A, B;
BEGIN
BOOLEAN ANEG, BNEG;
ANEG := TSIGN(A) < 0; BNEG := TSIGN(B) < 0;
IF ANEG AND BNEG THEN
TCMP := -TCMPUNSIGNED(TABS(A), TABS(B))
ELSE IF NOT ANEG AND BNEG THEN
TCMP := 1
ELSE IF ANEG AND NOT BNEG THEN
TCMP := -1
ELSE
TCMP := TCMPUNSIGNED(A, B);
END TCMP;
TEXT PROCEDURE TADDUNSIGNED(A, B); TEXT A, B;
BEGIN
INTEGER CARRY, I, J;
TEXT BF;
I := A.LENGTH;
J := B.LENGTH;
BF :- BLANKS(MAX(I, J) + 1);
WHILE I >= 1 OR J >= 1 DO BEGIN
INTEGER X, Y, Z;
IF I >= 1 THEN BEGIN
A.SETPOS(I); I := I - 1; X := RANK(A.GETCHAR) - RANK('0');
END;
IF J >= 1 THEN BEGIN
B.SETPOS(J); J := J - 1; Y := RANK(B.GETCHAR) - RANK('0');
END;
Z := X + Y + CARRY;
IF Z < 10 THEN
BEGIN BF.PUTCHAR(CHAR(Z + RANK('0'))); CARRY := 0;
END ELSE
BEGIN BF.PUTCHAR(CHAR(MOD(Z, 10) + RANK('0'))); CARRY := 1;
END;
END;
IF CARRY > 0 THEN
BF.PUTCHAR(CHAR(CARRY + RANK('0')));
BF :- TREVERSE(BF.STRIP);
TADDUNSIGNED :- BF;
END TADDUNSIGNED;
TEXT PROCEDURE TADD(A, B); TEXT A, B;
BEGIN
BOOLEAN ANEG, BNEG;
ANEG := TSIGN(A) < 0; BNEG := TSIGN(B) < 0;
IF NOT ANEG AND BNEG THEN ! (+7)+(-5) = (7-5) = 2 ;
TADD :- TSUBUNSIGNED(A, TABS(B))
ELSE IF ANEG AND NOT BNEG THEN ! (-7)+(+5) = (5-7) = -2 ;
TADD :- TSUBUNSIGNED(B, TABS(A))
ELSE IF ANEG AND BNEG THEN ! (-7)+(-5) = -(7+5) = -12 ;
TADD :- TNEGATE(TADDUNSIGNED(TABS(A), TABS(B)))
ELSE ! (+7)+(+5) = (7+5) = 12 ;
TADD :- TADDUNSIGNED(A, B);
END TADD;
TEXT PROCEDURE TSUBUNSIGNED(A, B); TEXT A, B;
BEGIN
INTEGER I, J, CARRY;
I := A.LENGTH; J := B.LENGTH;
IF I < J OR I = J AND A < B THEN
TSUBUNSIGNED :- TNEGATE(TSUBUNSIGNED(B, A)) ELSE
BEGIN
TEXT BF;
BF :- BLANKS(MAX(I, J) + 1);
WHILE I >= 1 OR J >= 1 DO
BEGIN
INTEGER X, Y, Z;
IF I >= 1 THEN
BEGIN A.SETPOS(I); I := I - 1;
X := RANK(A.GETCHAR) - RANK('0');
END;
IF J >= 1 THEN
BEGIN B.SETPOS(J); J := J - 1;
Y := RANK(B.GETCHAR) - RANK('0');
END;
Z := X - Y - CARRY;
IF Z >= 0 THEN
BEGIN
BF.PUTCHAR(CHAR(RANK('0') + Z));
CARRY := 0;
END ELSE
BEGIN
BF.PUTCHAR(CHAR(RANK('0') + MOD(10 + Z, 10)));
CARRY := 1; ! (Z / 10);
END;
END;
BF :- BF.STRIP;
BF :- TREVERSE(BF);
BF.SETPOS(1);
WHILE BF.LENGTH > 1 AND THEN BF.GETCHAR = '0' DO
BEGIN
BF :- BF.SUB(2, BF.LENGTH - 1);
BF.SETPOS(1);
END;
TSUBUNSIGNED :- BF;
END;
END TSUBUNSIGNED;
TEXT PROCEDURE TSUB(A, B); TEXT A, B;
BEGIN
BOOLEAN ANEG, BNEG;
ANEG := TSIGN(A) < 0; BNEG := TSIGN(B) < 0;
IF ANEG AND BNEG THEN ! (-7)-(-5) = -(7-5) = -2 ;
TSUB :- TNEGATE(TSUBUNSIGNED(TABS(A), TABS(B)))
ELSE IF NOT ANEG AND BNEG THEN ! (+7)-(-5) = (7+5) = 12 ;
TSUB :- TADDUNSIGNED(A, TABS(B))
ELSE IF ANEG AND NOT BNEG THEN ! (-7)-(+5) = -(7+5) = -12 ;
TSUB :- TNEGATE(TADDUNSIGNED(TABS(A), B))
ELSE ! (+7)-(+5) = (7-5) = 2 ;
TSUB :- TSUBUNSIGNED(A, B);
END TSUB;
TEXT PROCEDURE TMULUNSIGNED(A, B); TEXT A, B;
BEGIN
INTEGER ALEN, BLEN;
ALEN := A.LENGTH; BLEN := B.LENGTH;
IF ALEN < BLEN THEN
TMULUNSIGNED :- TMULUNSIGNED(B, A)
ELSE BEGIN
TEXT PRODUCT; INTEGER J;
PRODUCT :- "0";
FOR J := 1 STEP 1 UNTIL BLEN DO BEGIN
TEXT PART; INTEGER I, Y, CARRY;
B.SETPOS(J); Y := RANK(B.GETCHAR) - RANK('0');
PART :- BLANKS(ALEN + BLEN + 1); PART.SETPOS(1);
FOR I := ALEN STEP -1 UNTIL 1 DO BEGIN
INTEGER X, Z;
A.SETPOS(I); X := RANK(A.GETCHAR) - RANK('0');
Z := X * Y + CARRY;
IF Z < 10 THEN BEGIN
PART.PUTCHAR(CHAR(RANK('0') + Z));
CARRY := 0;
END ELSE BEGIN
PART.PUTCHAR(CHAR(RANK('0') + MOD(Z, 10)));
CARRY := Z // 10;
END;
END;
IF CARRY > 0 THEN
PART.PUTCHAR(CHAR(RANK('0') + CARRY));
PART :- PART.SUB(1, PART.POS - 1);
PART :- TREVERSE(PART);
PART.SETPOS(1);
WHILE PART.LENGTH > 1 AND THEN PART.GETCHAR = '0' DO
BEGIN
PART :- PART.SUB(2, PART.LENGTH - 1);
PART.SETPOS(1);
END;
PRODUCT :- TADDUNSIGNED(TSHL(PRODUCT), PART);
END;
TMULUNSIGNED :- PRODUCT;
END;
END TMULUNSIGNED;
TEXT PROCEDURE TMUL(A, B); TEXT A, B;
BEGIN
BOOLEAN ANEG, BNEG;
ANEG := TSIGN(A) < 0; BNEG := TSIGN(B) < 0;
IF ANEG AND BNEG THEN ! (-7)*(-5) = (7*5) => 35 ;
TMUL :- TMULUNSIGNED(TABS(A), TABS(B))
ELSE IF NOT ANEG AND BNEG THEN ! (+7)*(-5) = -(7*5) => -35 ;
TMUL :- TNEGATE(TMULUNSIGNED(A, TABS(B)))
ELSE IF ANEG AND NOT BNEG THEN ! (-7)*(+5) = -(7*5) => -35 ;
TMUL :- TNEGATE(TMULUNSIGNED(TABS(A), B))
ELSE ! (+7)*(+5) = (7*5) => 35 ;
TMUL :- TMULUNSIGNED(A, B);
END TMUL;
CLASS DIVMOD(DIV,MOD); TEXT DIV,MOD;;
REF(DIVMOD) PROCEDURE TDIVMODUNSIGNED(A, B); TEXT A, B;
BEGIN
INTEGER CC;
REF(DIVMOD) RESULT;
IF TISZERO(B) THEN
ERROR("DIVISION BY ZERO");
CC := TCMPUNSIGNED(A, B);
IF CC < 0 THEN
RESULT :- NEW DIVMOD("0", A)
ELSE IF CC = 0 THEN
RESULT :- NEW DIVMOD("1", "0")
ELSE BEGIN
INTEGER ALEN, BLEN, AIDX;
TEXT Q, R;
ALEN := A.LENGTH; BLEN := B.LENGTH;
Q :- BLANKS(ALEN); Q.SETPOS(1);
R :- BLANKS(ALEN); R.SETPOS(1);
R := A.SUB(1, BLEN - 1); R.SETPOS(BLEN);
FOR AIDX := BLEN STEP 1 UNTIL ALEN DO
BEGIN
INTEGER COUNT; BOOLEAN DONE;
IF TISZERO(R.STRIP) THEN
R.SETPOS(1);
A.SETPOS(AIDX); R.PUTCHAR(A.GETCHAR);
WHILE NOT DONE DO
BEGIN
TEXT DIFF;
DIFF :- TSUBUNSIGNED(R.STRIP, B);
IF TSIGN(DIFF) < 0 THEN
DONE := TRUE
ELSE BEGIN
R := DIFF; R.SETPOS(DIFF.LENGTH + 1);
COUNT := COUNT + 1;
END;
END;
IF (NOT (COUNT = 0)) OR (NOT (Q.POS = 1)) THEN
Q.PUTCHAR(CHAR(COUNT + RANK('0')));
END;
RESULT :- NEW DIVMOD(Q.STRIP, R.STRIP);
END;
TDIVMODUNSIGNED :- RESULT;
END TDIVMODUNSIGNED;
REF(DIVMOD) PROCEDURE TDIVMOD(A, B); TEXT A, B;
BEGIN
BOOLEAN ANEG, BNEG; REF(DIVMOD) RESULT;
ANEG := TSIGN(A) < 0; BNEG := TSIGN(B) < 0;
IF ANEG AND BNEG THEN
BEGIN
RESULT :- TDIVMOD(TABS(A), TABS(B));
RESULT.MOD :- TNEGATE(RESULT.MOD);
END
ELSE IF NOT ANEG AND BNEG THEN
BEGIN
RESULT :- TDIVMOD(A, TABS(B));
RESULT.DIV :- TNEGATE(RESULT.DIV);
END
ELSE IF ANEG AND NOT BNEG THEN
BEGIN
RESULT :- TDIVMOD(TABS(A), B);
RESULT.DIV :- TNEGATE(RESULT.DIV);
RESULT.MOD :- TNEGATE(RESULT.MOD);
END
ELSE
RESULT :- TDIVMODUNSIGNED(A, B);
TDIVMOD :- RESULT;
END TDIVMOD;
TEXT PROCEDURE TDIV(A, B); TEXT A, B;
TDIV :- TDIVMOD(A, B).DIV;
TEXT PROCEDURE TMOD(A, B); TEXT A, B;
TMOD :- TDIVMOD(A, B).MOD;
END BIGNUM; |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #OCaml | OCaml | let perf n =
let sum = ref 0 in
for i = 1 to n-1 do
if n mod i = 0 then
sum := !sum + i
done;
!sum = n |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Oforth | Oforth | : isPerfect(n) | i | 0 n 2 / loop: i [ n i mod ifZero: [ i + ] ] n == ; |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Logtalk | Logtalk | :- object(list).
:- public(permutation/2).
permutation(List, Permutation) :-
same_length(List, Permutation),
permutation2(List, Permutation).
permutation2([], []).
permutation2(List, [Head| Tail]) :-
select(Head, List, Remaining),
permutation2(Remaining, Tail).
same_length([], []).
same_length([_| Tail1], [_| Tail2]) :-
same_length(Tail1, Tail2).
select(Head, [Head| Tail], Tail).
select(Head, [Head2| Tail], [Head2| Tail2]) :-
select(Head, Tail, Tail2).
:- end_object. |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #VBScript | VBScript |
class playingcard
dim suit
dim pips
end class
class carddeck
private suitnames
private pipnames
private cardno
private deck(52)
private nTop
sub class_initialize
dim suit
dim pips
suitnames = split("H,D,C,S",",")
pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",")
cardno = 0
for suit = 1 to 4
for pips = 1 to 13
set deck(cardno) = new playingcard
deck(cardno).suit = suitnames(suit-1)
deck(cardno).pips = pipnames(pips-1)
cardno = cardno + 1
next
next
nTop = 0
end sub
public sub showdeck
dim a
redim a(51-nTop)
for i = nTop to 51
a(i) = deck(i).pips & deck(i).suit
next
wscript.echo join( a, ", ")
end sub
public sub shuffle
dim r
randomize timer
for i = nTop to 51
r = int( rnd * ( 52 - nTop ) )
if r <> i then
objswap deck(i),deck(r)
end if
next
end sub
public function deal()
set deal = deck( nTop )
nTop = nTop + 1
end function
public property get cardsRemaining
cardsRemaining = 52 - nTop
end property
private sub objswap( a, b )
dim tmp
set tmp = a
set a = b
set b = tmp
end sub
end class
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Tailspin | Tailspin |
use 'java:java.math' stand-alone
def zero: 0 -> math/BigInteger::valueOf;
def one: 1 -> math/BigInteger::valueOf;
def two: 2 -> math/BigInteger::valueOf;
def three: 3 -> math/BigInteger::valueOf;
def four: 4 -> math/BigInteger::valueOf;
def seven: 7 -> math/BigInteger::valueOf;
def ten: 10 -> math/BigInteger::valueOf;
templates g&{q:, r:, t:, k:, n:, l:}
def u: $four -> q::multiply -> r::add;
def nt: $n -> t::multiply;
$ -> #
when <?($t -> u::subtract <..~$nt>)> do
$n -> !OUT::write
$ -> \(<=1> $!\) -> '.' -> !OUT::write
def v: $three -> q::multiply -> r::add -> ten::multiply;
def quot: $t -> v::divide;
0 -> g&{q: $ten -> q::multiply,
r: $nt -> r::subtract -> ten::multiply,
t: $t,
k: $k,
n: $ten -> n::multiply -> quot::subtract,
l: $l } !
otherwise
def tl: $t -> l::multiply;
def rl: $r -> l::multiply;
def term: $q -> seven::multiply -> k::multiply -> two::add -> rl::add;
$ -> g&{q: $q -> k::multiply,
r: $two -> q::multiply -> r::add -> l::multiply,
t: $tl,
k: $k -> one::add,
n: $tl -> term::divide,
l: $l -> two::add} !
end g
1 -> g&{q:$one, r:$zero, t:$one, k:$one, n:$three, l:$three} -> !VOID
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #ooRexx | ooRexx | -- first perfect number over 10000 is 33550336...let's not be crazy
loop i = 1 to 10000
if perfectNumber(i) then say i "is a perfect number"
end
::routine perfectNumber
use strict arg n
sum = 0
-- the largest possible factor is n % 2, so no point in
-- going higher than that
loop i = 1 to n % 2
if n // i == 0 then sum += i
end
return sum = n |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Lua | Lua |
local function permutation(a, n, cb)
if n == 0 then
cb(a)
else
for i = 1, n do
a[i], a[n] = a[n], a[i]
permutation(a, n - 1, cb)
a[i], a[n] = a[n], a[i]
end
end
end
--Usage
local function callback(a)
print('{'..table.concat(a, ', ')..'}')
end
permutation({1,2,3}, 3, callback)
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Vedit_macro_language | Vedit macro language | // Playing Cards, main program
Call("CREATE_DECK")
Call("SHUFFLE_DECK")
#21 = Buf_Switch(Buf_Free) // #21 = players hand, 1st player
#1 = 5; Call("DEAL_CARDS") // deal 5 cards to player 1
#22 = Buf_Switch(Buf_Free) // #22 = players hand, 2nd player
#1 = 5; Call("DEAL_CARDS") // deal 5 cards to player 2
Buf_Switch(#10) BOF // display the deck
Return
///////////////////////////////////////////////////////////////////////////
//
// Create a deck into a new edit buffer. One text line for each card.
//
:CREATE_DECK:
#10 = Buf_Switch(Buf_Free) // Buffer @(#10) = the deck
RS(1, "Diamonds")
RS(2, "Spades")
RS(3, "Hearts")
RS(4, "Clubs")
RS(11, " Jack")
RS(12, "Queen")
RS(13, " King")
RS(14, " Ace")
for (#1=1; #1<5; #1++) {
for (#2=2; #2<15; #2++) {
if (#2 < 11) {
Num_Ins(#2, NOCR) // pip (2 to 10) as numeric
} else {
IT(@(#2)) // pip (11 to 14) as a word
}
IT(" of ")
IT(@(#1)) IN // suit
}
}
Return
///////////////////////////////////////////////////////////////////////////
//
// Shuffle the deck using Fisher-Yates algorithm
//
:SHUFFLE_DECK:
Buf_Switch(#10) // the deck
#90 = Time_Tick // seed for random number generator
#91 = 51 // random numbers in range 0 to 50
for (#1=1; #1<52; #1++) {
Call("RANDOM")
Goto_Line(Return_Value+1)
Block_Copy(#1, #1, LINESET+DELETE)
Reg_Copy(9, 1, DELETE)
Goto_Line(#1)
Reg_Ins(9)
}
Return
//--------------------------------------------------------------
// Generate random numbers in range 0 <= Return_Value < #91
// #90 = Seed (0 to 0x7fffffff)
// #91 = Scaling (0 to 0x10000)
:RANDOM:
#92 = 0x7fffffff / 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)
///////////////////////////////////////////////////////////////////////////
//
// Deal #1 cards: move the cards from deck to current edit buffer
//
:DEAL_CARDS:
#11 = Buf_Num // this buffer (players hand)
Buf_Switch(#10) // the deck
BOF
Reg_Copy(9, #1, DELETE) // pull the first #1 cards from the deck
Buf_Switch(#11) // players hand
Reg_ins(9) // insert the cards here
Return |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Tcl | Tcl | package require Tcl 8.6
# http://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml
# http://www.mathpropress.com/stan/bibliography/spigot.pdf
proc piDigitsBySpigot n {
yield [info coroutine]
set A [lrepeat [expr {int(floor(10*$n/3.)+1)}] 2]
set Alen [llength $A]
set predigits {}
while 1 {
set carry 0
for {set i $Alen} {[incr i -1] > 0} {} {
lset A $i [expr {
[set val [expr {[lindex $A $i] * 10 + $carry}]]
% [set modulo [expr {2*$i + 1}]]
}]
set carry [expr {$val / $modulo * $i}]
}
lset A 0 [expr {[set val [expr {[lindex $A 0]*10 + $carry}]] % 10}]
set predigit [expr {$val / 10}]
if {$predigit < 9} {
foreach p $predigits {yield $p}
set predigits [list $predigit]
} elseif {$predigit == 9} {
lappend predigits $predigit
} else {
foreach p $predigits {yield [incr p]}
set predigits [list 0]
}
}
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Oz | Oz | declare
fun {IsPerfect N}
fun {IsNFactor I} N mod I == 0 end
Factors = {Filter {List.number 1 N-1 1} IsNFactor}
in
{Sum Factors} == N
end
fun {Sum Xs} {FoldL Xs Number.'+' 0} end
in
{Show {Filter {List.number 1 10000 1} IsPerfect}}
{Show {IsPerfect 33550336}} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Global a$
Document a$
Module Permutations (s){
Module Level (n, s, h) {
If n=1 then {
while Len(s) {
m1=each(h)
while m1 {
Print Array$(m1);" ";
}
Print Array$(S)
ToClipBoard()
s=cdr(s)
}
} Else {
for i=1 to len(s) {
call Level n-1, cdr(s), cons(h, car(s))
s=cons(cdr(s), car(s))
}
}
Sub ToClipBoard()
local m=each(h)
Local b$=""
While m {
b$+=If$(Len(b$)<>0->" ","")+Array$(m)+" "
}
b$+=If$(Len(b$)<>0->" ","")+Array$(s,0)+" "+{
}
a$<=b$ ' assign to global need <=
End Sub
}
If len(s)=0 then Error
Head=(,)
Call Level Len(s), s, Head
}
Clear a$
Permutations (1,2,3,4)
Permutations (100, 200, 500)
Permutations ("A", "B", "C","D")
Permutations ("DOG", "CAT", "BAT")
ClipBoard a$
}
Checkit
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Wren | Wren | import "random" for Random
var FACES = "23456789TJQKA"
var SUITS = "shdc"
var createDeck = Fn.new {
var cards = []
SUITS.each { |suit| FACES.each { |face| cards.add("%(face)%(suit)") } }
return cards
}
var dealTopDeck = Fn.new { |deck, n| deck.take(n).toList }
var dealBottomDeck = Fn.new { |deck, n| deck[-n..-1][-1..0] }
var printDeck = Fn.new { |deck|
for (i in 0...deck.count) {
System.write("%(deck[i]) ")
if ((i + 1) % 13 == 0 || i == deck.count - 1) System.print()
}
}
var deck = createDeck.call()
System.print("After creation, deck consists of:")
printDeck.call(deck)
Random.new().shuffle(deck)
System.print("\nAfter shuffling, deck consists of:")
printDeck.call(deck)
var dealtTop = dealTopDeck.call(deck, 10)
System.print("\nThe 10 cards dealt from the top of the deck are:")
printDeck.call(dealtTop)
var dealtBottom = dealBottomDeck.call(deck, 10)
System.print("\nThe 10 cards dealt from the bottom of the deck are:")
printDeck.call(dealtBottom) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #TypeScript | TypeScript | type AnyWriteableObject={write:((textToOutput:string)=>any)};
function calcPi(pipe:AnyWriteableObject) {
let q = 1n, r=0n, t=1n, k=1n, n=3n, l=3n;
while (true) {
if (q * 4n + r - t < n* t) {
pipe.write(n.toString());
let nr = (r - n * t) * 10n;
n = (q * 3n + r) * 10n / t - n * 10n ;
q = q * 10n;
r = nr;
} else {
let nr = (q * 2n + r) * l;
let nn = (q * k * 7n + 2n + r * l) / (t * l);
q = q * k;
t = t * l;
l = l + 2n;
k = k + 1n;
n = nn;
r = nr;
}
}
}
calcPi(process.stdout); |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PARI.2FGP | PARI/GP | isPerfect(n)=sigma(n,-1)==2 |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Pascal | Pascal | program PerfectNumbers;
function isPerfect(number: longint): boolean;
var
i, sum: longint;
begin
sum := 1;
for i := 2 to round(sqrt(real(number))) do
if (number mod i = 0) then
sum := sum + i + (number div i);
isPerfect := (sum = number);
end;
var
candidate: longint;
begin
writeln('Perfect numbers from 1 to 33550337:');
for candidate := 2 to 33550337 do
if isPerfect(candidate) then
writeln (candidate, ' is a perfect number.');
end. |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #m4 | m4 | divert(-1)
# 1-based indexing of a string's characters.
define(`get',`substr(`$1',decr(`$2'),1)')
define(`set',`substr(`$1',0,decr(`$2'))`'$3`'substr(`$1',`$2')')
define(`swap',
`pushdef(`_u',`get(`$1',`$2')')`'dnl
pushdef(`_v',`get(`$1',`$3')')`'dnl
set(set(`$1',`$2',_v),`$3',_u)`'dnl
popdef(`_u',`_v')')
# $1-fold repetition of $2.
define(`repeat',`ifelse($1,0,`',`$2`'$0(decr($1),`$2')')')
#
# Heap's algorithm. Algorithm 2 in Robert Sedgewick, 1977. Permutation
# generation methods. ACM Comput. Surv. 9, 2 (June 1977), 137-164.
#
# This implementation permutes the characters in a string of length no
# more than 9. On longer strings, it may strain the resources of a
# very old implementation of m4.
#
define(`permutations',
`ifelse($2,`',`$1
$0(`$1',repeat(len(`$1'),1),2)',
`ifelse(eval(($3) <= len(`$1')),1,
`ifelse(eval(get($2,$3) < $3),1,
`swap(`$1',_$0($2,$3),$3)
$0(swap(`$1',_$0($2,$3),$3),set($2,$3,incr(get($2,$3))),2)',
`$0(`$1',set($2,$3,1),incr($3))')')')')
define(`_permutations',`eval((($2) % 2) + ((1 - (($2) % 2)) * get($1,$2)))')
divert`'dnl
permutations(`123')
permutations(`abcd') |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #XPL0 | XPL0 | char Deck(52); \card structure (low 2 bits = suit)
def Players = 4; \number of players to deal to
char Hand(Players, 52); \each player's hand
int Card, N, I, J, T;
char Suit, Royal;
[for Card:= 0 to 52-1 do \make a new deck
Deck(Card):= Card;
for N:= 0 to 10000 do \shuffle the deck
[I:= Ran(52); J:= Ran(52);
T:= Deck(I); Deck(I):= Deck(J); Deck(J):= T;
];
for N:= 0 to 52-1 do \deal from the deck
[Card:= Deck(N);
I:= N/Players;
J:= rem(0);
Hand(J, I):= Card;
];
Suit:= "HDCS "; \print each player's hand
Royal:= "JQK "; \ (= contents of the deck)
for J:= 0 to Players-1 do \e.g: 2D 3C 10C AS KD
[for I:= 0 to 52/Players -1 do
[Card:= Hand(J, I);
N:= Card>>2 + 1; \pip value
if N = 1 then ChOut(0, ^A)
else if N >= 11 then ChOut(0, Royal(N-11))
else IntOut(0, N);
ChOut(0, Suit(Card&3));
ChOut(0, ^ );
];
CrLf(0);
];
] |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Visual_Basic | Visual Basic | Option Explicit
Sub Main()
Const VECSIZE As Long = 3350
Const BUFSIZE As Long = 201
Dim buffer(1 To BUFSIZE) As Long
Dim vect(1 To VECSIZE) As Long
Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long
For n = 1 To VECSIZE
vect(n) = 2
Next n
For n = 1 To BUFSIZE
karray = 0
For l = VECSIZE To 1 Step -1
num = 100000 * vect(l) + karray * l
karray = num \ (2 * l - 1)
vect(l) = num - karray * (2 * l - 1)
Next l
k = karray \ 100000
buffer(n) = more + k
more = karray - k * 100000
Next n
Debug.Print CStr(buffer(1));
Debug.Print "."
l = 0
For n = 2 To BUFSIZE
Debug.Print Format$(buffer(n), "00000");
l = l + 1
If l = 10 Then
l = 0
Debug.Print 'line feed
End If
Next n
End Sub |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Perl | Perl | sub perf {
my $n = shift;
my $sum = 0;
foreach my $i (1..$n-1) {
if ($n % $i == 0) {
$sum += $i;
}
}
return $sum == $n;
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Maple | Maple | combinat:-permute(3);
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
combinat:-permute([a,b,c]);
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]] |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #zkl | zkl | const Diamonds=1, Spades=3, Clubs=0, Hearts=2, Ace=1; // informational
var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡
class Card{
fcn init(pip,suit){ // or 0..51
reg p,s;
if(vm.numArgs==1){ s=pip/13; p=pip%13; } else { p=pip; s=suit }
var [const] _pip=p, _suit=s;
}
fcn toString{
p:=_pip + (_pip>=11);
(suits[_suit]+p).toString(8); // int-->UTF-8
}
}
class Deck{ //--> 52 shuffled Cards
var [const] deck=L();
fcn init{
(0).pump(52,deck.clear().write,Card);
shuffle();
}
fcn shuffle{ deck.shuffle() }
fcn deal(cards=5){ deck.pop(0,cards); }
fcn toString{ deck.pump(String,"toString"); }
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Visual_Basic_.NET | Visual Basic .NET | Imports System
Imports System.Numerics
Public Module Module1
Public Sub Main()
Dim two, three, four, seven, ten, k, q, t, l, n, r, nn, nr As BigInteger,
first As Boolean = True
two = New BigInteger(2) : three = New BigInteger(3) : four = two + two
seven = three + four : ten = three + seven : k = BigInteger.One
q = k : t = k : l = three : n = three : r = BigInteger.Zero
While True
If four * q + r - t < n * t Then
Console.Write(n) : If first Then Console.Write(".") : first = False
nr = ten * (r - n * t) : n = ten * (three * q + r) / t - ten * n
q *= ten
Else
nr = (two * q + r) * l : nn = (q * seven * k + two + r * l) / (t * l)
q *= k : t *= l : l += two : k += BigInteger.One : n = nn
End If
r = nr
End While
End Sub
End Module |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Phix | Phix | function is_perfect(integer n)
return sum(factors(n,-1))=n
end function
for i=2 to 100000 do
if is_perfect(i) then ?i end if
end for
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PHP | PHP | function is_perfect($number)
{
$sum = 0;
for($i = 1; $i < $number; $i++)
{
if($number % $i == 0)
$sum += $i;
}
return $sum == $number;
}
echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
if(is_perfect($num))
echo $num . PHP_EOL;
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
(***Standard list functions:*)
fold[f_, x_, {}] := x
fold[f_, x_, {h_, t___}] := fold[f, f[x, h], {t}]
insert[L_, x_, n_] := Join[L[[;; n - 1]], {x}, L[[n ;;]]]
(***Generate all permutations of a list S:*)
permutations[S_] :=
fold[Join @@ (Function[{L},
Table[insert[L, #2, k + 1], {k, 0, Length[L]}]] /@ #1) &, {{}},
S]
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 GOSUB 5000
20 CLS
30 PRINT "Options:"
40 PRINT "1: Shuffle deck"
50 PRINT "2: Deal cards"
60 PRINT "3: Display deck"
70 INPUT o
80 IF o<1 OR o>3 OR o<>INT o THEN GOTO 70
90 GO SUB (o+1)*1000
100 GO TO 20
999 REM convert index to card
1000 LET s=INT ((x-1)/13)+1
1010 LET p=x-13*(s-1)
1020 LET n=s-2*INT (s/2)+1
1030 LET c$=p$(p)+CHR$ 16+CHR$ (n AND n>1)+s$(s): REM colour codes to force red or black
1040 RETURN
1999 REM shuffle - only a naive shuffle algorithm but it'll do; the modularity of the program means this is easy enough to modify
2000 CLS : PRINT FLASH 1;"Shuffling..."
2010 LET s=1: REM changing s allows shuffling the remainder of an undealt deck, say
2020 FOR x=1 TO 100
2030 LET a=INT (RND*53-s)+s
2040 LET b=INT (RND*53-s)+s
2050 LET n=d(a)
2060 LET d(a)=d(b)
2070 LET d(b)=n
2080 NEXT x
2090 RETURN
2999 REM deal
3000 INPUT "How many players? ";p
3010 INPUT "How many cards? ";c
3020 IF c<1 OR p<1 OR c<>INT c OR p<>INT p THEN PRINT "Don't be silly!": GO TO 3000
3030 IF c*p>52 THEN PRINT "Not enough cards for that!": GO TO 3000
3040 CLS : DIM h(p,c)
3050 LET k=1
3060 FOR f=1 TO c
3070 FOR e=1 TO p
3080 LET h(e,f)=d(k)
3090 LET k=k+1
3100 NEXT e
3110 NEXT f
3120 FOR e=1 TO p
3130 PRINT "Player ";e;"'s hand:"
3140 FOR f=1 TO c
3150 LET x=h(e,f)
3160 GO SUB 1000
3170 PRINT c$;" ";
3180 NEXT e
3190 PRINT
3200 NEXT f
3210 PRINT
3220 PRINT "Remaining deck:"
3230 IF c*p=52 THEN PRINT "none"
3240 GO SUB 4010
3250 RETURN
3999 REM display deck
4000 CLS : LET k=1
4010 FOR y=k TO 52: REM enter here with k>1 to show the rest of an undealt deck
4020 LET x=d(y)
4030 GO SUB 1000
4040 PRINT c$
4050 NEXT y
4060 FOR y=0 TO 1000
4070 NEXT y
4080 RETURN
4999 REM initialise
5000 DIM d(52)
5010 GO SUB 6000
5020 LET s$=CHR$ 144+CHR$ 145+CHR$ 146+CHR$ 147: REM or LET s$="HSDC" if you don't want symbols
5030 LET p$="A23456789TJQK"
5040 FOR x=1 TO 52
5050 LET d(x)=x
5060 NEXT x
5070 RETURN
5999 REM characters - the ZX Spectrum character set doesn't contain suit symbols
6000 RESTORE 7000
6010 FOR x=65368 TO 65399
6020 READ a
6030 POKE x,a
6040 NEXT x
6050 RETURN
7000 DATA BIN 01101100: REM 108
7010 DATA BIN 11111110: REM 254
7020 DATA BIN 11111110: REM 254
7030 DATA BIN 11111110: REM 254
7040 DATA BIN 01111100: REM 124
7050 DATA BIN 00111000: REM 56
7060 DATA BIN 00010000: REM 16
7070 DATA BIN 00000000: REM 0
7080 DATA BIN 00010000: REM 16
7090 DATA BIN 00111000: REM 56
7100 DATA BIN 01111100: REM 124
7110 DATA BIN 11111110: REM 254
7120 DATA BIN 01010100: REM 84
7130 DATA BIN 00010000: REM 16
7140 DATA BIN 01111100: REM 124
7150 DATA BIN 00000000: REM 0
7160 DATA BIN 00010000: REM 16
7170 DATA BIN 00111000: REM 56
7180 DATA BIN 01111100: REM 124
7190 DATA BIN 11111110: REM 254
7200 DATA BIN 01111100: REM 124
7210 DATA BIN 00111000: REM 56
7220 DATA BIN 00010000: REM 16
7230 DATA BIN 00000000: REM 0
7240 DATA BIN 00010000: REM 16
7250 DATA BIN 00111000: REM 56
7260 DATA BIN 01010100: REM 84
7270 DATA BIN 11111110: REM 254
7280 DATA BIN 01010100: REM 84
7290 DATA BIN 00010000: REM 16
7300 DATA BIN 01111100: REM 124
7310 DATA BIN 00000000: REM 0 |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Wren | Wren | import "/big" for BigInt
import "io" for Stdout
var calcPi = Fn.new {
var nn = BigInt.zero
var nr = BigInt.zero
var q = BigInt.one
var r = BigInt.zero
var t = BigInt.one
var k = BigInt.one
var n = BigInt.three
var l = BigInt.three
var first = true
while (true) {
if (q * BigInt.four + r - t < n * t) {
System.write(n)
if (first) {
System.write(".")
first = false
}
Stdout.flush()
nr = (r - n * t) * BigInt.ten
n = (q * BigInt.three + r) * BigInt.ten / t - n * BigInt.ten
q = q * BigInt.ten
r = nr
} else {
nr = (q * BigInt.two + r) * l
nn = (q * BigInt.new(7) * k + BigInt.two + r * l) / (t * l)
q = q * k
t = t * l
l = l + BigInt.two
k = k + BigInt.one
n = nn.copy()
r = nr
}
}
}
calcPi.call() |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Picat | Picat | go =>
println(perfect1=[I : I in 1..10_000, perfect1(I)]),
nl.
perfect1(N) => sum(divisors(N)) == N.
divisors(N) = [J: J in 1..1+N div 2, N mod J == 0]. |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PicoLisp | PicoLisp | (de perfect (N)
(let C 0
(for I (/ N 2)
(and (=0 (% N I)) (inc 'C I)) )
(= C N) ) ) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #MATLAB_.2F_Octave | MATLAB / Octave | perms([1,2,3,4]) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Yabasic | Yabasic | n = 1000
long = 10 * int(n / 4)
needdecimal = 1 //true
dim a(long)
nines = 0
predigit = 0 // {First predigit is a 0}
for j = 1 to long
a(j-1) = 2 // {Start with 2s}
next j
for j = 1 to n
q = 0
for i = long to 1 step -1
// {Work backwards}
x = 10*a(i-1) + q*i
a(i-1) = mod(x, (2*i - 1))
q = int(x / (2*i - 1))
next i
a(0) = mod(q, 10)
q = int(q / 10)
if q = 9 then
nines = nines + 1
else
if q = 10 then
d = predigit+1
gosub outputd
if nines > 0 then
for k = 1 to nines
d = 0
gosub outputd
next k
end if
predigit = 0
nines = 0
else
d = predigit
gosub outputd
predigit = q
if nines <> 0 then
for k = 1 to nines
d = 9
gosub outputd
next k
nines = 0
end if
end if
end if
next j
print predigit
end
label outputd
if needdecimal then
if d = 0 then return : fi
print d;
print ".";
needdecimal = 0 //false
else
print "", d;
endif
return |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PL.2FI | PL/I | perfect: procedure (n) returns (bit(1));
declare n fixed;
declare sum fixed;
declare i fixed binary;
sum = 0;
do i = 1 to n-1;
if mod(n, i) = 0 then sum = sum + i;
end;
return (sum=n);
end perfect; |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PL.2FM | PL/M | 100H: /* FIND SOME PERFECT NUMBERS: NUMBERS EQUAL TO THE SUM OF THEIR PROPER */
/* DIVISORS */
/* CP/M SYSTEM CALL AND I/O ROUTINES */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* TASK */
/* RETURNS TRUE IF N IS PERFECT, 0 OTHERWISE */
IS$PERFECT: PROCEDURE( N )BYTE;
DECLARE N ADDRESS;
DECLARE ( F1, F2, SUM ) ADDRESS;
SUM = 1;
F1 = 2;
F2 = N;
DO WHILE( F1 * F1 <= N );
IF N MOD F1 = 0 THEN DO;
SUM = SUM + F1;
F2 = N / F1;
/* AVOID COUNTING E.G., 2 TWICE AS A FACTOR OF 4 */
IF F2 > F1 THEN SUM = SUM + F2;
END;
F1 = F1 + 1;
END;
RETURN SUM = N;
END IS$PERFECT ;
/* TEST IS$PERFECT */
DECLARE N ADDRESS;
DO N = 2 TO 10$000;
IF IS$PERFECT( N ) THEN DO;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( N );
END;
END;
EOF |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Maxima | Maxima | next_permutation(v) := block([n, i, j, k, t],
n: length(v), i: 0,
for k: n - 1 thru 1 step -1 do (if v[k] < v[k + 1] then (i: k, return())),
j: i + 1, k: n,
while j < k do (t: v[j], v[j]: v[k], v[k]: t, j: j + 1, k: k - 1),
if i = 0 then return(false),
j: i + 1,
while v[j] < v[i] do j: j + 1,
t: v[j], v[j]: v[i], v[i]: t,
true
)$
print_perm(n) := block([v: makelist(i, i, 1, n)],
disp(v),
while next_permutation(v) do disp(v)
)$
print_perm(3);
/* [1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1] */ |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #zkl | zkl | var [const] BN=Import("zklBigNum"),
one=BN(1), two=BN(2), three=BN(3), four=BN(4), seven=BN(7), ten=BN(10);
fcn calcPiDigits{
reg q=BN(1), r=BN(0), t=BN(1), k=BN(1), n=BN(3), l=BN(3);
first:=True; N:=0;
while(True){ if((N+=1)==1000){ GarbageMan.collect(); N=0; } // take a deep breath ...
if(four*q + r - t < n*t){
n.print(); if(first){ print("."); first=False; }
nr:=(r - n*t).mul(ten); // 10 * (r - n * t);
n=(three*q).add(r).mul(ten) // ((10*(3*q + r))/t) - 10*n;
.div(t).sub(ten*n);
q.mul(ten); // q *= 10;
r=nr;
}else{
nr:=(two*q).add(r).mul(l); // (2*q + r)*l;
nn:=(q*seven).mul(k).add(two) // (q*(7*k + 2) + r*l)/(t*l);
.add(r*l).div(t*l);
q.mul(k); t.mul(l); // q*=k; t*=l;
l.add(two); k.add(one); // l+=2; k++;
n=nn; r=nr;
}
}
}(); |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PowerShell | PowerShell | Function IsPerfect($n)
{
$sum=0
for($i=1;$i-lt$n;$i++)
{
if($n%$i -eq 0)
{
$sum += $i
}
}
return $sum -eq $n
}
Returns "True" if the given number is perfect and "False" if it's not. |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Prolog | Prolog | tt_divisors(X, N, TT) :-
Q is X / N,
( 0 is X mod N -> (Q = N -> TT1 is N + TT;
TT1 is N + Q + TT);
TT = TT1),
( sqrt(X) > N + 1 -> N1 is N+1, tt_divisors(X, N1, TT1);
TT1 = X).
perfect(X) :-
tt_divisors(X, 2, 1).
perfect_numbers(N, L) :-
numlist(2, N, LN),
include(perfect, LN, L). |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE REALPTR="CARD"
TYPE PointR=[REALPTR x,y]
INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234 236 237 239 241 242 243 245 246 247 248
249 250 251 252 253 254 254 255 255 255 256 256 256 256]
INT FUNC Sin(INT a)
WHILE a<0 DO a==+360 OD
WHILE a>360 DO a==-360 OD
IF a<=90 THEN
RETURN (SinTab(a))
ELSEIF a<=180 THEN
RETURN (SinTab(180-a))
ELSEIF a<=270 THEN
RETURN (-SinTab(a-180))
ELSE
RETURN (-SinTab(360-a))
FI
RETURN (0)
INT FUNC Cos(INT a)
RETURN (Sin(a-90))
PROC Det(REAL POINTER x1,y1,x2,y2,res)
REAL tmp1,tmp2
RealMult(x1,y2,tmp1)
RealMult(y1,x2,tmp2)
RealSub(tmp1,tmp2,res)
RETURN
BYTE FUNC IsZero(REAL POINTER a)
CHAR ARRAY s(10)
StrR(a,s)
IF s(0)=1 AND s(1)='0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC Intersection(PointR POINTER p1,p2,p3,p4,res)
REAL det1,det2,dx1,dx2,dy1,dy2,nom,denom
Det(p1.x,p1.y,p2.x,p2.y,det1)
Det(p3.x,p3.y,p4.x,p4.y,det2)
RealSub(p1.x,p2.x,dx1)
RealSub(p1.y,p2.y,dy1)
RealSub(p3.x,p4.x,dx2)
RealSub(p3.y,p4.y,dy2)
Det(dx1,dy1,dx2,dy2,denom)
IF IsZero(denom) THEN
RETURN (0)
FI
Det(det1,dx1,det2,dx2,nom)
RealDiv(nom,denom,res.x)
Det(det1,dy1,det2,dy2,nom)
RealDiv(nom,denom,res.y)
RETURN (1)
PROC FloodFill(BYTE x0,y0)
BYTE ARRAY xs(300),ys(300)
INT first,last
first=0 last=0
xs(first)=x0
ys(first)=y0
WHILE first<=last
DO
x0=xs(first) y0=ys(first)
first==+1
IF Locate(x0,y0)=0 THEN
Plot(x0,y0)
IF Locate(x0-1,y0)=0 THEN
last==+1 xs(last)=x0-1 ys(last)=y0
FI
IF Locate(x0+1,y0)=0 THEN
last==+1 xs(last)=x0+1 ys(last)=y0
FI
IF Locate(x0,y0-1)=0 THEN
last==+1 xs(last)=x0 ys(last)=y0-1
FI
IF Locate(x0,y0+1)=0 THEN
last==+1 xs(last)=x0 ys(last)=y0+1
FI
FI
OD
RETURN
PROC Pentagram(INT x0,y0,r,a0 BYTE c1,c2)
INT ARRAY xs(16),ys(16)
INT angle
BYTE i
PointR p1,p2,p3,p4,p
REAL p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y,px,py
p1.x=p1x p1.y=p1y
p2.x=p2x p2.y=p2y
p3.x=p3x p3.y=p3y
p4.x=p4x p4.y=p4y
p.x=px p.y=py
;outer points
angle=a0
FOR i=0 TO 4
DO
xs(i)=r*Sin(angle)/256+x0
ys(i)=r*Cos(angle)/256+y0
angle==+144
OD
;intersection points
FOR i=0 TO 4
DO
IntToReal(xs(i MOD 5),p1x)
IntToReal(ys(i MOD 5),p1y)
IntToReal(xs((1+i) MOD 5),p2x)
IntToReal(ys((1+i) MOD 5),p2y)
IntToReal(xs((2+i) MOD 5),p3x)
IntToReal(ys((2+i) MOD 5),p3y)
IntToReal(xs((3+i) MOD 5),p4x)
IntToReal(ys((3+i) MOD 5),p4y)
Intersection(p1,p2,p3,p4,p)
xs(5+i)=RealToInt(px)
ys(5+i)=RealToInt(py)
OD
;centers of triangles
FOR i=0 TO 4
DO
xs(10+i)=(xs(i)+xs(5+i)+xs(5+(i+2) MOD 5))/3
ys(10+i)=(ys(i)+ys(5+i)+ys(5+(i+2) MOD 5))/3
OD
;center of pentagon
xs(15)=0 ys(15)=0
FOR i=5 TO 9
DO
xs(15)==+xs(i)
ys(15)==+ys(i)
OD
xs(15)==/5 ys(15)==/5
;draw lines
COLOR=c1
FOR i=0 TO 5
DO
IF i=0 THEN
Plot(xs(i MOD 5),ys(i MOD 5))
ELSE
DrawTo(xs(i MOD 5),ys(i MOD 5))
FI
OD
;fill
COLOR=c2
FOR i=10 TO 15
DO
FloodFill(xs(i),ys(i))
OD
RETURN
PROC Main()
BYTE CH=$02FC
Graphics(7+16)
SetColor(0,8,4)
SetColor(1,8,8)
SetColor(2,8,12)
Pentagram(40,48,40,0,1,2)
Pentagram(119,48,40,15,2,3)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Mercury | Mercury |
:- module permutations2.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- import_module list.
:- import_module set_ordlist.
:- import_module set.
:- import_module solutions.
%% permutationSet(List, Set) is true if List is a permutation of Set:
:- pred permutationSet(list(A)::out,set(A)::in) is nondet.
%% Two ways to compute all permutations of a given list (using backtracking):
:- func all_permutations1(list(int))=set_ordlist.set_ordlist(list(int)).
:- func all_permutations2(list(int))=set_ordlist.set_ordlist(list(int)).
:- implementation.
permutationSet([],set.init).
permutationSet([H|T], S) :- set.member(H,S), permutationSet(T,set.delete(S,H)).
all_permutations1(L) =
solutions_set(pred(X::out) is nondet:-permutationSet(X,set.from_list(L))).
%%Alternatively, using the imported list.perm predicate:
all_permutations2(L) =
solutions_set(pred(X::out) is nondet:-perm(L,X)).
main(!IO) :-
print(all_permutations1([1,2,3,4]),!IO),
nl(!IO),
print(all_permutations2([1,2,3,4]),!IO).
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #PureBasic | PureBasic | Procedure is_Perfect_number(n)
Protected summa, i=1, result=#False
Repeat
If Not n%i
summa+i
EndIf
i+1
Until i>=n
If summa=n
result=#True
EndIf
ProcedureReturn result
EndProcedure |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Python | Python | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Ada | Ada | with Ada.Numerics.Elementary_Functions;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Rectangles;
with SDL.Events.Events;
procedure Pentagram is
Width : constant := 600;
Height : constant := 600;
Offset : constant := 300.0;
Radius : constant := 250.0;
use SDL.Video.Rectangles;
use SDL.C;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
type Node_Id is mod 5;
Nodes : array (Node_Id) of Point;
procedure Calculate is
use Ada.Numerics.Elementary_Functions;
begin
for I in Nodes'Range loop
Nodes (I) := (X => int (Offset + Radius * Sin (Float (I), Cycle => 5.0)),
Y => int (Offset - Radius * Cos (Float (I), Cycle => 5.0)));
end loop;
end Calculate;
function Orient_2D (A, B, C : Point) return int is
((B.X - A.X) * (C.Y - A.Y) - (B.Y - A.Y) * (C.X - A.X));
procedure Fill is
Count : Natural;
begin
for Y in int (Offset - Radius) .. int (Offset + Radius) loop
for X in int (Offset - Radius) .. int (Offset + Radius) loop
Count := 0;
for Node in Nodes'Range loop
Count := Count +
(if Orient_2D (Nodes (Node), Nodes (Node + 2), (X, Y)) > 0 then 1 else 0);
end loop;
if Count in 4 .. 5 then
Renderer.Draw (Point => (X, Y));
end if;
end loop;
end loop;
end Fill;
procedure Draw_Outline is
begin
for Node in Nodes'Range loop
Renderer.Draw (Line => (Nodes (Node), Nodes (Node + 2)));
end loop;
end Draw_Outline;
procedure Wait is
use type SDL.Events.Event_Types;
begin
loop
SDL.Events.Events.Wait (Event);
exit when Event.Common.Event_Type = SDL.Events.Quit;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Pentagram",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Calculate;
Renderer.Set_Draw_Colour ((50, 50, 150, 255));
Fill;
Renderer.Set_Draw_Colour ((0, 220, 0, 255));
Draw_Outline;
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Pentagram; |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Microsoft_Small_Basic | Microsoft Small Basic | 'Permutations - sb
n=4
printem = "True"
For i = 1 To n
p[i] = i
EndFor
count = 0
Last = "False"
While Last = "False"
If printem Then
For t = 1 To n
TextWindow.Write(p[t])
EndFor
TextWindow.WriteLine("")
EndIf
count = count + 1
Last = "True"
i = n - 1
While i > 0
If p[i] < p[i + 1] Then
Last = "False"
Goto exitwhile
EndIf
i = i - 1
EndWhile
exitwhile:
j = i + 1
k = n
While j < k
t = p[j]
p[j] = p[k]
p[k] = t
j = j + 1
k = k - 1
EndWhile
j = n
While p[j] > p[i]
j = j - 1
EndWhile
j = j + 1
t = p[i]
p[i] = p[j]
p[j] = t
EndWhile
TextWindow.WriteLine("Number of permutations: "+count) |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Quackery | Quackery | [ 0 swap witheach + ] is sum ( [ --> n )
[ factors -1 pluck dip sum = ] is perfect ( n --> n )
say "Perfect numbers less than 10000:" cr
10000 times
[ i^ 1+ perfect if [ i^ 1+ echo cr ] ]
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #R | R | is.perf <- function(n){
if (n==0|n==1) return(FALSE)
s <- seq (1,n-1)
x <- n %% s
m <- data.frame(s,x)
out <- with(m, s[x==0])
return(sum(out)==n)
}
# Usage - Warning High Memory Usage
is.perf(28)
sapply(c(6,28,496,8128,33550336),is.perf) |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Applesoft_BASIC | Applesoft BASIC | 100 XO = 140
110 YO = 96
120 S = 90
130 B = 7
140 F = 6
150 C = 4
200 POKE 230,64
210 HCOLOR= B
220 HPLOT 0,0
230 CALL 62454
240 A = 49232
250 I = PEEK (A + 7) + PEEK (A + 2)
260 I = PEEK (A + 5) + PEEK (A)
300 SX = S
310 SY = S
320 PI = 3.1415926535
330 E = PI * 4
340 S = PI / 1.25
350 X = SIN (0)
360 Y = COS (0)
370 HCOLOR= F
380 PX = XO + X * SX
390 PY = YO - Y * SY
400 FOR I = 0 TO E STEP S
410 X = SIN (I)
420 Y = COS (I)
430 FOR J = 0 TO SX
440 HPLOT PX,PY TO XO + X * J,YO - Y * J
450 NEXT J
460 PX = XO + X * SX
470 PY = YO - Y * SY
480 NEXT I
500 HCOLOR= C
510 PX = XO + X * SX
520 PY = YO - Y * SY
600 FOR I = S TO E STEP S
610 X = SIN (I)
620 Y = COS (I)
630 HPLOT PX,PY TO XO + X * SX,YO - Y * SY
640 HPLOT PX + 1,PY TO XO + X * SX + 1,YO - Y * SY
650 HPLOT PX,PY + 1 TO XO + X * SX,YO - Y * SY + 1
660 HPLOT PX + 1,PY + 1 TO XO + X * SX + 1,YO - Y * SY + 1
670 PX = XO + X * SX
680 PY = YO - Y * SY
690 NEXT I |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #AutoHotkey | AutoHotkey |
#Include Gdip.ahk ; https://autohotkey.com/boards/viewtopic.php?f=6&t=6517
Width :=A_ScreenWidth, Height := A_ScreenHeight
Gui, 1: +E0x20 +Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs
Gui, 1: Show, NA
hwnd1 := WinExist()
OnExit, Exit
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start.
. Please ensure you have gdiplus on your system
ExitApp
}
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
pBrush := Gdip_BrushCreateSolid(0xFF6495ED)
pPen := Gdip_CreatePen(0xff000000, 3)
;---------------------------------
LL := 165
Cx := Floor(A_ScreenWidth/2)
Cy := Floor(A_ScreenHeight/2)
phi := 54
;---------------------------------
loop, 5
{
theta := abs(180-144-phi)
p1x := Floor(Cx + LL * Cos(phi * 0.01745329252))
p1y := Floor(Cy + LL * Sin(phi * 0.01745329252))
p2x := Floor(Cx - LL * Cos(theta * 0.01745329252))
p2y := Floor(Cy - LL * Sin(theta * 0.01745329252))
phi+= 72
Gdip_FillPolygon(G, pBrush, p1x "," p1y "|" Cx "," Cy "|" p2x "," p2y)
}
loop, 5
{
theta := abs(180-144-phi)
p1x := Floor(Cx + LL * Cos(phi * 0.01745329252))
p1y := Floor(Cy + LL * Sin(phi * 0.01745329252))
p2x := Floor(Cx - LL * Cos(theta * 0.01745329252))
p2y := Floor(Cy - LL * Sin(theta * 0.01745329252))
phi+= 72
Gdip_DrawLines(G, pPen, p1x "," p1y "|" p2x "," p2y ) ; "|" Cx "," Cy )
}
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
Gdip_DeleteBrush(pBrush)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
return
;----------------------------------------------------------------------
Esc::
Exit:
Gdip_Shutdown(pToken)
ExitApp
Return |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Modula-2 | Modula-2 | MODULE Permute;
FROM Terminal
IMPORT Read, Write, WriteLn;
FROM Terminal2
IMPORT WriteString;
CONST MAXIDX = 6;
MINIDX = 1;
TYPE TInpCh = ['a'..'z'];
TChr = SET OF TInpCh;
VAR n,
nl: INTEGER;
ch: CHAR;
a: ARRAY[MINIDX..MAXIDX] OF CHAR;
kt: TChr = TChr{'a'..'f'};
PROCEDURE output;
VAR i: INTEGER;
BEGIN
FOR i := MINIDX TO n DO Write(a[i]) END;
WriteString(" | ");
END output;
PROCEDURE exchange(VAR x, y : CHAR);
VAR z: CHAR;
BEGIN z := x; x := y; y := z
END exchange;
PROCEDURE permute(k: INTEGER);
VAR i: INTEGER;
BEGIN
IF k = 1 THEN
output;
INC(nl);
IF (nl MOD 8 = 1) THEN WriteLn END;
ELSE
permute(k-1);
FOR i := MINIDX TO k-1 DO
exchange(a[i], a[k]);
permute(k-1);
exchange(a[i], a[k]);
END
END
END permute;
BEGIN
n := 0; nl := 1; WriteString("Input {a,b,c,d,e,f} >");
REPEAT
Read(ch);
IF ch IN kt THEN INC(n); a[n] := ch; Write(ch) END
UNTIL (ch <= " ") OR (n > MAXIDX);
WriteLn;
IF n > 0 THEN permute(n) END;
(*Wait*)
END Permute. |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Racket | Racket | #lang racket
(require math)
(define (perfect? n)
(=
(* n 2)
(sum (divisors n))))
; filtering to only even numbers for better performance
(filter perfect? (filter even? (range 1e5)))
;-> '(0 6 28 496 8128) |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Raku | Raku | sub is-perf($n) { $n == [+] grep $n %% *, 1 .. $n div 2 }
# used as
put ((1..Inf).hyper.grep: {.&is-perf})[^4]; |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #C | C | #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Modula-3 | Modula-3 | MODULE Permutations EXPORTS Main;
IMPORT IO, IntSeq;
CONST n = 3;
TYPE Domain = SET OF [ 1.. n ];
VAR
chosen: IntSeq.T;
values := Domain { };
PROCEDURE GeneratePermutations(VAR chosen: IntSeq.T; remaining: Domain) =
(*
Recursively generates all the permutations of elements
in the union of "chosen" and "values".
Values in "chosen" have already been chosen;
values in "remaining" can still be chosen.
If "remaining" is empty, it prints the sequence and returns.
Otherwise, it picks each element in "remaining", removes it,
adds it to "chosen", recursively calls itself,
then removes the last element of "chosen" and adds it back to "remaining".
*)
BEGIN
FOR i := 1 TO n DO
(* check if each element is in "remaining" *)
IF i IN remaining THEN
(* if so, remove from "remaining" and add to "chosen" *)
remaining := remaining - Domain { i };
chosen.addhi(i);
IF remaining # Domain { } THEN
(* still something to process? do it *)
GeneratePermutations(chosen, remaining);
ELSE
(* otherwise, print what we've chosen *)
FOR j := 0 TO chosen.size() - 2 DO
IO.PutInt(chosen.get(j)); IO.Put(", ");
END;
IO.PutInt(chosen.gethi());
IO.PutChar('\n');
END;
(* add "i" back to "remaining" and remove from "chosen" *)
remaining := remaining + Domain { i };
EVAL chosen.remhi();
END;
END;
END GeneratePermutations;
BEGIN
(* initial setup *)
chosen := NEW(IntSeq.T).init(n);
FOR i := 1 TO n DO values := values + Domain { i }; END;
GeneratePermutations(chosen, values);
END Permutations. |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #REBOL | REBOL | perfect?: func [n [integer!] /local sum] [
sum: 0
repeat i (n - 1) [
if zero? remainder n i [
sum: sum + i
]
]
sum = n
] |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #REXX | REXX | /*REXX version of the ooRexx program (the code was modified to run with Classic REXX).*/
do i=1 to 10000 /*statement changed: LOOP ──► DO*/
if perfectNumber(i) then say i "is a perfect number"
end
exit
perfectNumber: procedure; parse arg n /*statements changed: ROUTINE,USE*/
sum=0
do i=1 to n%2 /*statement changed: LOOP ──► DO*/
if n//i==0 then sum=sum+i /*statement changed: sum += i */
end
return sum=n |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Delphi | Delphi |
unit Main;
interface
uses
Winapi.Windows, Vcl.Graphics, Vcl.Forms, System.Math;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
procedure DrawPentagram(len, x, y: Integer; fill, stoke: TColor);
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
degrees144: double;
degrees72: double;
degrees18: double;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientHeight := 640;
ClientWidth := 640;
degrees144 := DegToRad(144);
degrees72 := DegToRad(72);
degrees18 := DegToRad(18);
end;
procedure CreatePolygon(len, x, y, n: integer; ang: double; var points: TArray<TPoint>);
var
angle: Double;
index, i, x2, y2: Integer;
begin
angle := 0;
index := 0;
SetLength(points, n + 1);
points[index].Create(x, y);
for i := 1 to n do
begin
x2 := x + round(len * cos(angle));
y2 := y + round(len * sin(-angle));
x := x2;
y := y2;
angle := angle - ang;
points[index].Create(x2, y2);
inc(index);
end;
points[index].Create(points[0]);
end;
procedure TForm1.DrawPentagram(len, x, y: Integer; fill, stoke: TColor);
var
points, points_internal: TArray<TPoint>;
L, H: Integer;
begin
// Calc of sides for draw internal pollygon
// 2H+L = len -> 2H = len - L
// L = 2H*sin(36/2) (Pythagorean theorem)
// L = (len-L)sin(18)
// L = len*sin(18)/[1+sin(18)]
L := round(len * sin(degrees18) / (1 + sin(degrees18)));
// H = (len - L)/2
H := (len - L) div 2;
CreatePolygon(L, x + H, y, 5, degrees72, points_internal);
CreatePolygon(len, x, y, 5, degrees144, points);
with Canvas, Canvas.Brush do
begin
with pen do
begin
Color := stoke;
Style := psSolid;
Width := 5;
end;
Color := fill;
Polygon(points_internal);
Polygon(points);
end;
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
with Canvas, Brush do
begin
Style := bsSolid;
Color := clWhite;
// fill background with white
FillRect(ClientRect);
end;
drawPentagram(500, 70, 250, $ED9564, clDkGray);
end;
end. |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
import java.util.List
import java.util.ArrayList
-- =============================================================================
/**
* Permutation Iterator
* <br />
* <br />
* Algorithm by E. W. Dijkstra, "A Discipline of Programming", Prentice-Hall, 1976, p.71
*/
class RPermutationIterator implements Iterator
-- ---------------------------------------------------------------------------
properties indirect
perms = List
permOrders = int[]
maxN
currentN
first = boolean
-- ---------------------------------------------------------------------------
properties constant
isTrue = boolean (1 == 1)
isFalse = boolean (1 \= 1)
-- ---------------------------------------------------------------------------
method RPermutationIterator(initial = List) public
setUp(initial)
return
-- ---------------------------------------------------------------------------
method RPermutationIterator(initial = Object[]) public
init = ArrayList(initial.length)
loop elmt over initial
init.add(elmt)
end elmt
setUp(init)
return
-- ---------------------------------------------------------------------------
method RPermutationIterator(initial = Rexx[]) public
init = ArrayList(initial.length)
loop elmt over initial
init.add(elmt)
end elmt
setUp(init)
return
-- ---------------------------------------------------------------------------
method setUp(initial = List) private
setFirst(isTrue)
setPerms(initial)
setPermOrders(int[getPerms().size()])
setMaxN(getPermOrders().length)
setCurrentN(0)
po = getPermOrders()
loop i_ = 0 while i_ < po.length
po[i_] = i_
end i_
return
-- ---------------------------------------------------------------------------
method hasNext() public returns boolean
status = isTrue
if getCurrentN() == factorial(getMaxN()) then status = isFalse
setCurrentN(getCurrentN() + 1)
return status
-- ---------------------------------------------------------------------------
method next() public returns Object
if isFirst() then setFirst(isFalse)
else do
po = getPermOrders()
i_ = getMaxN() - 1
loop while po[i_ - 1] >= po[i_]
i_ = i_ - 1
end
j_ = getMaxN()
loop while po[j_ - 1] <= po[i_ - 1]
j_ = j_ - 1
end
swap(i_ - 1, j_ - 1)
i_ = i_ + 1
j_ = getMaxN()
loop while i_ < j_
swap(i_ - 1, j_ - 1)
i_ = i_ + 1
j_ = j_ - 1
end
end
return reorder()
-- ---------------------------------------------------------------------------
method remove() public signals UnsupportedOperationException
signal UnsupportedOperationException()
-- ---------------------------------------------------------------------------
method swap(i_, j_) private
po = getPermOrders()
save = po[i_]
po[i_] = po[j_]
po[j_] = save
return
-- ---------------------------------------------------------------------------
method reorder() private returns List
result = ArrayList(getPerms().size())
loop ix over getPermOrders()
result.add(getPerms().get(ix))
end ix
return result
-- ---------------------------------------------------------------------------
/**
* Calculate n factorial: {@code n! = 1 * 2 * 3 .. * n}
* @param n
* @return n!
*/
method factorial(n) public static
fact = 1
if n > 1 then loop i = 1 while i <= n
fact = fact * i
end i
return fact
-- ---------------------------------------------------------------------------
method main(args = String[]) public static
thing02 = RPermutationIterator(['alpha', 'omega'])
thing03 = RPermutationIterator([String 'one', 'two', 'three'])
thing04 = RPermutationIterator(Arrays.asList([Integer(1), Integer(2), Integer(3), Integer(4)]))
things = [thing02, thing03, thing04]
loop thing over things
N = thing.getMaxN()
say 'Permutations:' N'! =' factorial(N)
loop lineCount = 1 while thing.hasNext()
prm = thing.next()
say lineCount.right(8)':' prm.toString()
end lineCount
say 'Permutations:' N'! =' factorial(N)
say
end thing
return
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Ring | Ring |
for i = 1 to 10000
if perfect(i) see i + nl ok
next
func perfect n
sum = 0
for i = 1 to n - 1
if n % i = 0 sum = sum + i ok
next
if sum = n return 1 else return 0 ok
return sum
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Ruby | Ruby | def perf(n)
sum = 0
for i in 1...n
sum += i if n % i == 0
end
sum == n
end |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #EasyLang | EasyLang | xp = 10
yp = 40
linewidth 2
move xp yp
while angle > -720
x = xp + cos angle * 80
y = yp + sin -angle * 80
line x y
f[] &= x
f[] &= y
xp = x
yp = y
angle -= 144
.
color 900
polygon f[] |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1) // White
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED") // Cornflower Blue
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0) // Black
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Nim | Nim | import algorithm
var v = [1, 2, 3] # List has to start sorted
echo v
while v.nextPermutation():
echo v |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Run_BASIC | Run BASIC | for i = 1 to 10000
if perf(i) then print i;" ";
next i
FUNCTION perf(n)
for i = 1 TO n - 1
IF n MOD i = 0 THEN sum = sum + i
next i
IF sum = n THEN perf = 1
END FUNCTION |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Rust | Rust |
fn main ( ) {
fn factor_sum(n: i32) -> i32 {
let mut v = Vec::new(); //create new empty array
for x in 1..n-1 { //test vaules 1 to n-1
if n%x == 0 { //if current x is a factor of n
v.push(x); //add x to the array
}
}
let mut sum = v.iter().sum(); //iterate over array and sum it up
return sum;
}
fn perfect_nums(n: i32) {
for x in 2..n { //test numbers from 1-n
if factor_sum(x) == x {//call factor_sum on each value of x, if return value is = x
println!("{} is a perfect number.", x); //print value of x
}
}
}
perfect_nums(10000);
}
|
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for n = {61, 109, 181, 277}.
See also
Wikipedia entry: Pell's equation.
| #11l | 11l | F solvePell(n)
V x = Int(sqrt(n))
V (y, z, r) = (x, 1, x << 1)
BigInt e1 = 1
BigInt e2 = 0
BigInt f1 = 0
BigInt f2 = 1
L
y = r * z - y
z = (n - y * y) I/ z
r = (x + y) I/ z
(e1, e2) = (e2, e1 + e2 * r)
(f1, f2) = (f2, f1 + f2 * r)
V (a, b) = (f2 * x + e2, f2)
I a * a - n * b * b == 1
R (a, b)
L(n) [61, 109, 181, 277]
V (x, y) = solvePell(n)
print(‘x^2 - #3 * y^2 = 1 for x = #27 and y = #25’.format(n, x, y)) |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Haskell | Haskell | pentagram -w 400 -o pentagram_hs.svg
|
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Pentagra.bas"
110 OPTION ANGLE DEGREES
120 GRAPHICS HIRES 4
130 SET PALETTE BLUE,CYAN,YELLOW,BLACK
140 PLOT 640,700,ANGLE 288;
150 FOR I=1 TO 5
160 PLOT FORWARD 700,RIGHT 144;
170 NEXT
180 SET INK 3
190 SET BEAM OFF:PLOT 0,0,PAINT |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #OCaml | OCaml | (* Iterative, though loops are implemented as auxiliary recursive functions.
Translation of Ada version. *)
let next_perm p =
let n = Array.length p in
let i = let rec aux i =
if (i < 0) || (p.(i) < p.(i+1)) then i
else aux (i - 1) in aux (n - 2) in
let rec aux j k = if j < k then
let t = p.(j) in
p.(j) <- p.(k);
p.(k) <- t;
aux (j + 1) (k - 1)
else () in aux (i + 1) (n - 1);
if i < 0 then false else
let j = let rec aux j =
if p.(j) > p.(i) then j
else aux (j + 1) in aux (i + 1) in
let t = p.(i) in
p.(i) <- p.(j);
p.(j) <- t;
true;;
let print_perm p =
let n = Array.length p in
for i = 0 to n - 2 do
print_int p.(i);
print_string " "
done;
print_int p.(n - 1);
print_newline ();;
let print_all_perm n =
let p = Array.init n (function i -> i + 1) in
print_perm p;
while next_perm p do
print_perm p
done;;
print_all_perm 3;;
(* 1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1 *) |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #SASL | SASL |
|| The function which takes a number and returns a list of its factors (including one but excluding itself)
|| can be written
factors n = { a <- 1.. n/2; n rem a = 0 }
|| If we define a perfect number as one which is equal to the sum of its factors (for example 6 = 3 + 2 + 1 is perfect)
|| we can write the list of all perfect numbers as
perfects = { n <- 1... ; n = sum(factors n) }
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #S-BASIC | S-BASIC |
$lines
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)
rem - return true if n is perfect, otherwise false
function isperfect(n = integer) = integer
var sum, f1, f2 = integer
sum = 1
f1 = 2
while (f1 * f1) <= n do
begin
if mod(n, f1) = 0 then
begin
sum = sum + f1
f2 = n / f1
if f2 > f1 then sum = sum + f2
end
f1 = f1 + 1
end
end = (sum = n)
rem - exercise the function
var k, found = integer
print "Searching up to"; search_limit; " for perfect numbers ..."
found = 0
for k = 2 to search_limit
if isperfect(k) then
begin
print k
found = found + 1
end
next k
print found; " were found"
end
|
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for n = {61, 109, 181, 277}.
See also
Wikipedia entry: Pell's equation.
| #Ada | Ada | with Ada.Text_Io;
with Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Big_Numbers.Big_Integers;
procedure Pells_Equation is
use Ada.Numerics.Big_Numbers.Big_Integers;
type Pair is
record
V1, V2 : Big_Integer;
end record;
procedure Solve_Pell (N : Natural; X, Y : out Big_Integer) is
use Ada.Numerics.Elementary_Functions;
Big_N : constant Big_Integer := To_Big_Integer (N);
XX : constant Big_Integer := To_Big_Integer (Natural (Float'Floor (Sqrt (Float (N)))));
begin
if XX**2 = Big_N then
X := 1; Y := 0;
return;
end if;
declare
YY : Big_Integer := XX;
Z : Big_Integer := 1;
R : Big_Integer := 2 * XX;
E : Pair := Pair'(V1 => 1, V2 => 0);
F : Pair := Pair'(V1 => 0, V2 => 1);
begin
loop
YY := R * Z - YY;
Z := (Big_N - YY**2) / Z;
R := (XX + YY) / Z;
E := Pair'(V1 => E.V2, V2 => R * E.V2 + E.V1);
F := Pair'(V1 => F.V2, V2 => R * F.V2 + F.V1);
X := E.V2 + XX * F.V2;
Y := F.V2;
exit when X**2 - Big_N * Y**2 = 1;
end loop;
end;
end Solve_Pell;
procedure Test (N : Natural) is
package Natural_Io is new Ada.Text_Io.Integer_Io (Natural);
use Ada.Text_Io, Natural_Io;
X, Y : Big_Integer;
begin
Solve_Pell (N, X => X, Y => Y);
Put ("X**2 - ");
Put (N, Width => 3);
Put (" * Y**2 = 1 for X = ");
Put (To_String (X, Width => 22));
Put (" and Y = ");
Put (To_String (Y, Width => 20));
New_Line;
end Test;
begin
Test (61);
Test (109);
Test (181);
Test (277);
end Pells_Equation; |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #J | J | require'plot'
plot j./2 1 o./180p_1 %~ 144*i. 6 |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
| #Java | Java | import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ooRexx | ooRexx |
/* REXX Compute bunch permutations of things elements */
Parse Arg bunch things
If bunch='?' Then
Call help
If bunch=='' Then bunch=3
If datatype(bunch)<>'NUM' Then Call help 'bunch ('bunch') must be numeric'
thing.=''
Select
When things='' Then things=bunch
When datatype(things)='NUM' Then Nop
Otherwise Do
data=things
things=words(things)
Do i=1 To things
Parse Var data thing.i data
End
End
End
If things<bunch Then Call help 'things ('things') must be >= bunch ('bunch')'
perms =0
Call time 'R'
Call permSets things, bunch
Say perms 'Permutations'
Say time('E') 'seconds'
Exit
/*--------------------------------------------------------------------------------------*/
first_word: return word(Arg(1),1)
/*--------------------------------------------------------------------------------------*/
permSets: Procedure Expose perms thing.
Parse Arg things,bunch
aa.=''
sep=''
perm_elements='123456789ABCDEF'
Do k=1 To things
perm=first_word(first_word(substr(perm_elements,k,1) k))
dd.k=perm
End
Call .permSet 1
Return
.permSet: Procedure Expose dd. aa. things bunch perms thing.
Parse Arg iteration
If iteration>bunch Then do
perm= aa.1
Do j=2 For bunch-1
perm= perm aa.j
End
perms+=1
If thing.1<>'' Then Do
ol=''
Do pi=1 To words(perm)
z=word(perm,pi)
If datatype(z)<>'NUM' Then
z=9+pos(z,'ABCDEF')
ol=ol thing.z
End
Say strip(ol)
End
Else
Say perm
End
Else Do
Do q=1 for things
Do k=1 for iteration-1
If aa.k==dd.q Then
iterate q
End
aa.iteration= dd.q
Call .permSet iteration+1
End
End
Return
help:
Parse Arg msg
If msg<>'' Then Do
Say 'ERROR:' msg
Say ''
End
Say 'rexx perm -> Permutations of 1 2 3 '
Say 'rexx perm 2 -> Permutations of 1 2 '
Say 'rexx perm 2 4 -> Permutations of 1 2 3 4 in 2 positions'
Say 'rexx perm 2 a b c d -> Permutations of a b c d in 2 positions'
Exit |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Scala | Scala | def perfectInt(input: Int) = ((2 to sqrt(input).toInt).collect {case x if input % x == 0 => x + input / x}).sum == input - 1 |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Scheme | Scheme | (define (perf n)
(let loop ((i 1)
(sum 0))
(cond ((= i n)
(= sum n))
((= 0 (modulo n i))
(loop (+ i 1) (+ sum i)))
(else
(loop (+ i 1) sum))))) |
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.