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/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.
#ALGOL_68
ALGOL 68
BEGIN # find solutions to Pell's eqauation: x^2 - ny^2 = 1 for integer x, y, n # MODE BIGINT = LONG LONG INT; MODE BIGPAIR = STRUCT( BIGINT v1, v2 ); PROC solve pell = ( INT n )BIGPAIR: IF INT x = ENTIER( sqrt( n ) ); x * x = n THEN # n is a erfect square - no solution otheg than 1,0 # BIGPAIR( 1, 0 ) ELSE # there are non-trivial solutions # INT y := x; INT z := 1; INT r := 2*x; BIGPAIR e := BIGPAIR( 1, 0 ); BIGPAIR f := BIGPAIR( 0, 1 ); BIGINT a := 0; BIGINT b := 0; WHILE y := (r*z - y); z := ENTIER ((n - y*y) / z); r := ENTIER ((x + y) / z); e := BIGPAIR( v2 OF e, r * v2 OF e + v1 OF e ); f := BIGPAIR( v2 OF f, r * v2 OF f + v1 OF f ); a := (v2 OF e + x*v2 OF f); b := v2 OF f; a*a - n*b*b /= 1 DO SKIP OD; BIGPAIR( a, b ) FI # solve pell # ; # task test cases # []INT nv = (61, 109, 181, 277); FOR i FROM LWB nv TO UPB nv DO INT n = nv[ i ]; BIGPAIR r = solve pell(n); print( ("x^2 - ", whole( n, -3 ), " * y^2 = 1 for x = ", whole( v1 OF r, -21), " and y = ", whole( v2 OF r, -21 ), newline ) ) OD 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
#jq
jq
# Input: {svg, minx, miny, maxx, maxy} def svg: # viewBox = <min-x> <min-y> <width> <height> "<svg viewBox='\(.minx - 4|floor) \(.miny - 4 |floor) \(6 + .maxx - .minx|ceil) \(6 + .maxy - .miny|ceil)'", " preserveAspectRatio='xMinYmin meet'", " xmlns='http://www.w3.org/2000/svg' >", .svg, "</svg>" ;   # Input: an array of [x,y] points def minmax: {minx: (map(.[0])|min), miny: (map(.[1])|min), maxx: (map(.[0])|max), maxy: (map(.[1])|max)} ;   # Input: an array of [x,y] points def Polyline($fill; $stroke; $transform): def rnd: 1000*.|round/1000; def linearize: map( map(rnd) | join(" ") ) | join(", ");   "<polyline points='" + linearize + "'\n style='fill:\($fill); stroke: \($stroke); stroke-width:3;'" + "\n transform='\($transform)' />" ;   # Output: {minx, miny, maxx, maxy, svg} def pentagram($dim): (8 * (1|atan)) as $tau | 5 as $sides | [ (0, 2, 4, 1, 3, 0) | [ 0.9 * $dim * (($tau * $v / $sides) | cos), 0.9 * $dim * (($tau * $v / $sides) | sin) ] ] | minmax + {svg: Polyline("seashell"; "blue"; "rotate(-18)" )} ;   pentagram(200) | 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
#Julia
Julia
using Luxor   function drawpentagram(path::AbstractString, w::Integer=1000, h::Integer=1000) Drawing(h, w, path) origin() setline(16)   # To get a different color border from the fill, draw twice, first with fill, then without. sethue("aqua") star(0, 0, 500, 5, 0.39, 3pi/10, :fill)   sethue("navy") verts = star(0, 0, 500, 5, 0.5, 3pi/10, vertices=true) poly([verts[i] for i in [1,5,9,3,7,1]], :stroke) finish() preview() end   drawpentagram("data/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
#OpenEdge.2FProgress
OpenEdge/Progress
  DEFINE VARIABLE charArray AS CHARACTER EXTENT 3 INITIAL ["A","B","C"]. DEFINE VARIABLE sizeofArray AS INTEGER.   sizeOfArray = EXTENT(charArray).   RUN GetPermutations(1).   PROCEDURE GetPermutations: DEFINE INPUT PARAMETER n AS INTEGER.   DEFINE VARIABLE i AS INTEGER. DEFINE VARIABLE j AS INTEGER. DEFINE VARIABLE currentPermutation AS CHARACTER.   REPEAT i = n TO sizeOfArray: RUN swapValues(i,n). RUN GetPermutations(n + 1). RUN swapValues(i,n). END. IF n = sizeOfArray THEN DO: DO j = 1 TO EXTENT(charArray): currentPermutation = currentPermutation + charArray[j]. END. DISPLAY currentPermutation WITH FRAME A DOWN. END. END PROCEDURE.   PROCEDURE swapValues: DEFINE INPUT PARAMETER a AS INTEGER. DEFINE INPUT PARAMETER b AS INTEGER. DEFINE VARIABLE temp AS CHARACTER. temp = charArray[a]. charArray[a] = charArray[b]. charArray[b] = temp. END PROCEDURE.
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: isPerfect (in integer: n) is func result var boolean: isPerfect is FALSE; local var integer: i is 0; var integer: sum is 1; var integer: q is 0; begin for i range 2 to sqrt(n) do if n rem i = 0 then sum +:= i; q := n div i; if q > i then sum +:= q; end if; end if; end for; isPerfect := sum = n; end func;   const proc: main is func local var integer: n is 0; begin for n range 2 to 33550336 do if isPerfect(n) then writeln(n); end if; end for; 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.
#Sidef
Sidef
func is_perfect(n) { n.sigma == 2*n }   for n in (1..10000) { say n if is_perfect(n) }
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.
#Arturo
Arturo
solvePell: function [n][ x: to :integer sqrt n [y, z, r]: @[x, 1, shl x 1] [e1, e2]: [1, 0] [f1, f2]: [0, 1]   while [true][ y: (r * z) - y z: (n - y * y) / z r: (x + y) / z   [e1, e2]: @[e2, e1 + e2 * r] [f1, f2]: @[f2, f1 + f2 * r] [a, b]: @[e2 + f2 * x, f2] if 1 = (a*a) - n*b*b -> return @[a, b] ] ]   loop [61 109 181 277] 'n [ [x, y]: solvePell n print ["x² -" n "* y² = 1 for (x,y) =" 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
#Kotlin
Kotlin
// version 1.1.2   import java.awt.* import java.awt.geom.Path2D import javax.swing.*   class Pentagram : JPanel() { init { preferredSize = Dimension(640, 640) background = Color.white }   private fun drawPentagram(g: Graphics2D, len: Int, x: Int, y: Int, fill: Color, stroke: Color) { var x2 = x.toDouble() var y2 = y.toDouble() var angle = 0.0 val p = Path2D.Float() p.moveTo(x2, y2)   for (i in 0..4) { x2 += Math.cos(angle) * len y2 += Math.sin(-angle) * len p.lineTo(x2, y2) angle -= Math.toRadians(144.0) }   p.closePath() with(g) { color = fill fill(p) color = stroke draw(p) } }   override fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.stroke = BasicStroke(5.0f, BasicStroke.CAP_ROUND, 0) drawPentagram(g, 500, 70, 250, Color(0x6495ED), Color.darkGray) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() with(f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Pentagram" isResizable = false add(Pentagram(), BorderLayout.CENTER) pack() setLocationRelativeTo(null) isVisible = 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
#PARI.2FGP
PARI/GP
vector(n!,k,numtoperm(n,k))
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.
#Simula
Simula
BOOLEAN PROCEDURE PERF(N); INTEGER N; BEGIN INTEGER SUM; FOR I := 1 STEP 1 UNTIL N-1 DO IF MOD(N, I) = 0 THEN SUM := SUM + I; PERF := SUM = N; END PERF;
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.
#Slate
Slate
n@(Integer traits) isPerfect [ (((2 to: n // 2 + 1) select: [| :m | (n rem: m) isZero]) inject: 1 into: #+ `er) = n ].
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.
#C
C
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   struct Pair { uint64_t v1, v2; };   struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; }   struct Pair solvePell(int n) { int x = (int) sqrt(n);   if (x * x == n) { // n is a perfect square - no solution other than 1,0 return makePair(1, 0); } else { // there are non-trivial solutions int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0;   while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } }   return makePair(a, b); } }   void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); }   int main() { test(61); test(109); test(181); test(277);   return 0; }
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
#Lua
Lua
local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi   function Bitmap:render() for y = 1, self.height do print(table.concat(self.pixels[y])) end end   function Bitmap:pentagram(x, y, radius, rotation, outlcolor, fillcolor) local function pxy(i) return x+radius*cos(i*pi*2/5+rotation), y+radius*sin(i*pi*2/5+rotation) end local x1, y1 = pxy(0) for i = 1, 5 do local x2, y2 = pxy(i*2) -- btw: pxy(i) ==> pentagon self:line(floor(x1*2), floor(y1), floor(x2*2), floor(y2), outlcolor) x1, y1 = x2, y2 end self:floodfill(floor(x*2), floor(y), fillcolor) radius = radius / 2 for i = 1, 5 do x1, y1 = pxy(i) self:floodfill(floor(x1*2), floor(y1), fillcolor) end end   bitmap = Bitmap(40*2,40) bitmap:clear(".") bitmap:pentagram(20, 22, 20, -pi/2, "@", '+') bitmap:render()
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
#Pascal
Pascal
program perm;   var p: array[1 .. 12] of integer; is_last: boolean; n: integer;   procedure next; var i, j, k, t: integer; begin is_last := true; i := n - 1; while i > 0 do begin if p[i] < p[i + 1] then begin is_last := false; break; end; i := i - 1; end;   if not is_last then begin j := i + 1; k := n; while j < k do begin t := p[j]; p[j] := p[k]; p[k] := t; j := j + 1; k := k - 1; end;   j := n; while p[j] > p[i] do j := j - 1; j := j + 1;   t := p[i]; p[i] := p[j]; p[j] := t; end; end;   procedure print; var i: integer; begin for i := 1 to n do write(p[i], ' '); writeln; end;   procedure init; var i: integer; begin n := 0; while (n < 1) or (n > 10) do begin write('Enter n (1 <= n <= 10): '); readln(n); end; for i := 1 to n do p[i] := i; end;   begin init; repeat print; next; until is_last; 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.
#Smalltalk
Smalltalk
Integer extend [   "Translation of the C version; this is faster..." isPerfectC [ |tot| tot := 1. (2 to: (self sqrt) + 1) do: [ :i | (self rem: i) = 0 ifTrue: [ |q| tot := tot + i. q := self // i. q > i ifTrue: [ tot := tot + q ] ] ]. ^ tot = self ]   "... but this seems more idiomatic" isPerfect [ ^ ( ( ( 2 to: self // 2 + 1) select: [ :a | (self rem: a) = 0 ] ) inject: 1 into: [ :a :b | a + b ] ) = self ] ].
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.
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <tuple>   std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n);   if (x * x == n) { // n is a perfect square - no solution other than 1,0 return std::make_pair(1, 0); }   // there are non-trivial solutions int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0;   while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } }   return std::make_pair(a, b); }   void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; }   int main() { test(61); test(109); test(181); test(277);   return 0; }
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
#Maple
Maple
with(geometry): RegularStarPolygon(middle, 5/2, point(c, 0, 0), 1): v := [seq(coordinates(i), i in DefinedAs(middle))]: pentagram := plottools[rotate](plottools[polygon](v), Pi/2): plots[display](pentagram, colour = yellow, axes = none);
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Graphics[{ EdgeForm[Directive[Thickness[0.01], RGBColor[0, 0, 1]]],(*Edge coloring*) RGBColor[0.5, 0.5, .50], (*Fill coloring*) Polygon[AnglePath[Table[6 Pi/5, 5]]]} ]
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
#Perl
Perl
sub permutation { my ($perm,@set) = @_; print "$perm\n" || return unless (@set); permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreach (0..$#set); } my @input = (qw/a b c d/); permutation('',@input);
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.
#Swift
Swift
func perfect(n:Int) -> Bool { var sum = 0 for i in 1..<n { if n % i == 0 { sum += i } } return sum == n }   for i in 1..<10000 { if perfect(i) { println(i) } }
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.
#Tcl
Tcl
proc perfect n { set sum 0 for {set i 1} {$i <= $n} {incr i} { if {$n % $i == 0} {incr sum $i} } expr {$sum == 2*$n} }
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.
#C.23
C#
using System; using System.Numerics;   static class Program { static void Fun(ref BigInteger a, ref BigInteger b, int c) { BigInteger t = a; a = b; b = b * c + t; }   static void SolvePell(int n, ref BigInteger a, ref BigInteger b) { int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1; BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x); if (a * a - n * b * b == 1) return; } }   static void Main() { BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 }) { SolvePell(n, ref x, ref y); Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", 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
#Nim
Nim
  import libgd from math import sin, cos, degToRad   const width = 500 height = width outerRadius = 200   proc main() =   proc calcPosition(x: int, y: int, radius: int, posAngle: float): (cint, cint) = var width = int(radius.float * sin(degToRad(posAngle))) var height = int(radius.float * cos(degToRad(posAngle))) return (cast[cint](x + width), cast[cint](y - height))   proc getPentagonPoints(startAngle = 0, radius: int): array[5, array[2, int]] = let spacingAngle = 360 / 5   var posAngle = (90 - startAngle).float   var n = 0 var points: array[5, array[2, int]] while n < 5: (points[n][0], points[n][1]) = calcPosition(250, 250, radius, posAngle) n += 1 posAngle -= spacingAngle   return points   let outerPentagon = getPentagonPoints(18, outerRadius) # rotate 18 degrees let innerPentagon = getPentagonPoints(54, int((cos(degToRad(72.0))/cos(degToRad(36.0))) * outerRadius)) # rotate 54 degrees   var pentagram: array[10, array[2, int]] var n = 0 for i in countup(0, 4): pentagram[n] = outerPentagon[i] inc(n) pentagram[n] = innerPentagon[i] inc(n)   withGd imageCreate(width, height) as img: discard img.setColor(255, 255, 255)   let black = img.setColor(0x404040) let blue = img.setColor(0x6495ed)   img.drawPolygon( points=pentagram, color=blue, fill=true, open=false)   img.setThickness(4)   img.drawPolygon( points=pentagram, color=black, fill=false, open=false)   img.drawPolygon( points=innerPentagon, color=black, fill=false, open=false)   let png_out = open("pentagram.png", fmWrite) img.writePng(png_out)   png_out.close()   main()  
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
#ooRexx
ooRexx
/* REXX *************************************************************** * Create a BMP file showing a pentagram **********************************************************************/ pentagram='pentagram.bmp' 'erase' pentagram s='424d4600000000000000360000002800000038000000280000000100180000000000'X s=s'1000000000000000000000000000000000000000'x Say 'sl='length(s) z.0=0 white='ffffff'x red ='00ff00'x green='ff0000'x blue ='0000ff'x rd6=copies(rd,6) m=133 m=80 n=80 hor=m*8 /* 56 */ ver=n*8 /* 40 */ Say 'hor='hor Say 'ver='ver Say 'sl='length(s) s=overlay(lend(hor),s,19,4) s=overlay(lend(ver),s,23,4) Say 'sl='length(s) z.=copies('ffffff'x,3192%3) z.=copies('ffffff'x,8*m) z.0=648 s72 =RxCalcsin(72,,'D') c72 =RxCalccos(72,,'D') s144=RxCalcsin(144,,'D') c144=RxCalccos(144,,'D') xm=300 ym=300 r=200 p.0x.1=xm p.0y.1=ym+r p.0x.2=format(xm+r*s72,3,0) p.0y.2=format(ym+r*c72,3,0) p.0x.3=format(xm+r*s144,3,0) p.0y.3=format(ym+r*c144,3,0) p.0x.4=format(xm-r*s144,3,0) p.0y.4=p.0y.3 p.0x.5=format(xm-r*s72,3,0) p.0y.5=p.0y.2 Do i=1 To 5 Say p.0x.i p.0y.i End Call line p.0x.1,p.0y.1,p.0x.3,p.0y.3 Call line p.0x.1,p.0y.1,p.0x.4,p.0y.4 Call line p.0x.2,p.0y.2,p.0x.4,p.0y.4 Call line p.0x.2,p.0y.2,p.0x.5,p.0y.5 Call line p.0x.3,p.0y.3,p.0x.5,p.0y.5   Do i=1 To z.0 s=s||z.i End   Call lineout pentagram,s Call lineout pentagram Exit   lend: Return reverse(d2c(arg(1),4))   line: Procedure Expose z. red green blue Parse Arg x0, y0, x1, y1 Say 'line' x0 y0 x1 y1 dx = abs(x1-x0) dy = abs(y1-y0) if x0 < x1 then sx = 1 else sx = -1 if y0 < y1 then sy = 1 else sy = -1 err = dx-dy   Do Forever xxx=x0*3+2 Do yy=y0-1 To y0+1 z.yy=overlay(copies(blue,5),z.yy,xxx) End if x0 = x1 & y0 = y1 Then Leave e2 = 2*err if e2 > -dy then do err = err - dy x0 = x0 + sx end if e2 < dx then do err = err + dx y0 = y0 + sy end end Return ::requires RxMath Library
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
#Phix
Phix
with javascript_semantics requires("1.0.2") ?shorten(permutes("abcd"),"elements",5)
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.
#Ursala
Ursala
#import std #import nat   is_perfect = ~&itB&& ^(~&,~&t+ iota); ^E/~&l sum:-0+ ~| not remainder
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.
#VBA
VBA
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
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.
#D
D
import std.bigint; import std.math; import std.stdio;   void fun(ref BigInt a, ref BigInt b, int c) { auto t = a; a = b; b = b * c + t; }   void solvePell(int n, ref BigInt a, ref BigInt b) { int x = cast(int) sqrt(cast(real) n); int y = x; int z = 1; int r = x << 1; BigInt e1 = 1; BigInt e2 = 0; BigInt f1 = 0; BigInt f2 = 1; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; fun(e1, e2, r); fun(f1, f2, r); a = f2; b = e2; fun(b, a, x); if (a * a - n * b * b == 1) { return; } } }   void main() { BigInt x, y; foreach(n; [61, 109, 181, 277]) { solvePell(n, x, y); writefln("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d", 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
#Perl
Perl
use SVG;   my $tau = 2 * 4*atan2(1, 1); my $dim = 200; my $sides = 5;   for $v (0, 2, 4, 1, 3, 0) { push @vx, 0.9 * $dim * cos($tau * $v / $sides); push @vy, 0.9 * $dim * sin($tau * $v / $sides); }   my $svg= SVG->new( width => 2*$dim, height => 2*$dim);   my $points = $svg->get_path( x => \@vx, y => \@vy, -type => 'polyline', );   $svg->rect ( width => "100%", height => "100%", style => { 'fill' => 'bisque' } );   $svg->polyline ( %$points, style => { 'fill' => 'seashell', 'stroke' => 'blue', 'stroke-width' => 3, }, transform => "translate($dim,$dim) rotate(-18)" );   open $fh, '>', 'pentagram.svg'; print $fh $svg->xmlify(-namespace=>'svg'); close $fh;
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def save over over chain ps> swap 0 put >ps enddef   def permute /# l l -- #/ len 2 > if len for drop pop swap rot swap 1 put swap permute endfor else save rotate save rotate endif swap len if pop rot rot 0 put else drop drop endif enddef   ( ) >ps ( ) ( 1 2 3 4 ) permute ps> sort print
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.
#VBScript
VBScript
Function IsPerfect(n) IsPerfect = False i = n - 1 sum = 0 Do While i > 0 If n Mod i = 0 Then sum = sum + i End If i = i - 1 Loop If sum = n Then IsPerfect = True End If End Function   WScript.StdOut.Write IsPerfect(CInt(WScript.Arguments(0))) WScript.StdOut.WriteLine
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#11l
11l
V first = random:choice([1B, 0B])   V you = ‘’ V me = ‘’ V ht = ‘HT’ // to get round ‘bug in MSVC 2017’[https://developercommunity.visualstudio.com/t/bug-with-operator-in-c/565417] I first me = random:sample(Array(‘HT’ * 3), 3).join(‘’) print(‘I choose first and will win on first seeing #. in the list of tosses’.format(me)) L you.len != 3 | any(you.map(ch -> ch !C :ht)) | you == me you = input(‘What sequence of three Heads/Tails will you win with: ’) E L you.len != 3 | any(you.map(ch -> ch !C :ht)) you = input(‘After you: What sequence of three Heads/Tails will you win with: ’) me = (I you[1] == ‘T’ {‘H’} E ‘T’)‘’you[0.<2] print(‘I win on first seeing #. in the list of tosses’.format(me))   print("Rolling:\n ", end' ‘’) V rolled = ‘’ L rolled ‘’= random:choice(‘HT’) print(rolled.last, end' ‘’) I rolled.ends_with(you) print("\n You win!") L.break I rolled.ends_with(me) print("\n I win!") L.break sleep(1)
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#360_Assembly
360 Assembly
* Pathological floating point problems 03/05/2016 PATHOFP CSECT USING PATHOFP,R13 SAVEAR B STM-SAVEAR(R15) DC 17F'0' STM STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 LE F0,=E'2' STE F0,U u(1)=2 LE F0,=E'-4' STE F0,U+4 u(2)=-4 LA R6,3 n=3 LA R7,U+4 @u(n-1) LA R8,U @u(n-2) LA R9,U+8 @u(n) LOOPN CH R6,=H'100' do n=3 to 100 BH ELOOPN LE F4,0(R7) u(n-1) LE F2,=E'1130' 1130 DER F2,F4 1130/u(n-1) LE F0,=E'111' 111 SER F0,F2 111-1130/u(n-1) LE F2,0(R7) u(n-1) LE F4,0(R8) u(n-2) MER F2,F4 u(n-1)*u(n-2) LE F6,=E'3000' 3000 DER F6,F2 3000/(u(n-1)*u(n-2)) AER F0,F6 111-1130/u(n-1)+3000/(u(n-1)*u(n-2)) STE F0,0(R9) store into u(n) XDECO R6,PG+0 n LE F0,0(R9) u(n) LA R0,3 number of decimals BAL R14,FORMATF format(u(n),'F13.3') MVC PG+12(13),0(R1) put into buffer XPRNT PG,80 print buffer LA R6,1(R6) n=n+1 LA R7,4(R7) @u(n-1) LA R8,4(R8) @u(n-2) LA R9,4(R9) @u(n) B LOOPN ELOOPN L R13,4(0,R13) LM R14,R12,12(R13) XR R15,R15 BR R14 COPY FORMATF LTORG PG DC CL80' ' buffer U DS 100E YREGS YFPREGS END PATHOFP
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.
#Delphi
Delphi
  program Pells_equation;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers;   type TPellResult = record x, y: BigInteger; end;   function SolvePell(nn: UInt64): TPellResult; var n, x, y, z, r, e1, e2, f1, t, u, a, b: BigInteger; begin n := nn; x := nn; x := BigInteger.Sqrt(x); y := BigInteger(x); z := BigInteger.One; r := x shl 1;   e1 := BigInteger.One; e2 := BigInteger.Zero; f1 := BigInteger.Zero; b := BigInteger.One;   while True do begin y := (r * z) - y; z := (n - (y * y)) div z; r := (x + y) div z;   u := BigInteger(e1); e1 := BigInteger(e2); e2 := (r * e2) + u;   u := BigInteger(f1); f1 := BigInteger(b);   b := r * b + u; a := e2 + x * b;   t := (a * a) - (n * b * b);   if t = 1 then begin with Result do begin x := BigInteger(a); y := BigInteger(b); end; Break; end; end; end;   const ns: TArray<UInt64> = [61, 109, 181, 277]; fmt = 'x^2 - %3d*y^2 = 1 for x = %-21s and y = %s';   begin for var n in ns do with SolvePell(n) do writeln(format(fmt, [n, x.ToString, y.ToString]));   {$IFNDEF UNIX} readln; {$ENDIF} 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
#Phix
Phix
-- -- demo\rosetta\Pentagram.exw -- ========================== -- -- Start/stop rotation by pressing space. Resizeable. -- ZXYV stop any rotation and orient up/down/left/right. -- with javascript_semantics include pGUI.e Ihandle dlg, canvas, timer cdCanvas cdcanvas integer rot = 0 enum FILL,BORDER constant colours = {CD_BLUE,CD_RED}, modes = {CD_FILL,CD_CLOSED_LINES} function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE"), cx = floor(w/2), cy = floor(h/2), radius = floor(min(cx,cy)*0.9) cdCanvasActivate(cdcanvas) cdCanvasClear(cdcanvas) cdCanvasSetFillMode(cdcanvas, CD_WINDING) cdCanvasSetLineWidth(cdcanvas, round(radius/100)+1) for mode=FILL to BORDER do cdCanvasSetForeground(cdcanvas,colours[mode]) cdCanvasBegin(cdcanvas,modes[mode]) for a=90 to 666 by 144 do atom r = (a+rot)*CD_DEG2RAD, x = floor(radius*cos(r)+cx), y = floor(radius*sin(r)+cy) cdCanvasVertex(cdcanvas, x, y) end for cdCanvasEnd(cdcanvas) end for cdCanvasFlush(cdcanvas) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cdCanvasSetBackground(cdcanvas, CD_PARCHMENT) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) rot = mod(rot+359,360) IupRedraw(canvas) return IUP_IGNORE end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if c = upper(c) if c=' ' then IupSetInt(timer,"RUN",not IupGetInt(timer,"RUN")) else c = find(c,"ZYXV") if c then IupSetInt(timer,"RUN",false) rot = (c-1)*90 IupRedraw(canvas) end if end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=640x640") IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) dlg = IupDialog(canvas,`TITLE="Pentagram"`) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) timer = IupTimer(Icallback("timer_cb"), 80, active:=false) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#Picat
Picat
permutation_rec1([X|Y],Z) :- permutation_rec1(Y,W), select(X,Z,W). permutation_rec1([],[]).   permutation_rec2([], []). permutation_rec2([X], [X]) :-!. permutation_rec2([T|H], X) :- permutation_rec2(H, H1), append(L1, L2, H1), append(L1, [T], X1), append(X1, L2, X).
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.
#Vlang
Vlang
fn compute_perfect(n i64) bool { mut sum := i64(0) for i := i64(1); i < n; i++ { if n%i == 0 { sum += i } } return sum == n }   // following fntion satisfies the task, returning true for all // perfect numbers representable in the argument type fn is_perfect(n i64) bool { return n in [i64(6), 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128] }   // validation fn main() { for n := i64(1); ; n++ { if is_perfect(n) != compute_perfect(n) { panic("bug") } if n%i64(1e3) == 0 { println("tested $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.
#Wren
Wren
var isPerfect = Fn.new { |n| if (n <= 2) return false var tot = 1 for (i in 2..n.sqrt.floor) { if (n%i == 0) { tot = tot + i var q = (n/i).floor if (q > i) tot = tot + q } } return n == tot }   System.print("The first four perfect numbers are:") var count = 0 var i = 2 while (count < 4) { if (isPerfect.call(i)) { System.write("%(i) ") count = count + 1 } i = i + 2 // there are no known odd perfect numbers } System.print()
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#AutoHotkey
AutoHotkey
Gui, font, s12 Gui, add, text, w90, Computer: loop, 3 Gui, add, button, x+10 h30 w30 vCB%A_Index% Gui, add, edit, xs w240 R3 vSequence Gui, add, text, w90, Human: loop, 3 Gui, add, button, x+10 h30 w30 vHB%A_Index% gHumButton, H Gui, add, button, xm gToss, toss Gui, add, button, x+10 gReset, Reset Gui, show,, Penney's game CompSeq := HumSeq := Seq := GameEnd := ""   RandomStart: Random, WhoStarts, 1, 2 if (WhoStarts=1) gosub, CompButton return ;----------------------------------------------- CompButton: if CompSeq return Loop, 3 { Random, coin, 1, 2 GuiControl,, CB%A_Index%, % coin=1?"H":"T" CompSeq .= coin=1?"H":"T" } return ;----------------------------------------------- HumButton: if HumSeq return GuiControlGet, B,, % A_GuiControl GuiControl,, % A_GuiControl, % B="H"?"T":"H" return ;----------------------------------------------- Toss: if GameEnd return if !HumSeq { loop 3 { GuiControlGet, B,, HB%A_Index% HumSeq .= B } if (CompSeq = HumSeq) { MsgBox, 262160, Penney's game, Human's Selection Has to be different From Computer's Selection`nTry Again HumSeq := "" return } } if !CompSeq { CompSeq := (SubStr(HumSeq,2,1)="H"?"T":"H") . SubStr(HumSeq,1,2) loop, Parse, CompSeq GuiControl,, CB%A_Index%, % A_LoopField }   Random, coin, 1, 2 Seq .= coin=1?"H":"T" GuiControl,, Sequence, % seq if (SubStr(Seq, -2) = HumSeq) MsgBox % GameEnd := "Human Wins" else if (SubStr(Seq, -2) = CompSeq) MsgBox % GameEnd := "Computer Wins" return ;----------------------------------------------- Reset: loop, 3 { GuiControl,, CB%A_Index% GuiControl,, HB%A_Index%, H } GuiControl,, Sequence CompSeq := HumSeq := Seq := GameEnd := "" gosub, RandomStart return ;-----------------------------------------------
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Ada
Ada
with Ada.Text_IO;   procedure Converging_Sequence is   generic type Num is digits <>; After: Positive; procedure Task_1;   procedure Task_1 is package FIO is new Ada.Text_IO.Float_IO(Num); package IIO is new Ada.Text_IO.Integer_IO(Integer);   procedure Output (I: Integer; N: Num) is begin IIO.Put(Item => I, Width => 4); FIO.Put(Item => N, Fore => 4, Aft => After, Exp => 0); Ada.Text_IO.New_Line; end Output;   Very_Old: Num := 2.0; Old: Num := -4.0; Now: Num; begin Ada.Text_IO.Put_Line("Converging Sequence with" & Integer'Image(After) & " digits"); for I in 3 .. 100 loop Now := 111.0 - 1130.0 / Old + 3000.0 / (Old * Very_Old); Very_Old := Old; Old := Now; if (I < 9) or else (I=20 or I=30 or I=50 or I=100) then Output(I, Now); end if; end loop; Ada.Text_IO.New_Line; end Task_1;   type Short is digits(8); type Long is digits(16);   procedure Task_With_Short is new Task_1(Short, 8); procedure Task_With_Long is new Task_1(Long, 16); begin Task_With_Short; Task_With_Long; end Converging_Sequence;
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.
#Factor
Factor
USING: formatting kernel locals math math.functions sequences ;   :: solve-pell ( n -- a b )   n sqrt >integer :> x! x :> y! 1 :> z! 2 x * :> r!   1 0 :> ( e1! e2! ) 0 1 :> ( f1! f2! ) 0 0 :> ( a! b! )   [ a sq b sq n * - 1 = ] [   r z * y - y! n y sq - z / floor z! x y + z / floor r!   e2 r e2 * e1 + e2! e1! f2 r f2 * f1 + f2! f1!   e2 x f2 * + a! f2 b!   ] until a b ;   { 61 109 181 277 } [ dup solve-pell "x^2 - %3d*y^2 = 1 for x = %-21d and y = %d\n" printf ] each
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.
#FreeBASIC
FreeBASIC
  Sub Fun(Byref a As LongInt, Byref b As LongInt, c As Integer) Dim As LongInt t t = a : a = b : b = b * c + t End Sub   Sub SolvePell(n As Integer, Byref a As LongInt, Byref b As LongInt) Dim As Integer z, r Dim As LongInt x, y, e1, e2, f1, f2 x = Sqr(n) : y = x : z = 1 : r = 2 * x e1 = 1 : e2 = 0 : f1 = 0 : f2 = 1 While True y = r * z - y : z = (n - y * y) / z : r = (x + y) / z Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x) If a * a - n * b * b = 1 Then Exit Sub Wend End Sub   Dim As Integer i Dim As LongInt x, y Dim As Integer n(0 To 3) = {61, 109, 181, 277} For i = 0 To 3 ''n In {61, 109, 181, 277} SolvePell(n(i), x, y) Print Using "x^2 - ### * y^2 = 1 for x = ##################### and y = #####################"; n(i); x; y 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
#PostScript
PostScript
%!PS-Adobe-3.0 EPSF %%BoundingBox: 0 0 200 600   /n 5 def % 5-star; can be set to other odd numbers   /s { gsave } def /r { grestore } def /g { .7 setgray } def /t { 100 exch translate } def /p { 180 90 n div sub rotate 0 0 moveto n { 0 160 rlineto 180 180 n div sub rotate } repeat closepath } def   s 570 t p s g eofill r stroke r % even-odd fill s 370 t p s g fill r stroke r % non-zero fill s 170 t p s 2 setlinewidth stroke r g fill r % non-zero, but hide inner strokes   %%EOF
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
#Processing
Processing
  //Aamrun, 29th June 2022   size(1000,1000);   translate(width/2,height/2); rotate(3*PI/2); fill(#0000ff);   beginShape(); for(int i=0;i<10;i+=2){   vertex(450*cos(i*2*PI/5),450*sin(i*2*PI/5)); } endShape(CLOSE);  
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
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (permute (1 2 3))
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func Perfect(N); \Return 'true' if N is a perfect number int N, S, I, Q; [S:= 1; for I:= 2 to sqrt(N) do [Q:= N/I; if rem(0)=0 then S:= S+I+Q; ]; return S=N & N#1; ];   int A, N; [for A:= 1 to 16 do [N:= (1<<A - 1) * 1<<(A-1); if Perfect(N) then [IntOut(0, N); CrLf(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.
#Yabasic
Yabasic
  sub isPerfect(n) if (n < 2) or mod(n, 2) = 1 then return false : endif // asumimos que los números impares no son perfectos sum = 0 for i = 1 to n-1 if mod(n,i) = 0 then sum = sum + i : endif next i if sum = n then return true else return false : endif end sub   print "Los primeros 5 numeros perfectos son:" for i = 1 to 33550336 if isPerfect(i) then print i, " ", : endif next i print end  
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Action.21
Action!
DEFINE MAXSIZE="12"   INT ARRAY angleStack(MAXSIZE) BYTE ARRAY depthStack(MAXSIZE),stageStack(MAXSIZE) BYTE stacksize=[0]   BYTE FUNC IsEmpty() IF stacksize=0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC IsFull() IF stacksize=MAXSIZE THEN RETURN (1) FI RETURN (0)   PROC Push(INT angle BYTE depth,stage) IF IsFull() THEN Break() FI angleStack(stacksize)=angle depthStack(stacksize)=depth stageStack(stackSize)=stage stacksize==+1 RETURN   PROC Pop(INT POINTER angle BYTE POINTER depth,stage) IF IsEmpty() THEN Break() FI stacksize==-1 angle^=angleStack(stacksize) depth^=depthStack(stacksize) stage^=stageStack(stacksize) RETURN   INT FUNC Sin(INT a) WHILE a<0 DO a==+360 OD WHILE a>360 DO a==-360 OD IF a=90 THEN RETURN (1) ELSEIF a=270 THEN RETURN (-1) FI RETURN (0)   INT FUNC Cos(INT a) RETURN (Sin(a-90))   PROC DrawPeano(INT x BYTE y,len BYTE depth) BYTE stage INT angle=[90],a   Plot(x,y) Push(90,depth,0)   WHILE IsEmpty()=0 DO Pop(@a,@depth,@stage) IF stage<3 THEN Push(a,depth,stage+1) FI IF stage=0 THEN angle==+a IF depth>1 THEN Push(-a,depth-1,0) FI ELSEIF stage=1 THEN x==+len*Cos(angle) y==-len*Sin(angle) DrawTo(x,y) IF depth>1 THEN Push(a,depth-1,0) FI ELSEIF stage=2 THEN x==+len*Cos(angle) y==-len*Sin(angle) DrawTo(x,y) IF depth>1 THEN Push(-a,depth-1,0) FI ELSEIF stage=3 THEN angle==-a FI OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   DrawPeano(69,186,7,6)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#BASIC
BASIC
  global jugador, computador, secuencia jugador = "" : computador = ""   function SecuenciaJugador(secuencia) do valido = TRUE print chr(10) + "Ingresa una secuencia de 3 opciones, cada una de ellas H o T:"; input " > ", secuencia secuencia = upper(secuencia) if length(secuencia) <> 3 then valido = FALSE if secuencia = computador then print "Pero no la misma que yo..."+ chr(10): valido = FALSE if valido then for i = 1 to 3 opcion = mid(secuencia, i, 1) if opcion <> "H" and opcion <> "T" then valido = FALSE next i end if until valido SecuenciaJugador = secuencia end function   function LanzamientoCPU() secuencia = "" computador ="" for i = 1 to 3 opcion = rand if opcion < .5 then secuencia += "H" else secuencia += "T" next i LanzamientoCPU = secuencia end function   do cls print "*** Penney's Game ***" + chr(10) if rand < .5 then print "Empiezas... "; jugador = SecuenciaJugador(jugador) computador = LanzamientoCPU() if jugador = computador then computador = LanzamientoCPU() print "Yo gano al ver "; computador; " por primera vez en la lista de lanzamientos..." else computador = LanzamientoCPU() print "Elijo primero y gano al ver "; computador; " por primera vez en la lista de lanzamientos..." jugador = SecuenciaJugador(jugador) end if print: print "Lanzamientos..." secuencia = "" winner = FALSE do pause 1 if rand <= .5 then secuencia += "H" print "H "; else print "T "; secuencia += "T" end if if right(secuencia, 3) = jugador then print: print "¡Felicidades! ¡Ganaste!": winner = TRUE if right(secuencia, 3) = computador then print: print "¡Yo gano!": winner = TRUE until winner do valido = FALSE print input "¿Otra partida? (S/N) ", otra if instr("SsNn", otra) then valido = TRUE until valido until upper(otra) = "N" print "¡Gracias por jugar!" end  
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#Batch_File
Batch File
:: ::Penney's Game Task from Rosetta Code Wiki ::Batch File Implementation :: ::Please Directly Open the Batch File to play... ::   @echo off setlocal enabledelayedexpansion title The Penney's Game Batch File   set cpu=0&set you=0 cls echo. echo Penney's Game echo Batch File Implementation   :main set you_bet=&set cpu_bet= echo.&echo --------------------------------------------------------&echo. echo CPU's Score: %cpu% Your Score: %you% echo. <nul set /p "dummy=Heads I start, Tails you start..." set /a startrnd=%random%%%2 set firsttoss=Tails&set func=optimal if %startrnd%==1 (set firsttoss=Heads&set func=rndbet) ping -n 3 localhost >nul <nul set /p "dummy=. %firsttoss%^!" echo.&echo. goto %func%   :rndbet set /a "seq1=%random%%%2","seq2=%random%%%2","seq3=%random%%%2" set binary=%seq1%%seq2%%seq3% set cpu_bet=%binary:1=H% set cpu_bet=%cpu_bet:0=T% echo I will bet first. So, my bet sequence will be %cpu_bet%. :again1 set /p "you_bet=What will be your bet sequence? " call :validate again1 echo.&echo So, you're feeling lucky on %you_bet%. We'll see... goto succesivetossing   :optimal echo Ok. You will bet first. :again2 set /p "you_bet=What will be your bet sequence? " call :validate again2 set seq1=%you_bet:~0,1%&set seq2=%you_bet:~1,1% set new_seq1=T if /i %seq2%==T set new_seq1=H set cpu_bet=%new_seq1%%seq1%%seq2% echo.&echo Hmm... My bet will be %cpu_bet%. We'll see who's lucky...   :succesivetossing set toses=&set cnt=0 echo. <nul set /p "dummy=Tosses: " :tossloop call :tossgen <nul set /p dummy=%toss% ping -n 2 localhost >nul set /a newline=%cnt%%%60 if %newline%==59 ( echo. <nul set /p "dummy=. " ) if "%toses:~-3,3%"=="%cpu_bet%" goto iwin if "%toses:~-3,3%"=="%you_bet%" goto uwin set /a cnt+=1&goto tossloop   :tossgen set /a rand=%random%%%2 set toss=T if %rand%==0 set toss=H set toses=%toses%%toss% goto :EOF   :iwin set /a cpu+=1&set newgame= echo.&echo. echo I Win^^! Better Luck Next Time... echo. set /p "newgame=[Type Y if U Wanna Beat Me, or Else, Exit...] " if /i "!newgame!"=="Y" goto :main exit   :uwin set /a you+=1&set newgame= echo.&echo. echo Argh, You Win^^! ...But One Time I'll Beat You. echo. set /p "newgame=[Type Y for Another Game, or Else, Exit...] " if /i "!newgame!"=="Y" goto :main exit   :validate echo "!you_bet!"|findstr /r /c:"^\"[hHtT][hHtT][hHtT]\"$">nul || ( echo [Invalid Input...]&echo.&goto %1 ) if /i "!you_bet!"=="%cpu_bet%" (echo [Bet something different...]&echo.&goto %1) for %%i in ("t=T" "h=H") do set "you_bet=!you_bet:%%~i!" goto :EOF
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#ALGOL_68
ALGOL 68
BEGIN # task 1 # BEGIN PR precision 32 PR print( ( " 32 digit REAL numbers", newline ) ); [ 1 : 100 ]LONG LONG REAL v; v[ 1 ] := 2; v[ 2 ] := -4; FOR n FROM 3 TO UPB v DO v[ n ] := 111 - ( 1130 / v[ n - 1 ] ) + ( 3000 / ( v[ n - 1 ] * v[ n - 2 ] ) ) OD; FOR n FROM 3 TO 8 DO print( ( "n = ", whole( n, 3 ), " ", fixed( v[ n ], -22, 16 ), newline ) ) OD; FOR n FROM 20 BY 10 TO 50 DO print( ( "n = ", whole( n, 3 ), " ", fixed( v[ n ], -22, 16 ), newline ) ) OD; print( ( "n = 100 ", fixed( v[ 100 ], -22, 16 ), newline ) ) END; BEGIN PR precision 120 PR print( ( "120 digit REAL numbers", newline ) ); [ 1 : 100 ]LONG LONG REAL v; v[ 1 ] := 2; v[ 2 ] := -4; FOR n FROM 3 TO UPB v DO v[ n ] := 111 - ( 1130 / v[ n - 1 ] ) + ( 3000 / ( v[ n - 1 ] * v[ n - 2 ] ) ) OD; print( ( "n = 100 ", fixed( v[ 100 ], -22, 16 ), newline ) ) END; print( ( newline ) ); # task 2 # BEGIN print( ( "single precision REAL numbers...", newline ) ); REAL chaotic balance := exp( 1 ) - 1; print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END; BEGIN print( ( "double precision REAL numbers...", newline ) ); LONG REAL chaotic balance := long exp( 1 ) - 1; print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END; BEGIN PR precision 32 PR print( ( " 32 digit REAL numbers...", newline ) ); LONG LONG REAL chaotic balance := long long exp( 1 ) - 1; print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END 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.
#Go
Go
package main   import ( "fmt" "math/big" )   var big1 = new(big.Int).SetUint64(1)   func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1)   e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1)   t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } }   func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", 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
#Python
Python
import turtle   turtle.bgcolor("green") t = turtle.Turtle() t.color("red", "blue") t.begin_fill() for i in range(0, 5): t.forward(200) t.right(144) t.end_fill()
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
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL GLOBAL a, i, j, k, n AS INTEGER GLOBAL d, ns, s AS STRING 'dynamic string FUNCTION PBMAIN () AS LONG ns = INPUTBOX$(" n =",, "3") 'input n n = VAL(ns) DIM a(1 TO n) AS INTEGER FOR i = 1 TO n: a(i)= i: NEXT DO s = " " FOR i = 1 TO n d = STR$(a(i)) s = BUILD$(s, d) ' s & d concatenate NEXT  ? s 'print and pause i = n DO DECR i LOOP UNTIL i = 0 OR a(i) < a(i+1) j = i+1 k = n DO WHILE j < k SWAP a(j), a(k) INCR j DECR k LOOP IF i > 0 THEN j = i+1 DO WHILE a(j) < a(i) INCR j LOOP SWAP a(i), a(j) END IF LOOP UNTIL i = 0 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.
#Zig
Zig
  const std = @import("std"); const expect = std.testing.expect; const stdout = std.io.getStdOut().outStream();   pub fn main() !void { var i: u32 = 2; try stdout.print("The first few perfect numbers are: ", .{}); while (i <= 10_000) : (i += 2) if (propersum(i) == i) try stdout.print("{} ", .{i}); try stdout.print("\n", .{}); }   fn propersum(n: u32) u32 { var sum: u32 = 1; var d: u32 = 2; while (d * d <= n) : (d += 1) if (n % d == 0) { sum += d; const q = n / d; if (q > d) sum += q; }; return sum; }   test "Proper divisors" { expect(propersum(28) == 28); expect(propersum(71) == 1); expect(propersum(30) == 42); }  
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#AutoHotkey
AutoHotkey
gdip1() PeanoX := A_ScreenWidth/2 - 100, PeanoY := A_ScreenHeight/2 - 100 Peano(PeanoX, PeanoY, 3**3, 5, 5, Arr:=[]) xmin := xmax := ymin := ymax := 0 for i, point in Arr { xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x xmax := point.x > xmax ? point.x : xmax ymin := A_Index = 1 ? point.y : ymin < point.y ? ymin : point.y ymax := point.y > ymax ? point.y : ymax } for i, point in Arr points .= point.x - xmin + PeanoX "," point.y - ymin + PeanoY "|" points := Trim(points, "|") Gdip_DrawLines(G, pPen, Points) UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) return ; --------------------------------------------------------------- Peano(x, y, lg, i1, i2, Arr) { if (lg =1 ) { Arr[Arr.count()+1, "x"] := x Arr[Arr.count(), "y"] := y return } lg := lg/3 Peano(x+(2*i1*lg) , y+(2*i1*lg) , lg , i1 , i2 , Arr) Peano(x+((i1-i2+1)*lg) , y+((i1+i2)*lg) , lg , i1 , 1-i2 , Arr) Peano(x+lg , y+lg , lg , i1 , 1-i2 , Arr) Peano(x+((i1+i2)*lg) , y+((i1-i2+1)*lg) , lg , 1-i1 , 1-i2 , Arr) Peano(x+(2*i2*lg) , y+(2*(1-i2)*lg) , lg , i1 , i2 , Arr) Peano(x+((1+i2-i1)*lg) , y+((2-i1-i2)*lg) , lg , i1 , i2 , Arr) Peano(x+(2*(1-i1)*lg) , y+(2*(1-i1)*lg) , lg , i1 , i2 , Arr) Peano(x+((2-i1-i2)*lg) , y+((1+i2-i1)*lg) , lg , 1-i1 , i2 , Arr) Peano(x+(2*(1-i2)*lg) , y+(2*i2*lg) , lg , 1-i1 , i2 , Arr) } ; --------------------------------------------------------------- gdip1(){ global If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, Exit Width := A_ScreenWidth, Height := A_ScreenHeight Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop Gui, 1: Show, NA hwnd1 := WinExist() hbm := CreateDIBSection(Width, Height) hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4) pPen := Gdip_CreatePen(0xFFFF0000, 2) } ; --------------------------------------------------------------- gdip2(){ global Gdip_DeleteBrush(pBrush) Gdip_DeletePen(pPen) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) } ; --------------------------------------------------------------- Exit: gdip2() Gdip_Shutdown(pToken) ExitApp Return  
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#BBC_BASIC
BBC BASIC
REM >penney PRINT "*** Penney's Game ***" REPEAT PRINT ' "Heads you pick first, tails I pick first." PRINT "And it is... "; WAIT 100 ht% = RND(0 - TIME) AND 1 IF ht% THEN PRINT "heads!" PROC_player_chooses(player$) computer$ = FN_optimal(player$) PRINT "I choose "; computer$; "." ELSE PRINT "tails!" computer$ = FN_random PRINT "I choose "; computer$; "." PROC_player_chooses(player$) ENDIF PRINT "Starting the game..." ' SPC 5; sequence$ = "" winner% = FALSE REPEAT WAIT 100 roll% = RND AND 1 IF roll% THEN sequence$ += "H" PRINT "H "; ELSE PRINT "T "; sequence$ += "T" ENDIF IF RIGHT$(sequence$, 3) = computer$ THEN PRINT ' "I won!" winner% = TRUE ELSE IF RIGHT$(sequence$, 3) = player$ THEN PRINT ' "Congratulations! You won." winner% = TRUE ENDIF ENDIF UNTIL winner% REPEAT valid% = FALSE INPUT "Another game? (Y/N) " another$ IF INSTR("YN", another$) THEN valid% = TRUE UNTIL valid% UNTIL another$ = "N" PRINT "Thank you for playing!" END : DEF PROC_player_chooses(RETURN sequence$) LOCAL choice$, valid%, i% REPEAT valid% = TRUE PRINT "Enter a sequence of three choices, each of them either H or T:" INPUT "> " sequence$ IF LEN sequence$ <> 3 THEN valid% = FALSE IF valid% THEN FOR i% = 1 TO 3 choice$ = MID$(sequence$, i%, 1) IF choice$ <> "H" AND choice$ <> "T" THEN valid% = FALSE NEXT ENDIF UNTIL valid% ENDPROC : DEF FN_random LOCAL sequence$, choice%, i% sequence$ = "" FOR i% = 1 TO 3 choice% = RND AND 1 IF choice% THEN sequence$ += "H" ELSE sequence$ += "T" NEXT = sequence$ : DEF FN_optimal(sequence$) IF MID$(sequence$, 2, 1) = "H" THEN = "T" + LEFT$(sequence$, 2) ELSE = "H" + LEFT$(sequence$, 2) ENDIF
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#AWK
AWK
  BEGIN { do_task1() do_task2() do_task3() exit }     function do_task1(){ print "Task 1" v[1] = 2 v[2] = -4 for (n=3; n<=100; n++) v[n] = 111 - 1130 / v[n-1] + 3000 / (v[n-1] * v[n-2])   for (i=3; i<=8; i++) print_results(i) print_results(20) print_results(30) print_results(50) print_results(100) }   # This works because all awk variables are global, except when declared locally function print_results(n){ printf("n = %d\t%20.16f\n", n, v[n]) }   # This function doesn't need any parameters; declaring balance and i in the function parameters makes them local function do_task2( balance, i){ balance[0] = exp(1)-1 for (i=1; i<=25; i++) balance[i] = balance[i-1]*i-1 printf("\nTask 2\nBalance after 25 years: $%12.10f", balance[25]) }   function do_task3( a, b, f_ab){ a = 77617 b = 33096   f_ab = 333.75 * b^6 + a^2 * (11*a^2*b^2 - b^6 - 121*b^4 - 2) + 5.5*b^8 + a/(2*b) printf("\nTask 3\nf(%6.12f, %6.12f) = %10.24f", a, b, f_ab) }    
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.
#Haskell
Haskell
pell :: Integer -> (Integer, Integer) pell n = go (x, 1, x * 2, 1, 0, 0, 1) where x = floor $ sqrt $ fromIntegral n go (y, z, r, e1, e2, f1, f2) = let y' = r * z - y z' = (n - y' * y') `div` z r' = (x + y') `div` z' (e1', e2') = (e2, e2 * r' + e1) (f1', f2') = (f2, f2 * r' + f1) (a, b) = (f2', e2') (b', a') = (a, a * x + b) in if a' * a' - n * b' * b' == 1 then (a', b') else go (y', z', r', e1', e2', f1', f2')
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
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ [ 1 1 30 times [ tuck + ] swap join ] constant do ] is phi ( --> n/d )   [ 5 times [ 2dup walk 1 5 turn 2dup walk 3 5 turn ] 2drop ] is star ( n/d --> )   [ 5 times [ 2dup walk 2 5 turn ] 2drop ] is pentagram ( n/d --> )   turtle ' [ 79 126 229 ] fill [ 200 1 star ] 10 wide -1 10 turn 200 1 phi v* phi v* pentagram 1 10 turn
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
#R
R
p <- cbind(x = c(0, 1, 2,-0.5 , 2.5 ,0), y = c(0, 1, 0,0.6, 0.6,0)) plot(p) lines(p)
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
#PowerShell
PowerShell
  function permutation ($array) { function generate($n, $array, $A) { if($n -eq 1) { $array[$A] -join ' ' } else{ for( $i = 0; $i -lt ($n - 1); $i += 1) { generate ($n - 1) $array $A if($n % 2 -eq 0){ $i1, $i2 = $i, ($n-1) $A[$i1], $A[$i2] = $A[$i2], $A[$i1] } else{ $i1, $i2 = 0, ($n-1) $A[$i1], $A[$i2] = $A[$i2], $A[$i1] } } generate ($n - 1) $array $A } } $n = $array.Count if($n -gt 0) { (generate $n $array (0..($n-1))) } else {$array} } permutation @('A','B','C')  
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.
#zkl
zkl
fcn isPerfectNumber1(n) { n == [1..n-1].filter('wrap(i){ n % i == 0 }).sum(); }
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#C
C
  /*Abhishek Ghosh, 14th September 2018*/   #include <graphics.h> #include <math.h>   void Peano(int x, int y, int lg, int i1, int i2) {   if (lg == 1) { lineto(3*x,3*y); return; }   lg = lg/3; Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); Peano(x+lg, y+lg, lg, i1, 1-i2); Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); }   int main(void) {   initwindow(1000,1000,"Peano, Peano");   Peano(0, 0, 1000, 0, 0); /* Start Peano recursion. */   getch(); cleardevice();   return 0; }  
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#C
C
  #include <stdio.h> #include <stdlib.h> #include <time.h>   #define SEQLEN 3   int getseq(char *s) { int r = 0; int i = 1 << (SEQLEN - 1);   while (*s && i) { switch (*s++) { case 'H': case 'h': r |= i; break; case 'T': case 't': /* 0 indicates tails, this is 0, so do nothing */ break; default: return -1; } i >>= 1; }   return r; }   void printseq(int seq) { int i; for (i = SEQLEN - 1; i >= 0; --i) printf("%c", seq & (1 << i) ? 'h' : 't'); }   int getuser(void) { int user; char s[SEQLEN + 1];   printf("Enter your sequence of %d (h/t): ", SEQLEN); while (1) { /* This needs to be manually changed if SEQLEN is changed */ if (scanf("%3s", s) != 1) exit(1); if ((user = getseq(s)) != -1) return user; printf("Please enter only h/t characters: "); } }   int getai(int user) { int ai;   printf("Computers sequence of %d is: ", SEQLEN); /* The ai's perfect choice will only be perfect for SEQLEN == 3 */ if (user == -1) ai = rand() & (1 << SEQLEN) - 1; else ai = (user >> 1) | ((~user << 1) & (1 << SEQLEN - 1));   printseq(ai); printf("\n"); return ai; }   int rungame(int user, int ai) { /* Generate first SEQLEN flips. We only need to store the last SEQLEN * tosses at any one time. */ int last3 = rand() & (1 << SEQLEN) - 1;   printf("Tossed sequence: "); printseq(last3); while (1) { if (user == last3) { printf("\nUser wins!\n"); return 1; }   if (ai == last3) { printf("\nAi wins!\n"); return 0; }   last3 = ((last3 << 1) & (1 << SEQLEN) - 2) | (rand() & 1); printf("%c", last3 & 1 ? 'h' : 't'); } }   int main(void) { srand(time(NULL)); int playerwins = 0; int totalgames = 0;   /* Just use ctrl-c for exit */ while (1) { int user = -1; int ai = -1;   printf("\n"); if (rand() & 1) { ai = getai(user); user = getuser(); } else { user = getuser(); ai = getai(user); }   playerwins += rungame(user, ai); totalgames++;   printf("You have won %d out of %d games\n", playerwins, totalgames); printf("=================================\n"); }   return 0; }  
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#C
C
  #include<stdio.h> #include<gmp.h>   void firstCase(){ mpf_t a,b,c;   mpf_inits(a,b,c,NULL);   mpf_set_str(a,"0.1",10); mpf_set_str(b,"0.2",10); mpf_add(c,a,b);   gmp_printf("\n0.1 + 0.2 = %.*Ff",20,c); }   void pathologicalSeries(){ int n; mpf_t v1, v2, vn, a1, a2, a3, t2, t3, prod;   mpf_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);   mpf_set_str(v1,"2",10); mpf_set_str(v2,"-4",10); mpf_set_str(a1,"111",10); mpf_set_str(a2,"1130",10); mpf_set_str(a3,"3000",10);   for(n=3;n<=100;n++){ mpf_div(t2,a2,v2); mpf_mul(prod,v1,v2); mpf_div(t3,a3,prod); mpf_add(vn,a1,t3); mpf_sub(vn,vn,t2);   if((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){ gmp_printf("\nv_%d : %.*Ff",n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,vn); }   mpf_set(v1,v2); mpf_set(v2,vn); } }   void healthySeries(){ int n;   mpf_t num,denom,result; mpq_t v1, v2, vn, a1, a2, a3, t2, t3, prod;   mpf_inits(num,denom,result,NULL); mpq_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);   mpq_set_str(v1,"2",10); mpq_set_str(v2,"-4",10); mpq_set_str(a1,"111",10); mpq_set_str(a2,"1130",10); mpq_set_str(a3,"3000",10);   for(n=3;n<=100;n++){ mpq_div(t2,a2,v2); mpq_mul(prod,v1,v2); mpq_div(t3,a3,prod); mpq_add(vn,a1,t3); mpq_sub(vn,vn,t2);   if((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){ mpf_set_z(num,mpq_numref(vn)); mpf_set_z(denom,mpq_denref(vn)); mpf_div(result,num,denom);   gmp_printf("\nv_%d : %.*Ff",n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,result); }   mpq_set(v1,v2); mpq_set(v2,vn); } }   int main() { mpz_t rangeProd;   firstCase();   printf("\n\nPathological Series : ");   pathologicalSeries();   printf("\n\nNow a bit healthier : ");   healthySeries();   return 0; }  
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.
#J
J
NB. sqrt representation for continued fraction sqrt_cf =: 3 : 0 rep=. '' [ 'm d'=. 0 1 [ a =. a0=. <. %: y while. a ~: +: a0 do. rep=. rep , a=. <. (a0+m) % d=. d %~ y - *: m=. m -~ a*d end. a0;rep )   NB. find x,y such that x^2 - n*y^2 = 1 using continued fractions pell =: 3 : 0 n =. 1 [ 'a0 as' =. x: &.> sqrt_cf y while. 1 do. cs =. 2 x: (+%)/\ a0, n$as NB. convergents if. # sols =. I. 1 = (*: cs) +/ . * 1 , -y do. cs {~ {. sols return. end. n =. +: n 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.
#Java
Java
  import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List;   public class PellsEquation {   public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } }   private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } }   private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b;   while ( true ) { //count++; int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; }   // array[0] = new part of cont frac // array[1] = new a // array[2] = new b private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; }     }  
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
#Racket
Racket
#lang racket (require 2htdp/image)   (overlay (star-polygon 100 5 2 "outline" (make-pen "blue" 4 "solid" "round" "round")) (star-polygon 100 5 2 "solid" "cyan"))
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
#Raku
Raku
use SVG;   constant $dim = 200; constant $sides = 5;   my @vertices = map { 0.9 * $dim * cis($_ * τ / $sides) }, ^$sides;   my @points = map |*.reals.fmt("%0.3f"), flat @vertices[0, 2 ... *], @vertices[1, 3 ... *], @vertices[0];   say SVG.serialize( svg => [ :width($dim*2), :height($dim*2), :rect[:width<100%>, :height<100%>, :style<fill:bisque;>], :polyline[ :points(@points.join: ','), :style("stroke:blue; stroke-width:3; fill:seashell;"), :transform("translate($dim,$dim) rotate(-90)") ], ], );
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
#Prolog
Prolog
:- use_module(library(clpfd)).   permut_clpfd(L, N) :- length(L, N), L ins 1..N, all_different(L), label(L).
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#C.2B.2B
C++
#include <cmath> #include <fstream> #include <iostream> #include <string>   class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; };   void peano_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length; y_ = length; angle_ = 90; out << "<svg xmlns='http://www.w3.org/2000/svg' width='" << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "L"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; }   std::string peano_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { switch (c) { case 'L': t += "LFRFL-F-RFLFR+F+LFRFL"; break; case 'R': t += "RFLFR+F+LFRFL-F-RFLFR"; break; default: t += c; break; } } return t; }   void peano_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; }   void peano_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } }   int main() { std::ofstream out("peano_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } peano_curve pc; pc.write(out, 656, 8, 4); return 0; }
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#C.23
C#
using static System.Console; using static System.Threading.Thread; using System;   public static class PenneysGame { const int pause = 500; const int N = 3; static Random rng = new Random();   static int Toss() => rng.Next(2);   static string AsString(this int sequence) { string s = ""; for (int b = 0b100; b > 0; b >>= 1) { s += (sequence & b) > 0 ? 'T' : 'H'; } return s; }   static int UserInput() { while (true) { switch (ReadKey().Key) { case ConsoleKey.Escape: return -1; case ConsoleKey.H: return 0; case ConsoleKey.T: return 1; } Console.Write('\b'); } }   public static void Main2() { int yourScore = 0, myScore = 0; while (true) { WriteLine($"Your score: {yourScore}, My score: {myScore}"); WriteLine("Determining who goes first..."); Sleep(pause); bool youStart = Toss() == 1; WriteLine(youStart ? "You go first." : "I go first."); int yourSequence = 0, mySequence = 0; if (youStart) { WriteLine("Choose your sequence of (H)eads and (T)ails (or press Esc to exit)"); int userChoice; for (int i = 0; i < N; i++) { if ((userChoice = UserInput()) < 0) return; yourSequence = (yourSequence << 1) + userChoice; } mySequence = ((~yourSequence << 1) & 0b100) | (yourSequence >> 1); } else { for (int i = 0; i < N; i++) { mySequence = (mySequence << 1) + Toss(); }   WriteLine("I chose " + mySequence.AsString()); do { WriteLine("Choose your sequence of (H)eads and (T)ails (or press Esc to exit)"); int choice; yourSequence = 0; for (int i = 0; i < N; i++) { if ((choice = UserInput()) < 0) return; yourSequence = (yourSequence << 1) + choice; } if (yourSequence == mySequence) { WriteLine(); WriteLine("You cannot choose the same sequence."); } } while (yourSequence == mySequence); }   WriteLine(); WriteLine($"Your sequence: {yourSequence.AsString()}, My sequence: {mySequence.AsString()}"); WriteLine("Tossing..."); int sequence = 0; for (int i = 0; i < N; i++) { Sleep(pause); int toss = Toss(); sequence = (sequence << 1) + toss; Write(toss > 0 ? 'T' : 'H'); } while (true) { if (sequence == yourSequence) { WriteLine(); WriteLine("You win!"); yourScore++; break; } else if (sequence == mySequence) { WriteLine(); WriteLine("I win!"); myScore++; break; } Sleep(pause); int toss = Toss(); sequence = ((sequence << 1) + toss) & 0b111; Write(toss > 0 ? 'T' : 'H'); } WriteLine("Press a key."); ReadKey(); Clear(); } }   }  
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#C.23
C#
#define USE_BIGRATIONAL #define BANDED_ROWS #define INCREASED_LIMITS   using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Numerics; using Numerics;   using static Common; using static Task1; using static Task2; using static Task3;   #if !USE_BIGRATIONAL // Mock structure to make test code work. struct BigRational { public override string ToString() => "NOT USING BIGRATIONAL"; public static explicit operator decimal(BigRational value) => -1; } #endif   static class Common { public const string FMT_STR = "{0,4} {1,-15:G9} {2,-24:G17} {3,-32} {4,-32}"; public static string Headings { get; } = string.Format( CultureInfo.InvariantCulture, FMT_STR, new[] { "N", "Single", "Double", "Decimal", "BigRational (rounded as Decimal)" });   [Conditional("BANDED_ROWS")] static void SetConsoleFormat(int n) { if (n % 2 == 0) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; } else { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; } }   public static string FormatOutput(int n, (float sn, double db, decimal dm, BigRational br) x) { SetConsoleFormat(n); return string.Format(CultureInfo.CurrentCulture, FMT_STR, n, x.sn, x.db, x.dm, (decimal)x.br); }   static void Main() { WrongConvergence();   Console.WriteLine(); ChaoticBankSociety();   Console.WriteLine(); SiegfriedRump();   SetConsoleFormat(0); } }
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.
#jq
jq
# If $j is 0, then an error condition is raised; # otherwise, assuming infinite-precision integer arithmetic, # if the input and $j are integers, then the result will be an integer. def idivide($i; $j): ($i % $j) as $mod | ($i - $mod) / $j ; def idivide($j): idivide(.; $j);   # input should be a non-negative integer for accuracy # but may be any non-negative finite number def isqrt: def irt: . as $x | 1 | until(. > $x; . * 4) as $q | {$q, $x, r: 0} | until( .q <= 1; .q |= idivide(4) | .t = .x - .r - .q | .r |= idivide(2) | if .t >= 0 then .x = .t | .r += .q else . end) | .r ; if type == "number" and (isinfinite|not) and (isnan|not) and . >= 0 then irt else "isqrt requires a non-negative integer for accuracy" | error 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.
#Julia
Julia
function pell(n) x = BigInt(floor(sqrt(n))) y, z, r = x, BigInt(1), x << 1 e1, e2, f1, f2 = BigInt(1), BigInt(0), BigInt(0), BigInt(1) while true y = r * z - y z = div(n - y * y, z) r = div(x + y, z) e1, e2 = e2, e2 * r + e1 f1, f2 = f2, f2 * r + f1 a, b = f2, e2 b, a = a, a * x + b if a * a - n * b * b == 1 return a, b end end end   for target in BigInt[61, 109, 181, 277] x, y = pell(target) println("x\u00b2 - $target", "y\u00b2 = 1 for x = $x and y = $y") 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
#Red
Red
Red [ Source: https://github.com/vazub/rosetta-red Tabs: 4 Needs: 'View ]   canvas: 500x500 center: as-pair canvas/x / 2 canvas/y / 2 radius: 200   points: collect [ repeat vertex 10 [ angle: vertex * 36 + 18 ;-- +18 is required for pentagram rotation either vertex // 2 = 1 [ keep as-pair (cosine angle) * radius + center/x (sine angle) * radius + center/y ][ keep as-pair (cosine angle) * radius * 0.382 + center/x (sine angle) * radius * 0.382 + center/y ] ] ]   view [ title "Pentagram" base canvas white draw compose/deep [ fill-pen mint polygon (points) line-width 3 line (points/1) (points/5) (points/9) (points/3) (points/7) (points/1) ] ]  
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
#REXX
REXX
/* REXX *************************************************************** * Create a BMP file showing a pentagram **********************************************************************/ Parse Version v If pos('Regina',v)>0 Then pentagram='pentagrama.bmp' Else pentagram='pentagramx.bmp' 'erase' pentagram s='424d4600000000000000360000002800000038000000280000000100180000000000'X||, '1000000000000000000000000000000000000000'x Say 'sl='length(s) z.0=0 white='ffffff'x red ='00ff00'x green='ff0000'x blue ='0000ff'x rd6=copies(rd,6) m=133 m=80 n=80 hor=m*8 /* 56 */ ver=n*8 /* 40 */ Say 'hor='hor Say 'ver='ver Say 'sl='length(s) s=overlay(lend(hor),s,19,4) s=overlay(lend(ver),s,23,4) Say 'sl='length(s) z.=copies('ffffff'x,3192%3) z.=copies('ffffff'x,8*m) z.0=648 pi_5=2*3.14159/5 s72 =sin(pi_5 ) c72 =cos(pi_5 ) s144=sin(pi_5*2) c144=cos(pi_5*2) xm=300 ym=300 r=200 p.0x.1=xm p.0y.1=ym+r   p.0x.2=format(xm+r*s72,3,0) p.0y.2=format(ym+r*c72,3,0) p.0x.3=format(xm+r*s144,3,0) p.0y.3=format(ym+r*c144,3,0) p.0x.4=format(xm-r*s144,3,0) p.0y.4=p.0y.3 p.0x.5=format(xm-r*s72,3,0) p.0y.5=p.0y.2 Do i=1 To 5 Say p.0x.i p.0y.i End Call line p.0x.1,p.0y.1,p.0x.3,p.0y.3 Call line p.0x.1,p.0y.1,p.0x.4,p.0y.4 Call line p.0x.2,p.0y.2,p.0x.4,p.0y.4 Call line p.0x.2,p.0y.2,p.0x.5,p.0y.5 Call line p.0x.3,p.0y.3,p.0x.5,p.0y.5   Do i=1 To z.0 s=s||z.i End   Call lineout pentagram,s Call lineout pentagram Exit   lend: Return reverse(d2c(arg(1),4))   line: Procedure Expose z. red green blue Parse Arg x0, y0, x1, y1 Say 'line' x0 y0 x1 y1 dx = abs(x1-x0) dy = abs(y1-y0) if x0 < x1 then sx = 1 else sx = -1 if y0 < y1 then sy = 1 else sy = -1 err = dx-dy   Do Forever xxx=x0*3+2 Do yy=y0-1 To y0+1 z.yy=overlay(copies(blue,5),z.yy,xxx) End if x0 = x1 & y0 = y1 Then Leave e2 = 2*err if e2 > -dy then do err = err - dy x0 = x0 + sx end if e2 < dx then do err = err + dx y0 = y0 + sy end end Return   sin: Procedure /* REXX **************************************************************** * Return sin(x<,p>) -- with the specified precision ***********************************************************************/ Parse Arg x,prec If prec='' Then prec=9 Numeric Digits (2*prec) Numeric Fuzz 3 pi=3.14159 Do While x>pi x=x-pi End Do While x<-pi x=x+pi End o=x u=1 r=x Do i=3 By 2 ra=r o=-o*x*x u=u*i*(i-1) r=r+(o/u) If r=ra Then Leave End Numeric Digits prec Return r+0   cos: Procedure /* REXX **************************************************************** * Return cos(x) -- with specified precision ***********************************************************************/ Parse Arg x,prec If prec='' Then prec=9 Numeric Digits (2*prec) Numeric Fuzz 3 o=1 u=1 r=1 Do i=1 By 2 ra=r o=-o*x*x u=u*i*(i+1) r=r+(o/u) If r=ra Then Leave End Numeric Digits prec Return r+0   sqrt: Procedure /* REXX *************************************************************** * EXEC to calculate the square root of a = 2 with high precision **********************************************************************/ Parse Arg x,prec If prec<9 Then prec=9 prec1=2*prec eps=10**(-prec1) k = 1 Numeric Digits 3 r0= x r = 1 Do i=1 By 1 Until r=r0 | (abs(r*r-x)<eps) r0 = r r = (r + x/r) / 2 k = min(prec1,2*k) Numeric Digits (k + 5) End Numeric Digits prec Return r+0
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 ;;; MS-DOS syscalls gettim: equ 2Ch ; Get system time write: equ 40h ; Write to file exit: equ 4Ch ; Exit with return code ;;; MS-DOS process data arg: equ 80h ; Command line argument (length + string) ;;; BIOS calls conout: equ 0Eh ; Write character to console vstate: equ 0Fh ; Get current video state section .text org 100h mov ah,gettim ; Seed the RNG using the system time int 21h ; (in case of no argument) mov [rnddat],cx mov [rnddat+2],dx mov si,arg ; See if we have any arguments lodsb test al,al jnz hasarg jmp usage ; If not, print usage string ;;; Parse the command line arguments hasarg: xor bx,bx ; We do, zero-terminate the string xchg al,bl mov [si+bx],al mov di,count ; Place to start reading arguments doarg: lodsb ; Get argument byte .chr: test al,al ; Zero? jnz .arg ; If not, there are arguments left jmp check ; If so, we're done .arg: cmp al,' ' ; Space? je doarg ; Then get next character cmp al,'/' ; Option? je opt dec byte [nargs] ; Otherwise, it's an argument jnz rdnum ; Read a number if we still need one jmp usage ; Otherwise, incorrect arguments rdnum: xor bp,bp ; Place to keep number .chr: mov bl,al ; Keep the character in case not a digit sub al,'0' ; Make into digit cmp al,9 ; Valid digit? ja .done ; If not, done with number add bp,bp ; Multiply accumulator by 10 mov dx,bp add bp,bp add bp,bp add bp,dx xor ah,ah ; Then add the digit add bp,ax lodsb ; Read next digit jmp .chr .done: mov ax,bp ; Write the number into memory stosw mov al,bl ; Restore the character (next argument) jmp doarg.chr opt: lodsb ; Get option character or al,32 ; Make lowercase cmp al,'e' ; E? je .e cmp al,'s' ; S? je .s jmp usage ; If not, invalid argument .e: inc byte [excl] ; /E: turn on exclusion jmp doarg .s: lodsb ; /S: should be followed by '=' cmp al,'=' je .s_ok jmp usage ; If not, invalid argument .s_ok: xor bp,bp ; DX:BP = RNG state xor dx,dx .hex: lodsb ; Get (potential) hex digit mov ah,al ; Keep it around call hexdgt ; Parse hexadecimal digit jnc .hdone ; If invalid, we're done shl bp,1 ; Make room for it in the state rcl dx,1 ; Because it's a 32-bit value, shl bp,1 ; which is stored in two 16-bit registers, rcl dx,1 ; we have to shift and rotate the bits shl bp,1 ; one by one. rcl dx,1 shl bp,1 rcl dx,1 or dl,al ; Finally, add in the hexadecimal digit jmp .hex .hdone: mov [rnddat],bp ; Store random seed mov [rnddat+2],dx mov al,ah ; Restore the next character jmp doarg.chr ;;; Check the arguments check: dec byte [nargs] ; Were all arguments used? jz .argok jmp usage .argok: mov cx,[count] ; CX = count mov bp,[length] ; BP = length test cx,cx ; Sanity check (count must not be zero) mov si,errmsg.cnt jnz .cntok jmp error .cntok: cmp bp,4 ; Length must be at least four mov si,errmsg.len jae .len2 jmp error .len2: cmp bp,255 ; Length must be no more than 255 mov si,errmsg.lmax jbe mkmask jmp error ;;; Make a bitmask in which BP fits (for generating random ;;; numbers in the right range) mkmask: mov cx,bp mov bx,cx .loop: shr cx,1 or bx,cx test cx,cx jnz .loop stc rcl bx,1 mov [lmask],bl ; Password <= 255 chars ;;; Generate a password genpwd: lea cx,[bp-4] ; Get length minus four mov di,buffer ; Write password into buffer mov dl,[excl] ; Exclusion flag mov bx,lc ; A lowercase letter, mov ah,lc.len call rndchr mov bx,uc ; An uppercase letter call rndchr ; (same length of course) mov bx,dgt ; A digit, mov ah,dgt.len call rndchr mov bx,sym ; And a symbol mov ah,sym.len call rndchr test cx,cx ; If CX=0, we need no extra characters jz .done mov bx,cr ; Otherwise, we need CX extra characters mov ah,cr.len .loop: call rndchr loop .loop .done: mov ax,0A0Dh ; End with a newline stosw ;;; Swap the first four characters with random characters ;;; from the password, so the four necessary characters won't ;;; necessarily be at the beginning. swap: mov dx,bp ; Get length mov dh,[lmask] ; Load the mask mov si,buffer ; Password buffer xor bh,bh xor ah,ah ; Starting at zero .loc: call rand ; Get random byte and al,dh ; Mask off unused bits cmp al,dl ; Result within password? jae .loc ; If not, get another random number mov bl,ah ; Load first character in CL mov cl,[si+bx] mov bl,al ; Load random character in CH mov ch,[si+bx] mov [si+bx],cl ; Write them back the other way around mov bl,ah mov [si+bx],ch inc ah ; Next character cmp ah,4 ; Are we there yet? jb .loc ; If not, do another character. ;;; Write password to standard output xor bx,bx ; File handle 0 = stdout lea cx,[bp+2] ; Length = password length + 2 (for newline) mov dx,si ; Location of password mov ah,write ; Write the password int 21h jnc .ok ; Carry clear = success mov si,errmsg.wrt ; Otherwise, print error message jmp error .ok: dec word [count] ; Need any more passwords? jz stop ; If not, stop jmp genpwd ; Otherwise, make another password ;;; Quit with return code 0 (success) stop: mov ax,exit<<8 int 21h ;;; Generate a random character. BX=table, AH=length, ;;; DL=exclusion on/off rndchr: call rand ; Random number and al,7Fh ; from 0 to 127 cmp al,ah ; Within valid length? jae rndchr ; If not, get new random number xlatb ; Otherwise, get character from table test dl,dl ; Is exclusion on? jz .out ; If not, just store it push cx ; Otherwise, keep CX around, push di ; and DI, mov cx,ex.len ; See if character is in exclusion table mov di,ex repne scasb pop di ; restore DI pop cx ; Restore CX je rndchr ; And if it was found, get another character .out: stosb ; Store in password buffer ret ;;; Random number generator using XABC algorithm ;;; Returns random byte in AL rand: push cx push dx mov cx,[rnddat] ; CH=X CL=A mov dx,[rnddat+2] ; DH=B DL=C inc ch ; X++ xor cl,ch ; A ^= X xor cl,dl ; A ^= C add dh,cl ; B += A mov al,dh ; C' = B shr al,1 ; C' >>= 1 xor al,cl ; C' ^= A add al,dl ; C' += C mov dl,al ; C = C' mov [rnddat],cx mov [rnddat+2],dx pop dx pop cx ret ;;; If AL is a hexadecimal digit in ASCII, set AL to be its ;;; value. Carry flag set if digit was valid. hexdgt: or al,32 ; Make letter lowercase (numbers unchanged) sub al,'0' ; Subtract 0 cmp al,10 ; If it is a valid digit now, we're done jc .out sub al,39 ; Otherwise, correct for cmp al,17 .out: ret ;;; Write the help message, and stop with return code 2 usage: mov si,help ;;; Write an error message, directly to the console, bypassing ;;; DOS to ensure it does not end up in the redirected output. ;;; Then, stop with return code 2 (failure) error: mov ah,vstate ; Retrieve current video state int 10h ; (this sets BH = current page) .loop lodsb ; Get string byte test al,al ; Zero? jz .out ; Then we have reached the end mov ah,conout ; Otherwise, write the character int 10h jmp .loop ; And get another one .out: mov ax,exit<<8|2 ; Stop with error code 2 int 21h section .data nargs: db 3 ; We need two non-option arguments excl: db 0 ; Exclusion is off by default cr: ;;; Password characters lc: db 'abcdefghijklmnopqrstuvwxyz' .len: equ $-lc uc: db 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .len: equ $-uc dgt: db '0123456789' .len: equ $-dgt sym: db '!"#$%&()*+,-./:;<=>?@[]^_{|}~',39 ; 39=single quote .len: equ $-sym cr.len: equ $-cr ex: db 'Il1O05S2Z' ; Excluded characters .len: equ $-ex ;;; Help message help: db 'PASSGEN [/S=seed] [/E] count length',13,10 db 9,'generate <count> passwords of length <length>',13,10 db 13,10 db 9,'/S=seed: set RNG seed (hexadecimal number)',13,10 db 9,'/E: exclude visually similar characters',13,10 db 0 errmsg: ;;; Error messages .len: db 'Minimum password length is 4.',0 .lmax: db 'Maximum password length is 255.',0 .cnt: db 'At least one password must be generated.',0 .wrt: db 'Write error.',0 section .bss count: resw 1 ; Amount of passwords to generate length: resw 1 ; Length of passwords lmask: resb 1 ; Mask for random number generation rnddat: resb 4 ; RNG state buffer: resb 257 ; Space to store password
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
#PureBasic
PureBasic
Macro reverse(firstIndex, lastIndex) first = firstIndex last = lastIndex While first < last Swap cur(first), cur(last) first + 1 last - 1 Wend EndMacro   Procedure nextPermutation(Array cur(1)) Protected first, last, elementCount = ArraySize(cur()) If elementCount < 1 ProcedureReturn #False ;nothing to permute EndIf   ;Find the lowest position pos such that [pos] < [pos+1] Protected pos = elementCount - 1 While cur(pos) >= cur(pos + 1) pos - 1 If pos < 0 reverse(0, elementCount) ProcedureReturn #False ;no higher lexicographic permutations left, return lowest one instead EndIf Wend   ;Swap [pos] with the highest positional value that is larger than [pos] last = elementCount While cur(last) <= cur(pos) last - 1 Wend Swap cur(pos), cur(last)   ;Reverse the order of the elements in the higher positions reverse(pos + 1, elementCount) ProcedureReturn #True ;next lexicographic permutation found EndProcedure   Procedure display(Array a(1)) Protected i, fin = ArraySize(a()) For i = 0 To fin Print(Str(a(i))) If i = fin: Continue: EndIf Print(", ") Next PrintN("") EndProcedure   If OpenConsole() Dim a(2) a(0) = 1: a(1) = 2: a(2) = 3 display(a()) While nextPermutation(a()): display(a()): Wend   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Factor
Factor
USING: accessors L-system ui ;   : peano ( L-system -- L-system ) L-parser-dialect >>commands [ 90 >>angle ] >>turtle-values "L" >>axiom { { "L" "LFRFL-F-RFLFR+F+LFRFL" } { "R" "RFLFR+F+LFRFL-F-RFLFR" } } >>rules ;   [ <L-system> peano "Peano curve" open-window ] with-ui
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#F.C5.8Drmul.C3.A6
Fōrmulæ
Const anchura = 243 'una potencia de 3 para una curva uniformemente espaciada   Screenres 700,700   Sub Peano(x As Integer, y As Integer, lg As Integer, i1 As Integer, i2 As Integer) If lg = 1 Then Line - (x * 3, y * 3) Return End If lg /= 3 Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Peano(x + lg, y + lg, lg, i1, 1 - i2) Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub   Peano(0, 0, anchura, 0, 0)   Sleep
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#C.2B.2B
C++
  #include <time.h> #include <iostream> #include <string>   using namespace std;   class penney { public: penney() { pW = cW = 0; } void gameLoop() { string a; while( true ) { playerChoice = computerChoice = ""; if( rand() % 2 ) { computer(); player(); } else { player(); computer(); }   play();   cout << "[Y] to play again "; cin >> a; if( a[0] != 'Y' && a[0] != 'y' ) { cout << "Computer won " << cW << " times." << endl << "Player won " << pW << " times."; break; } cout << endl << endl; } } private: void computer() { if( playerChoice.length() == 0 ) { for( int x = 0; x < 3; x++ ) computerChoice.append( ( rand() % 2 ) ? "H" : "T", 1 ); } else { computerChoice.append( playerChoice[1] == 'T' ? "H" : "T", 1 ); computerChoice += playerChoice.substr( 0, 2 ); } cout << "Computer's sequence of three is: " << computerChoice << endl; } void player() { cout << "Enter your sequence of three (H/T) "; cin >> playerChoice; } void play() { sequence = ""; while( true ) { sequence.append( ( rand() % 2 ) ? "H" : "T", 1 ); if( sequence.find( playerChoice ) != sequence.npos ) { showWinner( 1 ); break; } else if( sequence.find( computerChoice ) != sequence.npos ) { showWinner( 0 ); break; } } } void showWinner( int i ) { string s; if( i ) { s = "Player wins!"; pW++; } else { s = "Computer wins!"; cW++; } cout << "Tossed sequence: " << sequence << endl << s << endl << endl; } string playerChoice, computerChoice, sequence; int pW, cW; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned>( time( NULL ) ) ); penney game; game.gameLoop(); return 0; }  
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Clojure
Clojure
(def converge-to-six ((fn task1 [a b] (lazy-seq (cons a (task1 b (+ (- 111 (/ 1130 b)) (/ 3000 (* b a))))))) 2 -4)) (def values [3 4 5 6 7 8 20 30 50 100]) ; print decimal values: (pprint (sort (zipmap values (map double (map #(nth converge-to-six (dec %)) values))))) ; print rational values: (pprint (sort (zipmap values (map #(nth converge-to-six (dec %)) values))))
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.
#Kotlin
Kotlin
import java.math.BigInteger import kotlin.math.sqrt   class BIRef(var value: BigInteger) { operator fun minus(b: BIRef): BIRef { return BIRef(value - b.value) }   operator fun times(b: BIRef): BIRef { return BIRef(value * b.value) }   override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false   other as BIRef   if (value != other.value) return false   return true }   override fun hashCode(): Int { return value.hashCode() }   override fun toString(): String { return value.toString() } }   fun f(a: BIRef, b: BIRef, c: Int) { val t = a.value a.value = b.value b.value = b.value * BigInteger.valueOf(c.toLong()) + t }   fun solvePell(n: Int, a: BIRef, b: BIRef) { val x = sqrt(n.toDouble()).toInt() var y = x var z = 1 var r = x shl 1 val e1 = BIRef(BigInteger.ONE) val e2 = BIRef(BigInteger.ZERO) val f1 = BIRef(BigInteger.ZERO) val f2 = BIRef(BigInteger.ONE) while (true) { y = r * z - y z = (n - y * y) / z r = (x + y) / z f(e1, e2, r) f(f1, f2, r) a.value = f2.value b.value = e2.value f(b, a, x) if (a * a - BIRef(n.toBigInteger()) * b * b == BIRef(BigInteger.ONE)) { return } } }   fun main() { val x = BIRef(BigInteger.ZERO) val y = BIRef(BigInteger.ZERO) intArrayOf(61, 109, 181, 277).forEach { solvePell(it, x, y) println("x^2 - %3d * y^2 = 1 for x = %,27d and y = %,25d".format(it, x.value, y.value)) } }
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
#Ring
Ring
  # Project : Pentagram   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Pentagram") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,10,400,400) settext("") } new qpushbutton(win1) { setgeometry(150,500,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(5) } paint = new qpainter() { begin(p1) setpen(pen)   nn = 165 cx = 800 cy = 600 phi = 54   color = new qcolor() color.setrgb(0, 0, 255,255) mybrush = new qbrush() {setstyle(1) setcolor(color)} setbrush(mybrush)   for n = 1 to 5 theta = fabs(180-144-phi) p1x = floor(cx + nn * cos(phi * 0.01745329252)) p1y = floor(cy + nn * sin(phi * 0.01745329252)) p2x = floor(cx - nn * cos(theta * 0.01745329252)) p2y = floor(cy - nn * sin(theta * 0.01745329252)) phi+= 72 drawpolygon([[p1x,p1y],[cx,cy],[p2x,p2y]],0) next   endpaint() } label1 { setpicture(p1) show() } return  
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
#Scala
Scala
import java.awt._ import java.awt.geom.Path2D   import javax.swing._   object Pentagram extends App {   SwingUtilities.invokeLater(() => new JFrame("Pentagram") {   class Pentagram extends JPanel { setPreferredSize(new Dimension(640, 640)) setBackground(Color.white) final private val degrees144 = Math.toRadians(144)   override def paintComponent(gg: Graphics): Unit = { val g = gg.asInstanceOf[Graphics2D]   def drawPentagram(g: Graphics2D, x: Int, y: Int, fill: Color): Unit = { var (_x, _y, angle) = (x, y, 0.0) val p = new Path2D.Float p.moveTo(_x, _y) for (i <- 0 until 5) { val (x2, y2) = (_x + (Math.cos(angle) * 500).toInt, _y + (Math.sin(-angle) * 500).toInt) p.lineTo(x2, y2) _x = x2 _y = y2 angle -= degrees144 } p.closePath() g.setColor(fill) g.fill(p) g.setColor(Color.darkGray) g.draw(p) }   super.paintComponent(gg) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)) drawPentagram(g, 70, 250, new Color(0x6495ED)) } }   add(new Pentagram, BorderLayout.CENTER) pack() setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(false) setVisible(true) } )   }
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Action.21
Action!
BYTE FUNC GetNumParam(CHAR ARRAY text BYTE min,max) BYTE res   DO PrintF("Input %S (%B-%B): ",text,min,max) res=InputB() UNTIL res>=min AND res<=max OD RETURN (res)   BYTE FUNC GetBoolParam(CHAR ARRAY text) CHAR ARRAY s(255)   DO PrintF("%S? (Y/N): ",text) InputS(s) IF s(0)=1 THEN IF s(1)='y OR s(1)='Y THEN RETURN (1) ELSEIF s(1)='n OR s(1)='N THEN RETURN (0) FI FI OD RETURN (0)   PROC Shuffle(CHAR ARRAY s) BYTE i,j CHAR tmp   i=s(0) WHILE i>1 DO j=Rand(i)+1 tmp=s(i) s(i)=s(j) s(j)=tmp i==-1 OD RETURN   BYTE FUNC Contains(CHAR ARRAY s CHAR c) BYTE i   IF s(0)=0 THEN RETURN (0) FI FOR i=1 TO s(0) DO IF s(i)=c THEN RETURN (1) FI OD RETURN (0)   CHAR FUNC RandChar(CHAR ARRAY s,unsafe) BYTE len CHAR c   len=s(0) DO c=s(Rand(len)+1) UNTIL Contains(unsafe,c)=0 OD RETURN (c)   PROC Generate(CHAR ARRAY res BYTE len,safe) DEFINE PTR="CARD" CHAR ARRAY st, upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ", lower="abcdefghijklmnopqrstuvwxyz", numbers="0123456789", special="!""#$%&'()*+,-./:;<=>?@[]^_|", unsafe="Il1O05S2Z" PTR ARRAY sets(4) BYTE i   sets(0)=upper sets(1)=lower sets(2)=numbers sets(3)=special   res(0)=len FOR i=1 TO len DO IF safe THEN res(i)=RandChar(sets(i MOD 4),unsafe) ELSE res(i)=RandChar(sets(i MOD 4),"") FI OD Shuffle(res) RETURN   PROC PrintHelp() PutE() PrintE("Program generates random passwords") PrintE("containing at least one upper-case") PrintE("letter, one lower-case letter, one") PrintE("digit and one special character.") PrintE("It is possible to exclude visually") PrintE("similar characters Il1O05S2Z.") PutE() RETURN   PROC Main() BYTE len,count,safe,i,again,help CHAR ARRAY password(255)   help=GetBoolParam("Show help") IF help THEN PrintHelp() FI   DO len=GetNumParam("length of password",4,30) safe=GetBoolParam("Exclude similar chars") count=GetNumParam("number of passwords",1,10) PutE() FOR i=1 TO count DO Generate(password,len,safe) PrintF("%B. %S%E",i,password) OD PutE() again=GetBoolParam("Generate again") UNTIL again=0 OD 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
#Python
Python
import itertools for values in itertools.permutations([1,2,3]): print (values)
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#FreeBASIC
FreeBASIC
Const anchura = 243 'una potencia de 3 para una curva uniformemente espaciada   Screenres 700,700   Sub Peano(x As Integer, y As Integer, lg As Integer, i1 As Integer, i2 As Integer) If lg = 1 Then Line - (x * 3, y * 3) Return End If lg /= 3 Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Peano(x + lg, y + lg, lg, i1, 1 - i2) Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub   Peano(0, 0, anchura, 0, 0)   Sleep
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#Clojure
Clojure
(ns penney.core (:gen-class))   (def heads \H) (def tails \T)   (defn flip-coin [] (let [flip (rand-int 2)] (if (= flip 0) heads tails)))   (defn turn [coin] (if (= coin heads) tails heads))   (defn first-index [combo coll] (some #(if (= (second %) combo) (first %)) coll))   (defn find-winner [h c] (if (< h c) (do (println "YOU WIN!\n") :human) (do (println "COMPUTER WINS!\n") :computer)))   (defn flip-off [human comp] (let [flips (repeatedly flip-coin) idx-flips (map-indexed vector (partition 3 1 flips)) h (first-index (seq human) idx-flips) c (first-index (seq comp) idx-flips)] (println (format "Tosses: %s" (apply str (take (+ 3 (min h c)) flips)))) (find-winner h c)))   (defn valid? [combo] (if (empty? combo) true (and (= 3 (count combo)) (every? #(or (= heads %) (= tails %)) combo))))   (defn ask-move [] (println "What sequence of 3 Heads/Tails do you choose?") (let [input (clojure.string/upper-case (read-line))] (if-not (valid? input) (recur) input)))   (defn optimize-against [combo] (let [mid (nth combo 1) comp (str (turn mid) (first combo) mid)] (println (format "Computer chooses %s: " comp)) comp))   (defn initial-move [game] (let [combo (apply str (repeatedly 3 flip-coin))] (println "--------------") (println (format "Current score | CPU: %s, You: %s" (:computer game) (:human game))) (if (= (:first-player game) tails) (do (println "Computer goes first and chooses: " combo) combo) (println "YOU get to go first."))))   (defn play-game [game] (let [c-move (initial-move game) h-move (ask-move)] (if-not (empty? h-move) (let [winner (flip-off h-move (if (nil? c-move) (optimize-against h-move) c-move))] (recur (assoc game winner (inc (winner game)) :first-player (flip-coin)))) (println "Thanks for playing!"))))   (defn -main [& args] (println "Penney's Game.") (play-game {:first-player (flip-coin)  :human 0, :computer 0}))
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Crystal
Crystal
require "big"   ar = [0.to_big_d, 2.to_big_d, -4.to_big_d]   100.times { ar << 111 - 1130.to_big_d.div(ar[-1], 132) + 3000.to_big_d.div((ar[-1] * ar[-2]), 132) }   [3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n| puts "%3d -> %0.16f" % [n, ar[n]] 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.
#langur
langur
val .fun = f [.b, .b x .c + .a]   val .solvePell = f(.n) { val .x = truncate .n ^/ 2 var .y, .z, .r = .x, 1, .x x 2 var .e1, .e2, .f1, .f2 = 1, 0, 0, 1   for { .y = .r x .z - .y .z = (.n - .y x .y) \ .z .r = (.x + .y) \ .z .e1, .e2 = .fun(.e1, .e2, .r) .f1, .f2 = .fun(.f1, .f2, .r) val .b, .a = .fun(.e2, .f2, .x) if .a^2 - .n x .b^2 == 1: return [.a, .b] } }   val .C = f(.x) { # format number string with commas var .neg, .s = ZLS, toString .x if .s[1] == '-' { .neg, .s = "-", rest .s } .neg ~ join ",", split -3, .s }   for .n in [61, 109, 181, 277, 8941] { val .x, .y = .solvePell(.n) writeln $"x² - \.n;y² = 1 for:\n\tx = \.x:.C;\n\ty = \.y:.C;\n" }  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FindInstance[x^2 - 61 y^2 == 1, {x, y}, PositiveIntegers] FindInstance[x^2 - 109 y^2 == 1, {x, y}, PositiveIntegers] FindInstance[x^2 - 181 y^2 == 1, {x, y}, PositiveIntegers] FindInstance[x^2 - 277 y^2 == 1, {x, y}, PositiveIntegers]
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
#Sidef
Sidef
func pentagram(dim=200, sides=5) { var pentagram = <<-EOT <?xml version="1.0" standalone="no" ?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd"> <svg height="#{dim*2}" width="#{dim*2}" style="" xmlns="http://www.w3.org/2000/svg"> <rect height="100%" width="100%" style="fill:black;" /> EOT   func cis(x) { cos(x) + sin(x).i }   func pline(q) { <<-EOT <polyline points="#{[q..., q[0], q[1]].map{|n| '%0.3f' % n }.join(' ')}" style="fill:blue; stroke:white; stroke-width:3;" transform="translate(#{dim}, #{dim}) rotate(-18)" /> EOT }   var v = sides.range.map {|k| 0.9 * dim * cis(k * Num.tau / sides) } pentagram += pline([v[range(0, v.end, 2)], v[range(1, v.end, 2)]].map{.reals}) pentagram += '</svg>'   return pentagram }   say pentagram()
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Ada
Ada
with Ada.Numerics.Discrete_Random; with Ada.Strings.Fixed; with Ada.Command_Line; with Ada.Integer_Text_IO; with Ada.Text_IO;   procedure Mkpw is   procedure Put_Usage; procedure Parse_Command_Line (Success : out Boolean); function Create_Password (Length : in Positive; Safe  : in Boolean) return String;   procedure Put_Usage is use Ada.Text_IO; begin Put_Line ("Usage: "); Put_Line (" mkpw help - Show this help text "); Put_Line (" mkpw [count <n>] [length <l>] [seed <s>] [safe] "); Put_Line (" count <n> - Number of passwords generated (default 4)"); Put_Line (" length <l> - Password length (min 4) (default 4)"); Put_Line (" seed <l> - Seed for random generator (default 0)"); Put_Line (" safe - Do not use unsafe characters (0O1lIS52Z)"); end Put_Usage;   Lower_Set  : constant String := "abcdefghijklmnopqrstuvwxyz"; Upper_Set  : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Digit_Set  : constant String := "0123456789"; Spec_Set  : constant String := "!""#$%&'()*+,-./:;<=>?@[]^_{|}~"; Unsafe_Set : constant String := "0O1lI5S2Z";   Full_Set : constant String := Lower_Set & Upper_Set & Digit_Set & Spec_Set; subtype Full_Indices is Positive range Full_Set'Range;   package Full_Index_Generator is new Ada.Numerics.Discrete_Random (Full_Indices);   Index_Generator : Full_Index_Generator.Generator;   Config_Safe  : Boolean  := False; Config_Count  : Natural  := 4; Config_Length  : Positive := 6; Config_Seed  : Integer  := 0; Config_Show_Help  : Boolean  := False;   procedure Parse_Command_Line (Success : out Boolean) is use Ada.Command_Line; Got_Safe, Got_Count : Boolean  := False; Got_Length, Got_Seed  : Boolean  := False; Last  : Positive; Index  : Positive := 1; begin Success := False; if Argument_Count = 1 and then Argument (1) = "help" then Config_Show_Help := True; return; end if;   while Index <= Argument_Count loop if Ada.Command_Line.Argument (Index) = "safe" then if Got_Safe then return; end if; Got_Safe := True; Config_Safe  := True; Index := Index + 1; elsif Argument (Index) = "count" then if Got_Count then return; end if; Got_Count := True; Ada.Integer_Text_IO.Get (Item => Config_Count, From => Argument (Index + 1), Last => Last); if Last /= Argument (Index + 1)'Last then return; end if; Index := Index + 2; elsif Argument (Index) = "length" then if Got_Length then return; end if; Got_Length := True; Ada.Integer_Text_IO.Get (Item => Config_Length, From => Argument (Index + 1), Last => Last); if Last /= Argument (Index + 1)'Last then return; end if; if Config_Length < 4 then return; end if; Index := Index + 2; elsif Argument (Index) = "seed" then if Got_Seed then return; end if; Got_Seed := True; Ada.Integer_Text_IO.Get (Item => Config_Seed, From => Argument (Index + 1), Last => Last); if Last /= Argument (Index + 1)'Last then return; end if; Index := Index + 2; else return; end if; end loop; Success := True; exception when Constraint_Error | Ada.Text_IO.Data_Error => null; end Parse_Command_Line;   function Create_Password (Length : in Positive; Safe  : in Boolean) return String is   function Get_Random (Safe : in Boolean) return Character;   function Get_Random (Safe : in Boolean) return Character is use Ada.Strings.Fixed; C : Character; begin loop C := Full_Set (Full_Index_Generator.Random (Index_Generator)); if Safe then exit when Index (Source => Unsafe_Set, Pattern => "" & C) = 0; else exit; end if; end loop; return C; end Get_Random;   function Has_Four (Item : in String) return Boolean;   function Has_Four (Item : in String) return Boolean is use Ada.Strings.Fixed; Has_Upper, Has_Lower : Boolean := False; Has_Digit, Has_Spec  : Boolean := False; begin for C of Item loop if Index (Upper_Set, "" & C) /= 0 then Has_Upper := True; end if; if Index (Lower_Set, "" & C) /= 0 then Has_Lower := True; end if; if Index (Digit_Set, "" & C) /= 0 then Has_Digit := True; end if; if Index (Spec_Set, "" & C) /= 0 then Has_Spec  := True; end if; end loop; return Has_Upper and Has_Lower and Has_Digit and Has_Spec; end Has_Four;   Password : String (1 .. Length); begin loop for I in Password'Range loop Password (I) := Get_Random (Safe); end loop; exit when Has_Four (Password); end loop; return Password; end Create_Password;   Parse_Success : Boolean; begin   Parse_Command_Line (Parse_Success);   if Config_Show_Help or not Parse_Success then Put_Usage; return; end if;   if Config_Seed = 0 then Full_Index_Generator.Reset (Index_Generator); else Full_Index_Generator.Reset (Index_Generator, Config_Seed); end if;   for Count in 1 .. Config_Count loop Ada.Text_IO.Put_Line (Create_Password (Length => Config_Length, Safe => Config_Safe)); end loop;   end Mkpw;
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
#QBasic
QBasic
SUB perms (n) DIM a(0 TO n - 1), c(0 TO n - 1)   FOR j = 0 TO n - 1 a(j) = j + 1 PRINT a(j); NEXT j PRINT   i = 0 WHILE i < n IF c(i) < i THEN IF (i AND 1) = 0 THEN SWAP a(0), a(i) ELSE SWAP a(c(i)), a(i) END IF FOR j = 0 TO n - 1 PRINT a(j); NEXT j PRINT c(i) = c(i) + 1 i = 0 ELSE c(i) = 0 i = i + 1 END IF WEND END SUB   perms(4)
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Go
Go
package main   import "github.com/fogleman/gg"   var points []gg.Point   const width = 81   func peano(x, y, lg, i1, i2 int) { if lg == 1 { px := float64(width-x) * 10 py := float64(width-y) * 10 points = append(points, gg.Point{px, py}) return } lg /= 3 peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2) peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2) peano(x+lg, y+lg, lg, i1, 1-i2) peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2) peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2) peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2) peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2) peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2) peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2) }   func main() { peano(0, 0, width, 0, 0) dc := gg.NewContext(820, 820) dc.SetRGB(1, 1, 1) // White background dc.Clear() for _, p := range points { dc.LineTo(p.X, p.Y) } dc.SetRGB(1, 0, 1) // Magenta curve dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("peano.png") }
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#Common_Lisp
Common Lisp
(setf *random-state* (make-random-state t))   (defparameter *heads* #\H) (defparameter *tails* #\T)   (defun main () (format t "Penney's Game~%~%") (format t "Flipping to see who goes first ...")   (setq p2 nil) (if (string= (flip) *heads*) (progn (format t " I do.~%") (setq p2 (choose-random-sequence)) (format t "I choose: ~A~%" p2)) (format t "You do.~%"))   (setq p1 nil) (loop while (null p1) doing (format t "Enter your three-flip sequence: ") (setq p1 (string (read))) (cond ((/= (length p1) 3) (format t "Sequence must consist of three flips.~%") (setq p1 nil)) ((string= p1 p2) (format t "Sequence must be different from mine.~%") (setq p1 nil)) ((notevery #'valid? (coerce p1 'list)) (format t "Sequence must be contain only ~A's and ~A's.~%" *heads* *tails*) (setq p1 nil)))) (format t "You picked: ~A~%" p1)   (if (null p2) (progn (setq p2 (choose-optimal-sequence p1)) (format t "I choose: ~A~%" p2)))   (format t "Here we go. ~A, you win; ~A, I win.~%" p1 p2) (format t "Flips:") (let ((winner nil) (flips '())) (loop while (null winner) doing (setq flips (cons (flip) flips)) (format t " ~A" (car flips)) (if (>= (length flips) 3) (let ((trail (coerce (reverse (subseq flips 0 3)) 'string))) (cond ((string= trail p1) (setq winner "You")) ((string= trail p2) (setq winner "I")))))) (format t "~&~A win!" winner)))   (defparameter *sides* (list *heads* *tails*)) (defun flip () (nth (random 2 *random-state*) *sides*))   (defun valid? (flip) (not (null (member flip *sides*))))   (defun opposite (flip) (if (string= flip *heads*) *tails* *heads*))   (defun choose-random-sequence () (coerce (list (flip) (flip) (flip)) 'string))   (defun choose-optimal-sequence (against) (let* ((opposed (coerce against 'list)) (middle (cadr opposed)) (my-list (list (opposite middle) (car opposed) middle))) (coerce my-list 'string)))   (main)
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Delphi
Delphi
  program Pathological_floating_point_problems;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers, Velthuis.BigRationals, Velthuis.BigDecimals;   type TBalance = record e, d: BigInteger; end;   procedure Sequence(Precision: Integer); var v, v1, c111, c1130, c3000, t2, t3: BigRational; n: integer; begin BigDecimal.DefaultPrecision := Precision; v1 := 2; v := -4; n := 2; c111 := BigRational(111); c1130 := BigRational(1130); c3000 := BigRational(3000);   var r := function(): BigRational begin t3 := v * v1; t3 := BigRational.Create(BigDecimal.Divide(c3000, t3)); t2 := BigRational.Create(BigDecimal.Divide(c1130, v)); result := c111 - t2; result := result + t3; end;   writeln(' n sequence value');   for var x in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] do begin while n < x do begin var tmp := BigRational.Create(v); v := BigRational.Create(r()); v1 := BigRational.Create(tmp); inc(n); end;   var f := double(v); writeln(format('%3d %19.16f', [n, f])); end; end;   procedure Bank(); var balance: TBalance; m, one, ef, df: BigInteger; e, b: BigDecimal; begin balance.e := 1; balance.d := -1; one := BigInteger.One;   for var y := 1 to 25 do begin m := y; balance.e := m * balance.e; balance.d := m * balance.d; balance.d := balance.d - one; end;   e := BigDecimal.Create('2.71828182845904523536028747135');   ef := balance.e; df := balance.d;   b := e * ef; b := b + df;   writeln(format('Bank balance after 25 years: $%.2f', [b.AsDouble])); end;   function f(a, b: Double): Double; var a1, a2, b1, b2, b4, b6, b8, two, t1, t21, t2, t3, t4, t23: BigDecimal; begin var fp := function(x: double): BigDecimal begin Result := BigDecimal.Create(x); end;   a1 := fp(a); b1 := fp(b); a2 := a1 * a1; b2 := b1 * b1; b4 := b2 * b2; b6 := b2 * b4; b8 := b4 * b4;   two := fp(2); t1 := fp(333.75); t1 := t1 * b6; t21 := fp(11); t21 := t21 * a2 * b2; t23 := fp(121); t23 := t23 * b4;   t2 := t21 - b6; t2 := (t2 - t23) - two; t2 := a2 * t2;   t3 := fp(5.5); t3 := t3 * b8;   t4 := two * b1; t4 := a1 / t4;   var s := t1 + t2; s := s + t3; s := s + t4; result := s.AsDouble; end;   procedure Rump(); var a, b: Double; begin a := 77617; b := 33096; writeln(format('Rump f(%g, %g): %g', [a, b, f(a, b)])); end;   { TBigRationalHelper }     begin for var Precision in [100, 200] do begin writeln(#10'Precision: ', Precision); sequence(Precision); bank(); rump(); end;   readln; end.