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/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Type MyType Public: Declare Sub InstanceMethod(s As String) Declare Static Sub StaticMethod(s As String) Private: dummy_ As Integer ' types cannot be empty in FB End Type   Sub MyType.InstanceMethod(s As String) Print s End Sub   Static Sub MyType.StaticMethod(s As String) Print s End Sub   Dim t As MyType t.InstanceMethod("Hello world!") MyType.Staticmethod("Hello static world!") Print Print "Press any key to quit the program" Sleep  
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Delphi
Delphi
procedure DoSomething; external 'MYLIB.DLL';
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Forth
Forth
  c-library math   s" m" add-lib \c #include <math.h> c-function gamma tgamma r -- r   end-c-library  
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings;   procedure Test_C_Interface is function strdup (s1 : Char_Array) return Chars_Ptr; pragma Import (C, strdup, "_strdup");   S1 : constant String := "Hello World!"; S2 : Chars_Ptr; begin S2 := strdup (To_C (S1)); Put_Line (Value (S2)); Free (S2); end Test_C_Interface;
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Aikido
Aikido
#include <aikido.h> extern "C" { // need C linkage   // define the function using a macro defined in aikido.h AIKIDO_NATIVE(strdup) { aikido::string *s = paras[0].str; char *p = strdup (s->c_str()); aikido::string *result = new aikido::string(p); free (p); return result; }   }
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#68000_Assembly
68000 Assembly
JSR myFunction
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#CLU
CLU
cantor = cluster is make rep = null ac = array[char] aac = array[array[char]]   make = proc (width, height: int, ch: char) returns (string) lines: aac := aac$fill_copy(0, height, ac$fill(0, width, ch)) cantor_step(lines, 0, width, 1) s: stream := stream$create_output() for line: ac in aac$elements(lines) do stream$putl(s, string$ac2s(line)) end return(stream$get_contents(s)) end make   cantor_step = proc (lines: aac, start, len, index: int) seg: int := len / 3 if seg = 0 then return end for i: int in int$from_to(index, aac$high(lines)) do for j: int in int$from_to(start+seg, start+seg*2-1) do lines[i][j] := ' ' end end cantor_step(lines, start, seg, index+1) cantor_step(lines, start+seg*2, seg, index+1) end cantor_step end cantor   start_up = proc () po: stream := stream$primary_output() cs: string := cantor$make(81, 5, '*') stream$puts(po, cs) end start_up
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. CANTOR.   DATA DIVISION. WORKING-STORAGE SECTION. 01 SETTINGS. 03 NUM-LINES PIC 9 VALUE 5. 03 FILL-CHAR PIC X VALUE '#'. 01 VARIABLES. 03 CUR-LINE. 05 CHAR PIC X OCCURS 81 TIMES. 03 WIDTH PIC 99. 03 CUR-SIZE PIC 99. 03 POS PIC 99. 03 MAXPOS PIC 99. 03 NEXTPOS PIC 99. 03 I PIC 99.   PROCEDURE DIVISION. BEGIN. COMPUTE WIDTH = 3 ** (NUM-LINES - 1). PERFORM INIT. MOVE WIDTH TO CUR-SIZE. DISPLAY CUR-LINE. PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. STOP RUN.   INIT. PERFORM INIT-CHAR VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN WIDTH.   INIT-CHAR. MOVE FILL-CHAR TO CHAR(I).   DO-LINE. DIVIDE 3 INTO CUR-SIZE. MOVE 1 TO POS. SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. DISPLAY CUR-LINE.   BLANK-REGIONS. ADD CUR-SIZE TO POS. PERFORM BLANK-CHAR CUR-SIZE TIMES.   BLANK-CHAR. MOVE SPACE TO CHAR(POS). ADD 1 TO POS.
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#FreeBASIC
FreeBASIC
#include "gcd.bas"   type rational num as integer den as integer end type   dim shared as rational ONE, TWO ONE.num = 1 : ONE.den = 1 TWO.num = 2 : TWO.den = 1   function simplify( byval a as rational ) as rational dim as uinteger g = gcd( a.num, a.den ) a.num /= g : a.den /= g if a.den < 0 then a.den = -a.den a.num = -a.num end if return a end function   operator + ( a as rational, b as rational ) as rational dim as rational ret ret.num = a.num * b.den + b.num*a.den ret.den = a.den * b.den return simplify(ret) end operator   operator - ( a as rational, b as rational ) as rational dim as rational ret ret.num = a.num * b.den - b.num*a.den ret.den = a.den * b.den return simplify(ret) end operator   operator * ( a as rational, b as rational ) as rational dim as rational ret ret.num = a.num * b.num ret.den = a.den * b.den return simplify(ret) end operator   operator / ( a as rational, b as rational ) as rational dim as rational ret ret.num = a.num * b.den ret.den = a.den * b.num return simplify(ret) end operator   function floor( a as rational ) as rational dim as rational ret ret.den = 1 ret.num = a.num \ a.den return ret end function   function cw_nextterm( q as rational ) as rational dim as rational ret = (TWO*floor(q)) ret = ret + ONE : ret = ret - q return ONE / ret end function   function frac_to_int( byval a as rational ) as uinteger redim as uinteger cfrac(-1) dim as integer lt = -1, ones = 1, ret = 0 do lt += 1 redim preserve as uinteger cfrac(0 to lt) cfrac(lt) = floor(a).num a = a - floor(a) : a = ONE / a loop until a.num = 0 or a.den = 0 if lt mod 2 = 1 and cfrac(lt) = 1 then lt -= 1 cfrac(lt)+=1 redim preserve as uinteger cfrac(0 to lt) end if if lt mod 2 = 1 and cfrac(lt) > 1 then cfrac(lt) -= 1 lt += 1 redim preserve as uinteger cfrac(0 to lt) cfrac(lt) = 1 end if for i as integer = lt to 0 step -1 for j as integer = 1 to cfrac(i) ret *= 2 if ones = 1 then ret += 1 next j ones = 1 - ones next i return ret end function   function disp_rational( a as rational ) as string if a.den = 1 or a.num= 0 then return str(a.num) return str(a.num)+"/"+str(a.den) end function   dim as rational q q.num = 1 q.den = 1 for i as integer = 1 to 20 print i, disp_rational(q) q = cw_nextterm(q) next i   q.num = 83116 q.den = 51639 print disp_rational(q)+" is the "+str(frac_to_int(q))+"th term."
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Tcl
Tcl
package require crimp package require crimp::pgm   proc readPGM {filename} { set f [open $filename rb] set data [read $f] close $f return [crimp read pgm $data] } proc writePGM {filename image} { crimp write 2file pgm-raw $filename $image }   proc cannyFilterFile {{inputFile "lena.pgm"} {outputFile "lena_canny.pgm"}} { writePGM $outputFile [crimp filter canny sobel [readPGM $inputFile]] } cannyFilterFile {*}$argv
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Wren
Wren
import "dome" for Window import "graphics" for Canvas, Color, ImageData import "math" for Math import "./check" for Check   var MaxBrightness = 255   class Canny { construct new(inFile, outFile) { Window.title = "Canny edge detection" var image1 = ImageData.loadFromFile(inFile) var w = image1.width var h = image1.height Window.resize(w * 2 + 20, h) Canvas.resize(w * 2 + 20, h) var image2 = ImageData.create(outFile, w, h) var pixels = List.filled(w * h, 0) var ix = 0 // convert image1 to gray scale as a list of pixels for (y in 0...h) { for (x in 0...w) { var c1 = image1.pget(x, y) var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor pixels[ix] = lumin ix = ix + 1 } }   // find edges var data = cannyEdgeDetection(pixels, w, h, 45, 50, 1)   // write to image2 ix = 0 for (y in 0...h) { for (x in 0...w) { var d = data[ix] var c = Color.rgb(d, d, d) image2.pset(x, y, c) ix = ix + 1 } }   // display the two images side by side image1.draw(0, 0) image2.draw(w + 20, 0)   // save image2 to outFile image2.saveToFile(outFile) }   init() {}   // If normalize is true, map pixels to range 0..MaxBrightness convolution(input, output, kernel, nx, ny, kn, normalize) { Check.ok((kn % 2) == 1) Check.ok(nx > kn && ny > kn) var khalf = (kn / 2).floor var min = Num.largest var max = -min if (normalize) { for (m in khalf...nx-khalf) { for (n in khalf...ny-khalf) { var pixel = 0 var c = 0 for (j in -khalf..khalf) { for (i in -khalf..khalf) { pixel = pixel + input[(n-j)*nx + m - i] * kernel[c] c = c + 1 } } if (pixel < min) min = pixel if (pixel > max) max = pixel } } }   for (m in khalf...nx-khalf) { for (n in khalf...ny-khalf) { var pixel = 0 var c = 0 for (j in -khalf..khalf) { for (i in -khalf..khalf) { pixel = pixel + input[(n-j)*nx + m - i] * kernel[c] c = c + 1 } } if (normalize) pixel = MaxBrightness * (pixel - min) / (max - min) output[n * nx + m] = pixel.truncate } } }   gaussianFilter(input, output, nx, ny, sigma) { var n = 2 * (2 * sigma).truncate + 3 var mean = (n / 2).floor var kernel = List.filled(n * n, 0) System.print("Gaussian filter: kernel size = %(n), sigma = %(sigma)") var c = 0 for (i in 0...n) { for (j in 0...n) { var t = (-0.5 * (((i - mean) / sigma).pow(2) + ((j - mean) / sigma).pow(2))).exp kernel[c] = t / (2 * Num.pi * sigma * sigma) c = c + 1 } } convolution(input, output, kernel, nx, ny, n, true) }   // Returns the square root of 'x' squared + 'y' squared. hypot(x, y) { (x*x + y*y).sqrt }   cannyEdgeDetection(input, nx, ny, tmin, tmax, sigma) { var output = List.filled(input.count, 0) gaussianFilter(input, output, nx, ny, sigma) var Gx = [-1, 0, 1, -2, 0, 2, -1, 0, 1] var afterGx = List.filled(input.count, 0) convolution(output, afterGx, Gx, nx, ny, 3, false) var Gy = [1, 2, 1, 0, 0, 0, -1, -2, -1] var afterGy = List.filled(input.count, 0) convolution(output, afterGy, Gy, nx, ny, 3, false) var G = List.filled(input.count, 0) for (i in 1..nx-2) { for (j in 1..ny-2) { var c = i + nx * j G[c] = hypot(afterGx[c], afterGy[c]).floor } }   // non-maximum suppression: straightforward implementation var nms = List.filled(input.count, 0) for (i in 1..nx-2) { for (j in 1..ny-2) { var c = i + nx * j var nn = c - nx var ss = c + nx var ww = c + 1 var ee = c - 1 var nw = nn + 1 var ne = nn - 1 var sw = ss + 1 var se = ss - 1 var temp = Math.atan(afterGy[c], afterGx[c]) + Num.pi var dir = (temp % Num.pi) / Num.pi * 8 if (((dir <= 1 || dir > 7) && G[c] > G[ee] && G[c] > G[ww]) || // O° ((dir > 1 && dir <= 3) && G[c] > G[nw] && G[c] > G[se]) || // 45° ((dir > 3 && dir <= 5) && G[c] > G[nn] && G[c] > G[ss]) || // 90° ((dir > 5 && dir <= 7) && G[c] > G[ne] && G[c] > G[sw])) { // 135° nms[c] = G[c] } else { nms[c] = 0 } } }   // tracing edges with hysteresis: non-recursive implementation var edges = List.filled((input.count/2).floor, 0) for (i in 0...output.count) output[i] = 0 var c = 1 for (j in 1..ny-2) { for (i in 1..nx-2) { if (nms[c] >= tmax && output[c] == 0) { // trace edges output[c] = MaxBrightness var nedges = 1 edges[0] = c while (true) { nedges = nedges - 1 var t = edges[nedges] var nbs = [ // neighbors t - nx, // nn t + nx, // ss t + 1, // ww t - 1, // ee t - nx + 1, // nw t - nx - 1, // ne t + nx + 1, // sw t + nx - 1 // se ] for (n in nbs) { if (nms[n] >= tmin && output[n] == 0) { output[n] = MaxBrightness edges[nedges] = n nedges = nedges + 1 } } if (nedges == 0) break } } c = c + 1 } } return output }   update() {}   draw(alpha) {} } var Game = Canny.new("Valve_original.png", "Valve_monchrome_canny.png")
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Python
Python
#!/usr/bin/env python # canonicalize a CIDR block specification: # make sure none of the host bits are set   import sys from socket import inet_aton, inet_ntoa from struct import pack, unpack   args = sys.argv[1:] if len(args) == 0: args = sys.stdin.readlines()   for cidr in args: # IP in dotted-decimal / bits in network part dotted, size_str = cidr.split('/') size = int(size_str)   numeric = unpack('!I', inet_aton(dotted))[0] # IP as an integer binary = f'{numeric:#034b}' # then as a padded binary string prefix = binary[:size + 2] # just the network part # (34 and +2 are to account # for leading '0b')   canon_binary = prefix + '0' * (32 - size) # replace host part with all zeroes canon_numeric = int(canon_binary, 2) # convert back to integer canon_dotted = inet_ntoa(pack('!I', (canon_numeric))) # and then to dotted-decimal print(f'{canon_dotted}/{size}') # output result
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Raku
Raku
#!/usr/bin/env raku   # canonicalize a CIDR block: make sure none of the host bits are set if (!@*ARGS) { @*ARGS = $*IN.lines; }   for @*ARGS -> $cidr {   # dotted-decimal / bits in network part my ($dotted, $size) = $cidr.split('/');   # get IP as binary string my $binary = $dotted.split('.').map(*.fmt("%08b")).join;   # Replace the host part with all zeroes $binary.substr-rw($size) = 0 x (32 - $size);   # Convert back to dotted-decimal my $canon = $binary.comb(8).map(*.join.parse-base(2)).join('.');   # And output say "$canon/$size"; }
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Lua
Lua
local N = 2 local base = 10 local c1 = 0 local c2 = 0   for k = 1, math.pow(base, N) - 1 do c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 io.write(k .. ' ') end end   print() print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.0 * c2 / c1))
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#J
J
  q =: (,"0 1~ >:@i.@<:@+/"1)&.>@(,&.>"0 1~ >:@i.)&.>@I.@(1&p:@i.)@>: f1 =: (0: = {. | <:@{: * 1&{ + {:) *. ((1&{ | -@*:@{:) = 1&{ | {.) f2 =: 1: = <:@{. | ({: * 1&{) p2 =: 0:`((* 1&p:)@(<.@(1: + <:@{: * {. %~ 1&{ + {:)))@.f1 p3 =: 3:$0:`((* 1&p:)@({: , {. , (<.@>:@(1&{ %~ {. * {:))))@.(*@{.)@(p2 , }.) (-. 3:$0:)@(((*"0 f2)@p3"1)@;@;@q) 61  
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type IntFunc As Function(As Integer, As Integer) As Integer   Function reduce(a() As Integer, f As IntFunc) As Integer '' if array is empty or function pointer is null, return 0 say If UBound(a) = -1 OrElse f = 0 Then Return 0 Dim result As Integer = a(LBound(a)) For i As Integer = LBound(a) + 1 To UBound(a) result = f(result, a(i)) Next Return result End Function   Function add(x As Integer, y As Integer) As Integer Return x + y End Function   Function subtract(x As Integer, y As Integer) As Integer Return x - y End Function   Function multiply(x As Integer, y As Integer) As Integer Return x * y End Function   Function max(x As Integer, y As Integer) As Integer Return IIf(x > y, x, y) End Function   Function min(x As Integer, y As Integer) As Integer Return IIf(x < y, x, y) End Function   Dim a(4) As Integer = {1, 2, 3, 4, 5} Print "Sum is  :"; reduce(a(), @add) Print "Difference is :"; reduce(a(), @subtract) Print "Product is  :"; reduce(a(), @multiply) Print "Maximum is  :"; reduce(a(), @max) Print "Minimum is  :"; reduce(a(), @min) Print "No op is  :"; reduce(a(), 0) Print Print "Press any key to quit" Sleep  
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#PureBasic
PureBasic
#MAXNUM = 15 Declare catalan()   If OpenConsole("Catalan numbers") catalan() Input() End 0 Else End -1 EndIf   Procedure catalan() Define k.i, n.i, num.d, den.d, cat.d   Print("1 ")   For n=2 To #MAXNUM num=1 : den =1 For k=2 To n num * (n+k) den * k cat = num / den Next Print(Str(cat)+" ") Next EndProcedure
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Python
Python
>>> n = 15 >>> t = [0] * (n + 2) >>> t[1] = 1 >>> for i in range(1, n + 1): for j in range(i, 1, -1): t[j] += t[j - 1] t[i + 1] = t[i] for j in range(i + 1, 1, -1): t[j] += t[j - 1] print(t[i+1] - t[i], end=' ')     1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 >>>
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#NESL
NESL
dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie"; "There is just one dog, named " ++ dog;
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie";   if dog == Dog & Dog == DOG & dog == DOG then do say 'There is just one dog named' dog'.' end else do say 'The three dogs are named' dog',' Dog 'and' DOG'.' end   return  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Nim
Nim
var dog, Dog: string (dog, Dog, DOG) = ("Benjamin", "Samba", "Bernie")   if dog == Dog: if dog == DOG: echo "There is only one dog, ", DOG) else: echo "There are two dogs: ", dog, " and ", DOG elif Dog == DOG : echo "There are two dogs: ", dog, " and ", DOG else: echo "There are three dogs: ", dog, ", ", Dog, " and ", DOG
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Java
Java
  import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList;   import java.util.List;   public class CartesianProduct {   public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; }   return emptyList(); }   private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }  
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#C.23
C#
namespace CatalanNumbers { /// <summary> /// Class that holds all options. /// </summary> public class CatalanNumberGenerator { private static double Factorial(double n) { if (n == 0) return 1;   return n * Factorial(n - 1); }   public double FirstOption(double n) { const double topMultiplier = 2; return Factorial(topMultiplier * n) / (Factorial(n + 1) * Factorial(n)); }   public double SecondOption(double n) { if (n == 0) { return 1; } double sum = 0; double i = 0; for (; i <= (n - 1); i++) { sum += SecondOption(i) * SecondOption((n - 1) - i); } return sum; }   public double ThirdOption(double n) { if (n == 0) { return 1; } return ((2 * (2 * n - 1)) / (n + 1)) * ThirdOption(n - 1); } } }     // Program.cs using System; using System.Configuration;   // Main program // Be sure to add the following to the App.config file and add a reference to System.Configuration: // <?xml version="1.0" encoding="utf-8" ?> // <configuration> // <appSettings> // <clear/> // <add key="MaxCatalanNumber" value="50"/> // </appSettings> // </configuration> namespace CatalanNumbers { class Program { static void Main(string[] args) { CatalanNumberGenerator generator = new CatalanNumberGenerator(); int i = 0; DateTime initial; DateTime final; TimeSpan ts;   try { initial = DateTime.Now; for (; i <= Convert.ToInt32(ConfigurationManager.AppSettings["MaxCatalanNumber"]); i++) { Console.WriteLine("CatalanNumber({0}):{1}", i, generator.FirstOption(i)); } final = DateTime.Now; ts = final - initial; Console.WriteLine("It took {0}.{1} to execute\n", ts.Seconds, ts.Milliseconds);   i = 0; initial = DateTime.Now; for (; i <= Convert.ToInt32(ConfigurationManager.AppSettings["MaxCatalanNumber"]); i++) { Console.WriteLine("CatalanNumber({0}):{1}", i, generator.SecondOption(i)); } final = DateTime.Now; ts = final - initial; Console.WriteLine("It took {0}.{1} to execute\n", ts.Seconds, ts.Milliseconds);   i = 0; initial = DateTime.Now; for (; i <= Convert.ToInt32(ConfigurationManager.AppSettings["MaxCatalanNumber"]); i++) { Console.WriteLine("CatalanNumber({0}):{1}", i, generator.ThirdOption(i)); } final = DateTime.Now; ts = final - initial; Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds, ts.TotalMilliseconds); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("Stopped at index {0}:", i); Console.WriteLine(ex.Message); Console.ReadLine(); } } } }
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Go
Go
type Foo int // some custom type   // method on the type itself; can be called on that type or its pointer func (self Foo) ValueMethod(x int) { }   // method on the pointer to the type; can be called on pointers func (self *Foo) PointerMethod(x int) { }     var myValue Foo var myPointer *Foo = new(Foo)   // Calling value method on value myValue.ValueMethod(someParameter) // Calling pointer method on pointer myPointer.PointerMethod(someParameter)   // Value methods can always be called on pointers // equivalent to (*myPointer).ValueMethod(someParameter) myPointer.ValueMethod(someParameter)   // In a special case, pointer methods can be called on values that are addressable (i.e. lvalues) // equivalent to (&myValue).PointerMethod(someParameter) myValue.PointerMethod(someParameter)   // You can get the method out of the type as a function, and then explicitly call it on the object Foo.ValueMethod(myValue, someParameter) (*Foo).PointerMethod(myPointer, someParameter) (*Foo).ValueMethod(myPointer, someParameter)
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Icon_and_Unicon
Icon and Unicon
procedure main()   bar := foo() # create instance bar.m2() # call method m2 with self=bar, an implicit first parameter   foo_m1( , "param1", "param2") # equivalent of static class method, first (self) parameter is null end   class foo(cp1,cp2) method m1(m1p1,m1p2) local ml1 static ms1 ml1 := m1p1 # do something return end method m2(m2p1) # do something else return end initially L := [cp1] end
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Fortran
Fortran
  double add_n(double* a, double* b) { return *a + *b; }  
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Attempt to call Beep function in Win32 API Dim As Any Ptr library = DyLibLoad("kernel32.dll") '' load dll   If library = 0 Then Print "Unable to load kernel32.dll - calling built in Beep function instead" Beep : Beep : Beep Else Dim beep_ As Function (ByVal As ULong, ByVal As ULong) As Long '' declare function pointer beep_ = DyLibSymbol(library, "Beep") If beep_ = 0 Then Print "Unable to retrieve Beep function from kernel32.dll - calling built in Beep function instead" Beep : Beep : Beep Else For i As Integer = 1 To 3 : beep_(1000, 250) : Next End If DyLibFree(library) '' unload library End If   Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#ALGOL_68
ALGOL 68
  BEGIN MODE PASSWD = STRUCT (STRING name, passwd, INT uid, gid, STRING gecos, dir, shell); PROC getpwnam = (STRING name) PASSWD : BEGIN FILE c source; create (c source, stand out channel); putf (c source, ($gl$, "#include <sys/types.h>", "#include <pwd.h>", "#include <stdio.h>", "main ()", "{", " char name[256];", " scanf (""%s"", name);", " struct passwd *pass = getpwnam (name);", " if (pass == (struct passwd *) NULL) {", " putchar ('\n');", " } else {", " printf (""%s\n"", pass->pw_name);", " printf (""%s\n"", pass->pw_passwd);", " printf (""%d\n"", pass->pw_uid);", " printf (""%d\n"", pass->pw_gid);", " printf (""%s\n"", pass->pw_gecos);", " printf (""%s\n"", pass->pw_dir);", " printf (""%s\n"", pass->pw_shell);", " }", "}" )); STRING source name = idf (c source); STRING bin name = source name + ".bin"; INT child pid = execve child ("/usr/bin/gcc", ("gcc", "-x", "c", source name, "-o", bin name), ""); wait pid (child pid); PIPE p = execve child pipe (bin name, "Ding dong, a68g calling", ""); put (write OF p, (name, newline)); STRING line; PASSWD result; IF get (read OF p, (line, newline)); line = "" THEN result := ("", "", -1, -1, "", "", "") CO Return to sender, address unknown. No such number, no such zone. CO ELSE name OF result := line; get (read OF p, (passwd OF result, newline)); get (read OF p, (uid OF result, newline)); get (read OF p, (gid OF result, newline)); get (read OF p, (gecos OF result, newline)); get (read OF p, (dir OF result, newline)); get (read OF p, (shell OF result, newline)) FI; close (write OF p); CO Sundry cleaning up. CO close (read OF p); execve child ("/bin/rm", ("rm", "-f", source name, bin name), ""); result END; PASSWD mr root = getpwnam ("root"); IF name OF mr root = "" THEN print (("Oh dear, we seem to be rootless.", newline)) ELSE printf (($2(g,":"), 2(g(0),":"), 2(g,":"), gl$, mr root)) FI END  
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#8086_Assembly
8086 Assembly
call foo
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#D
D
import std.stdio;   enum WIDTH = 81; enum HEIGHT = 5;   char[WIDTH*HEIGHT] lines;   void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i=index; i<HEIGHT; i++) { for (int j=start+seg; j<start+seg*2; j++) { int pos = i*WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index+1); cantor(start+seg*2, seg, index+1); }   void main() { // init lines[] = '*';   // calculate cantor(0, WIDTH, 1);   // print for (int i=0; i<HEIGHT; i++) { int beg = WIDTH * i; writeln(lines[beg..beg+WIDTH]); } }
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math" "math/big" "strconv" "strings" )   func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw }   func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { // ensure always odd res[le-1]-- res = append(res, 1) } return res }   func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) }   func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s }   func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Canny_edge_detector // Adapted from Phix to Yabasic by Galileo, 01/2022   import ReadFromPPM2   MaxBrightness = 255   readPPM("Valve.ppm") print "Be patient, please ..."   width = peek("winwidth") height = peek("winheight") dim pixels(width, height), C_E_D(3, 3)   data -1, -1, -1, -1, 8, -1, -1, -1, -1 for i = 0 to 2 for j = 0 to 2 read C_E_D(i, j) next next   // convert image to gray scale for y = 1 to height for x = 1 to width c$ = right$(getbit$(x, y, x, y), 6) r = dec(left$(c$, 2)) g = dec(mid$(c$, 3, 2)) b = dec(right$(c$, 2)) lumin = floor(0.2126 * r + 0.7152 * g + 0.0722 * b) pixels(x, y) = lumin next next   dim new_image(width, height)   divisor = 1   // apply an edge detection filter   for y = 2 to height-2 for x = 2 to width-2 newrgb = 0 for i = -1 to 1 for j = -1 to 1 newrgb = newrgb + C_E_D(i+1, j+1) * pixels(x+i, y+j) next new_image(x, y) = max(min(newrgb / divisor,255),0) next next next   // show result   for x = 1 to width for y = 1 to height c = new_image(x, y) color c, c, c dot x, y next next
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#REXX
REXX
/*REXX pgm canonicalizes IPv4 addresses that are in CIDR notation (dotted─dec/network).*/ parse arg a . /*obtain optional argument from the CL.*/ if a=='' | a=="," then a= '87.70.141.1/22' , /*Not specified? Then use the defaults*/ '36.18.154.103/12' , '62.62.197.11/29' , '67.137.119.181/4' , '161.214.74.21/24' , '184.232.176.184/18'   do i=1 for words(a); z= word(a, i) /*process each IPv4 address in the list*/ parse var z # '/' -0 mask /*get the address nodes & network mask.*/ #= subword( translate(#, , .) 0 0 0, 1, 4) /*elide dots from addr, ensure 4 nodes.*/ $= # /*use original node address (for now). */ hb= 32 - substr(word(mask .32, 1), 2) /*obtain the size of the host bits. */ $=; ##= /*crop the host bits only if mask ≤ 32.*/ do k=1 for 4; _= word(#, k) /*create a 32-bit (binary) IPv4 address*/ ##= ## || right(d2b(_), 8, 0) /*append eight bits of the " " */ end /*k*/ /* [↑] ... and ensure a node is 8 bits.*/ ##= left(##, 32-hb, 0) /*crop bits in host part of IPv4 addr. */ ##= left(##, 32, 0) /*replace cropped bits with binary '0's*/ do j=8 by 8 for 4 /* [↓] parse the four nodes of address*/ $= $ || . || b2d(substr(##, j-7, 8)) /*reconstitute the decimal nodes. */ end /*j*/ /* [↑] and insert a dot between nodes.*/ say /*introduce a blank line between IPv4's*/ $= substr($, 2) /*elid the leading decimal point in $ */ say ' original IPv4 address: ' z /*display the original IPv4 address. */ say ' canonicalized address: ' translate( space($), ., " ")mask /*canonicalized.*/ end /*i*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ b2d: return x2d( b2x( arg(1) ) ) + 0 /*convert binary ───► decimal number.*/ d2b: return x2b( d2x( arg(1) ) ) + 0 /* " decimal ───► binary " */
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Co9[n_, b_: 10] := With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]}, If[ans == b - 1, 0, ans]];
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Nim
Nim
import sequtils   iterator castOut(base = 10, start = 1, ending = 999_999): int = var ran: seq[int] = @[] for y in 0 ..< base-1: if y mod (base - 1) == (y*y) mod (base - 1): ran.add(y)   var x = start div (base - 1) var y = start mod (base - 1)   block outer: while true: for n in ran: let k = (base - 1) * x + n if k < start: continue if k > ending: break outer yield k inc x   echo toSeq(castOut(base=16, start=1, ending=255))
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Java
Java
public class Test {   static int mod(int n, int m) { return ((n % m) + m) % m; }   static boolean isPrime(int n) { if (n == 2 || n == 3) return true; else if (n < 2 || n % 2 == 0 || n % 3 == 0) return false; for (int div = 5, inc = 2; Math.pow(div, 2) <= n; div += inc, inc = 6 - inc) if (n % div == 0) return false; return true; }   public static void main(String[] args) { for (int p = 2; p < 62; p++) { if (!isPrime(p)) continue; for (int h3 = 2; h3 < p; h3++) { int g = h3 + p; for (int d = 1; d < g; d++) { if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3) continue; int q = 1 + (p - 1) * g / d; if (!isPrime(q)) continue; int r = 1 + (p * q / h3); if (!isPrime(r) || (q * r) % (p - 1) != 1) continue; System.out.printf("%d x %d x %d%n", p, q, r); } } } } }
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Go
Go
package main   import ( "fmt" )   func main() { n := []int{1, 2, 3, 4, 5}   fmt.Println(reduce(add, n)) fmt.Println(reduce(sub, n)) fmt.Println(reduce(mul, n)) }   func add(a int, b int) int { return a + b } func sub(a int, b int) int { return a - b } func mul(a int, b int) int { return a * b }   func reduce(rf func(int, int) int, m []int) int { r := m[0] for _, v := range m[1:] { r = rf(r, v) } return r }
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Quackery
Quackery
[ [] 0 rot 0 join witheach [ tuck + rot join swap ] drop ] is nextline ( [ --> [ )   [ ' [ 1 ] swap times [ nextline nextline dup dup size 2 / split nip 2 split drop do - echo sp ] drop ] is catalan ( n --> )   15 catalan
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Oberon-2
Oberon-2
  MODULE CaseSensitivity; IMPORT Out; VAR dog, Dog, DOG: STRING; BEGIN dog := "Benjamin"; Dog := "Samba"; DOG := "Bernie"; Out.Object("The three dogs are named " + dog + ", " + Dog + " and " + DOG); Out.Ln END CaseSensitivity.  
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#JavaScript
JavaScript
(() => { // CARTESIAN PRODUCT OF TWO LISTS ---------------------   // cartProd :: [a] -> [b] -> [[a, b]] const cartProd = xs => ys => xs.flatMap(x => ys.map(y => [x, y]))     // TEST ----------------------------------------------- return [ cartProd([1, 2])([3, 4]), cartProd([3, 4])([1, 2]), cartProd([1, 2])([]), cartProd([])([1, 2]), ].map(JSON.stringify).join('\n'); })();
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#C.2B.2B
C++
#if !defined __ALGORITHMS_H__ #define __ALGORITHMS_H__   namespace rosetta { namespace catalanNumbers { namespace detail {   class Factorial { public: unsigned long long operator()(unsigned n)const; };   class BinomialCoefficient { public: unsigned long long operator()(unsigned n, unsigned k)const; };   } //namespace detail   class CatalanNumbersDirectFactorial { public: CatalanNumbersDirectFactorial(); unsigned long long operator()(unsigned n)const; private: detail::Factorial factorial; };   class CatalanNumbersDirectBinomialCoefficient { public: CatalanNumbersDirectBinomialCoefficient(); unsigned long long operator()(unsigned n)const; private: detail::BinomialCoefficient binomialCoefficient; };   class CatalanNumbersRecursiveSum { public: CatalanNumbersRecursiveSum(); unsigned long long operator()(unsigned n)const; };   class CatalanNumbersRecursiveFraction { public: CatalanNumbersRecursiveFraction(); unsigned long long operator()(unsigned n)const; };   } //namespace catalanNumbers } //namespace rosetta   #endif //!defined __ALGORITHMS_H__
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Haskell
Haskell
data Obj = Obj { field :: Int, method :: Int -> Int }   -- smart constructor mkAdder :: Int -> Obj mkAdder x = Obj x (+x)   -- adding method from a type class instanse Show Obj where show o = "Obj " ++ show (field o)
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#J
J
methodName_className_ parameters
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Java
Java
ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Go
Go
#include <stdio.h> /* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */ int openimage(const char *s) { static int handle = 100; fprintf(stderr, "opening %s\n", s); return handle++; }
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Haskell
Haskell
#!/usr/bin/env stack -- stack --resolver lts-6.33 --install-ghc runghc --package unix   import Control.Exception ( try ) import Foreign ( FunPtr, allocaBytes ) import Foreign.C ( CSize(..), CString, withCAStringLen, peekCAStringLen ) import System.Info ( os ) import System.IO.Error ( ioeGetErrorString ) import System.IO.Unsafe ( unsafePerformIO ) import System.Posix.DynamicLinker ( RTLDFlags(RTLD_LAZY), dlsym, dlopen )   dlSuffix :: String dlSuffix = if os == "darwin" then ".dylib" else ".so"   type RevFun = CString -> CString -> CSize -> IO ()   foreign import ccall "dynamic" mkFun :: FunPtr RevFun -> RevFun   callRevFun :: RevFun -> String -> String callRevFun f s = unsafePerformIO $ withCAStringLen s $ \(cs, len) -> do allocaBytes len $ \buf -> do f buf cs (fromIntegral len) peekCAStringLen (buf, len)   getReverse :: IO (String -> String) getReverse = do lib <- dlopen ("libcrypto" ++ dlSuffix) [RTLD_LAZY] fun <- dlsym lib "BUF_reverse" return $ callRevFun $ mkFun fun   main = do x <- try getReverse let (msg, rev) = case x of Left e -> (ioeGetErrorString e ++ "; using fallback", reverse) Right f -> ("Using BUF_reverse from OpenSSL", f) putStrLn msg putStrLn $ rev "a man a plan a canal panama"
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#11l
11l
V e0 = 0.0 V e = 2.0 V n = 0 V fact = 1 L (e - e0 > 1e-15) e0 = e n++ fact *= 2 * n * (2 * n + 1) e += (2.0 * n + 2) / fact   print(‘Computed e = ’e) print(‘Real e = ’math:e) print(‘Error = ’(math:e - e)) print(‘Number of iterations = ’n)
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program forfunction.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szString: .asciz "Hello word\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: @ entry of program push {fp,lr} @ saves registers   ldr r0,iAdrszString @ string address bl strdup @ call function C @ return new pointer bl affichageMess @ display dup string bl free @ free heap   100: @ standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrszString: .int szString   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return  
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program callfonct.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /***********************/ /* Initialized data */ /***********************/ .data szMessage: .asciz "Hello. \n" // message szRetourLigne: .asciz "\n" szMessResult: .asciz "Resultat : " // message result   /***********************/ /* No Initialized data */ /***********************/ .bss sZoneConv: .skip 100   .text .global main main: ldr x0,=szMessage // adresse of message short program bl affichageMess // call function with 1 parameter (x0)   // call function with parameters in register mov x0,#5 mov x1,#10 bl fonction1 // call function with 2 parameters (x0,x1) ldr x1,qAdrsZoneConv // result in x0 bl conversion10S // call function with 2 parameter (x0,x1) ldr x0,=szMessResult bl affichageMess // call function with 1 parameter (x0) ldr x0,qAdrsZoneConv bl affichageMess ldr x0,qAdrszRetourLigne bl affichageMess // call function with parameters on stack mov x0,#5 mov x1,#10 stp x0,x1,[sp,-16]! // store registers on stack bl fonction2 // call function with 2 parameters on the stack // result in x0 ldr x1,qAdrsZoneConv bl conversion10S // call function with 2 parameter (x0,x1) ldr x0,=szMessResult bl affichageMess // call function with 1 parameter (x0) ldr x0,qAdrsZoneConv bl affichageMess ldr x0,qAdrszRetourLigne bl affichageMess // end of program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform the system call qAdrsZoneConv: .quad sZoneConv qAdrszRetourLigne: .quad szRetourLigne /******************************************************************/ /* call function parameter in register */ /******************************************************************/ /* x0 value one */ /* x1 value two */ /* return in x0 */ fonction1: stp x2,lr,[sp,-16]! // save registers mov x2,#20 mul x0,x0,x2 add x0,x0,x1 ldp x2,lr,[sp],16 // restaur 2 registres ret // retour adresse lr x30   /******************************************************************/ /* call function parameter in the stack */ /******************************************************************/ /* return in x0 */ fonction2: stp fp,lr,[sp,-16]! // save registers add fp,sp,#16 // address parameters in the stack stp x1,x2,[sp,-16]! // save others registers ldr x0,[fp] // second paraméter ldr x1,[fp,#8] // first parameter mov x2,#-20 mul x0,x0,x2 add x0,x0,x1 ldp x1,x2,[sp],16 // restaur 2 registres ldp fp,lr,[sp],16 // restaur 2 registres add sp,sp,#16 // very important, for stack aligned ret // retour adresse lr x30     /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Delphi
Delphi
  program Cantor_set;   {$APPTYPE CONSOLE}   const WIDTH: Integer = 81; HEIGHT: Integer = 5;   var Lines: TArray<TArray<Char>>;   procedure Init; var i, j: Integer; begin SetLength(lines, HEIGHT, WIDTH); for i := 0 to HEIGHT - 1 do for j := 0 to WIDTH - 1 do lines[i, j] := '*'; end;   procedure Cantor(start, len, index: Integer); var seg, i, j: Integer; begin seg := len div 3; if seg = 0 then Exit; for i := index to HEIGHT - 1 do for j := start + seg to start + seg * 2 - 1 do lines[i, j] := ' '; Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); end;   var i, j: Integer;   begin Init; Cantor(0, WIDTH, 1); for i := 0 to HEIGHT - 1 do begin for j := 0 to WIDTH - 1 do Write(lines[i, j]); Writeln; end; Readln; end.  
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Go
Go
package main   import ( "fmt" "math" "math/big" "strconv" "strings" )   func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw }   func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { // ensure always odd res[le-1]-- res = append(res, 1) } return res }   func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) }   func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s }   func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Ruby
Ruby
#!/usr/bin/env ruby   # canonicalize a CIDR block: make sure none of the host bits are set if ARGV.length == 0 then ARGV = $stdin.readlines.map(&:chomp) end   ARGV.each do |cidr|   # dotted-decimal / bits in network part dotted, size_str = cidr.split('/') size = size_str.to_i   # get IP as binary string binary = dotted.split('.').map { |o| "%08b" % o }.join   # Replace the host part with all zeroes binary[size .. -1] = '0' * (32 - size)   # Convert back to dotted-decimal canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')   # And output puts "#{canon}/#{size}" end
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Rust
Rust
use std::net::Ipv4Addr;   fn canonical_cidr(cidr: &str) -> Result<String, &str> { let mut split = cidr.splitn(2, '/'); if let (Some(addr), Some(mask)) = (split.next(), split.next()) { let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?; let mask = mask.parse::<u8>().map_err(|_| cidr)?; let bitmask = 0xff_ff_ff_ffu32 << (32 - mask); let addr = Ipv4Addr::from(addr & bitmask); Ok(format!("{}/{}", addr, mask)) } else { Err(cidr) } }   #[cfg(test)] mod tests {   #[test] fn valid() { [ ("87.70.141.1/22", "87.70.140.0/22"), ("36.18.154.103/12", "36.16.0.0/12"), ("62.62.197.11/29", "62.62.197.8/29"), ("67.137.119.181/4", "64.0.0.0/4"), ("161.214.74.21/24", "161.214.74.0/24"), ("184.232.176.184/18", "184.232.128.0/18"), ] .iter() .cloned() .for_each(|(input, expected)| { assert_eq!(expected, super::canonical_cidr(input).unwrap()); }); } }   fn main() { println!("{}", canonical_cidr("127.1.2.3/24").unwrap()); }
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Objeck
Objeck
class CastingNines { function : Main(args : String[]) ~ Nil { base := 10; N := 2; c1 := 0; c2 := 0;   for (k:=1; k<base->As(Float)->Power(N->As(Float)); k+=1;){ c1+=1; if (k%(base-1) = (k*k)%(base-1)){ c2+=1; IO.Console->Print(k)->Print(" "); }; };   IO.Console->Print("\nTrying ")->Print(c2)->Print(" numbers instead of ") ->Print(c1)->Print(" numbers saves ")->Print(100 - (c2->As(Float)/c1 ->As(Float)*100))->PrintLine("%"); } }
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Julia
Julia
using Primes   function carmichael(pmax::Integer) if pmax ≤ 0 throw(DomainError("pmax must be strictly positive")) end car = Vector{typeof(pmax)}(0) for p in primes(pmax) for h₃ in 2:(p-1) m = (p - 1) * (h₃ + p) pmh = mod(-p ^ 2, h₃) for Δ in 1:(h₃+p-1) if m % Δ != 0 || Δ % h₃ != pmh continue end q = m ÷ Δ + 1 if !isprime(q) continue end r = (p * q - 1) ÷ h₃ + 1 if !isprime(r) || mod(q * r, p - 1) == 1 continue end append!(car, [p, q, r]) end end end return reshape(car, 3, length(car) ÷ 3) end
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Kotlin
Kotlin
fun Int.isPrime(): Boolean { return when { this == 2 -> true this <= 1 || this % 2 == 0 -> false else -> { val max = Math.sqrt(toDouble()).toInt() (3..max step 2) .filter { this % it == 0 } .forEach { return false } true } } }   fun mod(n: Int, m: Int) = ((n % m) + m) % m   fun main(args: Array<String>) { for (p1 in 3..61) { if (p1.isPrime()) { for (h3 in 2 until p1) { val g = h3 + p1 for (d in 1 until g) { if ((g * (p1 - 1)) % d == 0 && mod(-p1 * p1, h3) == d % h3) { val q = 1 + (p1 - 1) * g / d if (q.isPrime()) { val r = 1 + (p1 * q / h3) if (r.isPrime() && (q * r) % (p1 - 1) == 1) { println("$p1 x $q x $r") } } } } } } } }
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Groovy
Groovy
def vector1 = [1,2,3,4,5,6,7] def vector2 = [7,6,5,4,3,2,1] def map1 = [a:1, b:2, c:3, d:4]   println vector1.inject { acc, val -> acc + val } // sum println vector1.inject { acc, val -> acc + val*val } // sum of squares println vector1.inject { acc, val -> acc * val } // product println vector1.inject { acc, val -> acc<val?val:acc } // max println ([vector1,vector2].transpose().inject(0) { acc, val -> acc + val[0]*val[1] }) //dot product (with seed 0)   println (map1.inject { Map.Entry accEntry, Map.Entry entry -> // some sort of weird map-based reduction [(accEntry.key + entry.key):accEntry.value + entry.value ].entrySet().toList().pop() })
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Racket
Racket
  #lang racket   (define (next-half-row r) (define r1 (for/list ([x r] [y (cdr r)]) (+ x y))) `(,(* 2 (car r1)) ,@(for/list ([x r1] [y (cdr r1)]) (+ x y)) 1 0))   (let loop ([n 15] [r '(1 0)]) (cons (- (car r) (cadr r)) (if (zero? n) '() (loop (sub1 n) (next-half-row r))))) ;; -> '(1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 ;; 2674440 9694845)  
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Raku
Raku
constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;   constant @catalan = gather for 2, 4 ... * -> $ix { my @row := @pascal[$ix]; my $mid = +@row div 2; take [-] @row[$mid, $mid+1] }   .say for @catalan[^20];
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Objeck
Objeck
class Program { function : Main(args : String[]) ~ Nil { dog := "Benjamin"; Dog := "Samba"; DOG := "Bernie"; "The three dogs are named {$dog}, {$Dog}, and {$DOG}."->PrintLine(); } }
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#OCaml
OCaml
let () = let dog = "Benjamin" in let dOG = "Samba" in let dOg = "Bernie" in Printf.printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#jq
jq
  def products: .[0][] as $x | .[1][] as $y | [$x,$y];  
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Clojure
Clojure
(def ! (memoize #(apply * (range 1 (inc %)))))   (defn catalan-numbers-direct [] (map #(/ (! (* 2 %)) (* (! (inc %)) (! %))) (range)))   (def catalan-numbers-recursive #(->> [1 1] ; [c0 n1] (iterate (fn [[c n]] [(* 2 (dec (* 2 n)) (/ (inc n)) c) (inc n)]) ,) (map first ,)))   user> (take 15 (catalan-numbers-direct)) (1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440)   user> (take 15 (catalan-numbers-recursive)) (1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440)
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#JavaScript
JavaScript
x.y()
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Julia
Julia
module Animal
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#J
J
require 'dll' strdup=: 'msvcrt.dll _strdup >x *' cd < free=: 'msvcrt.dll free n x' cd < getstr=: free ] memr@,&0 _1   DupStr=:verb define try. getstr@strdup y catch. y end. )
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Java
Java
/* TrySort.java */   import java.util.Collections; import java.util.Random;   public class TrySort { static boolean useC; static { try { System.loadLibrary("TrySort"); useC = true; } catch(UnsatisfiedLinkError e) { useC = false; } }   static native void sortInC(int[] ary);   static class IntList extends java.util.AbstractList<Integer> { int[] ary; IntList(int[] ary) { this.ary = ary; } public Integer get(int i) { return ary[i]; } public Integer set(int i, Integer j) { Integer o = ary[i]; ary[i] = j; return o; } public int size() { return ary.length; } }   static class ReverseAbsCmp implements java.util.Comparator<Integer> { public int compare(Integer pa, Integer pb) { /* Order from highest to lowest absolute value. */ int a = pa > 0 ? -pa : pa; int b = pb > 0 ? -pb : pb; return a < b ? -1 : a > b ? 1 : 0; } }   static void sortInJava(int[] ary) { Collections.sort(new IntList(ary), new ReverseAbsCmp()); }   public static void main(String[] args) { /* Create an array of random integers. */ int[] ary = new int[1000000]; Random rng = new Random(); for (int i = 0; i < ary.length; i++) ary[i] = rng.nextInt();   /* Do the reverse sort. */ if (useC) { System.out.print("Sorting in C... "); sortInC(ary); } else { System.out.print ("Missing library for C! Sorting in Java... "); sortInJava(ary); }   for (int i = 0; i < ary.length - 1; i++) { int a = ary[i]; int b = ary[i + 1]; if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) { System.out.println("*BUG IN SORT*"); System.exit(1); } } System.out.println("ok"); } }
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#360_Assembly
360 Assembly
* Calculating the value of e - 21/07/2018 CALCE PROLOG LE F0,=E'0' STE F0,EOLD eold=0 LE F2,=E'1' e=1 LER F4,F2 xi=1 LER F6,F2 facti=1 BWHILE CE F2,EOLD while e<>eold BE EWHILE ~ STE F2,EOLD eold=e LE F0,=E'1' 1 DER F0,F6 1/facti AER F2,F0 e=e+1/facti AE F4,=E'1' xi=xi+1 MER F6,F4 facti=facti*xi LER F0,F4 xi B BWHILE end while EWHILE LER F0,F2 e LA R0,5 number of decimals BAL R14,FORMATF format a float number MVC PG(13),0(R1) output e XPRNT PG,L'PG print e EPILOG COPY FORMATF format a float number EOLD DS E eold PG DC CL80' ' buffer REGEQU END CALCE
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Arturo
Arturo
// compile with: // clang -c -w mylib.c // clang -shared -o libmylib.dylib mylib.o   #include <stdio.h>   void sayHello(char* name){ printf("Hello %s!\n", name); }   int doubleNum(int num){ return num * 2; }
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#AutoHotkey
AutoHotkey
; Example: Calls the Windows API function "MessageBox" and report which button the user presses.   WhichButton := DllCall("MessageBox", "int", "0", "str", "Press Yes or No", "str", "Title of box", "int", 4) MsgBox You pressed button #%WhichButton%.
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#ActionScript
ActionScript
myfunction(); /* function with no arguments in statement context */ myfunction(6,b); // function with two arguments in statement context stringit("apples"); //function with a string argument
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Excel
Excel
CANTOR =LAMBDA(n, APPLYN(n)( LAMBDA(grid, APPENDROWS(grid)( CANTOROW( LASTROW(grid) ) ) ) )({0,1}) )     CANTOROW =LAMBDA(xys, LET( nCols, COLUMNS(xys),   IF(2 > nCols, xys, IF(3 < nCols, APPENDCOLS( CANTORSLICES(TAKECOLS(2)(xys)) )( CANTOROW(DROPCOLS(2)(xys)) ), CANTORSLICES(TAKECOLS(2)(xys)) ) ) ) )     CANTORSLICES =LAMBDA(ab, LET( a, INDEX(ab, 1), b, INDEX(ab, 2), third, (b - a) / 3,   CHOOSE({1,2,3,4}, a, a + third, b - third, b) ) )     SHOWCANTOR =LAMBDA(grid, LET( leaves, LASTROW(grid), leafWidth, INDEX(leaves, 1, 2) - INDEX(leaves, 1, 1), leafCount, 1 / leafWidth,   SHOWCANTROWS(leafCount)(grid) ) )     SHOWCANTROWS =LAMBDA(leafCount, LAMBDA(grid, LET( xs, FILTERP( LAMBDA(x, NOT(ISNA(x))) )( HEADCOL(grid) ),   runLengths, LAMBDA(x, CEILING.MATH(leafCount * x))( SUBTRACT(TAILROW(xs))(INITROW(xs) ) ),   iCols, SEQUENCE(1, COLUMNS(runLengths)),   CONCAT( REPT( IF(ISEVEN(iCols), " ", "█"), runLengths ) ) & IF(1 < ROWS(grid), CHAR(10) & SHOWCANTROWS(leafCount)( TAILCOL(grid) ), "" ) ) ) )
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Haskell
Haskell
import Control.Monad (forM_) import Data.Bool (bool) import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr) import Text.Printf (printf)   -- The infinite Calkin-Wilf sequence, a(n), starting with a(1) = 1. calkinWilfs :: [Rational] calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1   -- The index into the Calkin-Wilf sequence of a given rational number, starting -- with 1 at index 1. calkinWilfIdx :: Rational -> Integer calkinWilfIdx = rld . cfo   -- A continued fraction representation of a given rational number, guaranteed -- to have an odd length. cfo :: Rational -> NonEmpty Int cfo = oddLen . cf   -- The canonical (i.e. shortest) continued fraction representation of a given -- rational number. cf :: Rational -> NonEmpty Int cf = unfoldr step where step r = case properFraction r of (n, 1) -> (succ n, Nothing) (n, 0) -> (n, Nothing) (n, f) -> (n, Just (recip f))   -- Ensure a continued fraction has an odd length. oddLen :: NonEmpty Int -> NonEmpty Int oddLen = fromList . go . toList where go [x, y] = [x, pred y, 1] go (x:y:zs) = x : y : go zs go xs = xs   -- Run-length decode a continued fraction. rld :: NonEmpty Int -> Integer rld = snd . foldr step (True, 0) where step i (b, n) = let p = 2 ^ i in (not b, n * p + bool 0 (pred p) b)   main :: IO () main = do forM_ (take 20 $ zip [1 :: Int ..] calkinWilfs) $ \(i, r) -> printf "%2d  %s\n" i (show r) let r = 83116 / 51639 printf "\n%s is at index %d of the Calkin-Wilf sequence.\n" (show r) (calkinWilfIdx r)
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Wren
Wren
import "/fmt" for Fmt, Conv import "/str" for Str   // canonicalize a CIDR block: make sure none of the host bits are set var canonicalize = Fn.new { |cidr| // dotted-decimal / bits in network part var split = cidr.split("/") var dotted = split[0] var size = Num.fromString(split[1])   // get IP as binary string var binary = dotted.split(".").map { |n| Fmt.swrite("$08b", Num.fromString(n)) }.join()   // replace the host part with all zeros binary = binary[0...size] + "0" * (32 - size)   // convert back to dotted-decimal var chunks = Str.chunks(binary, 8) var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")   // and return return canon + "/" + split[1] }   var tests = [ "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" ]   for (test in tests) { Fmt.print("$-18s -> $s", test, canonicalize.call(test)) }
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#PARI.2FGP
PARI/GP
{base=10; N=2; c1=c2=0; for(k=1,base^N-1, c1++; if (k%(base-1) == k^2%(base-1), c2++; print1(k" ") ); ); print("\nTrying "c2" numbers instead of "c1" numbers saves " 100.-(c2/c1)*100 "%")}  
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Lua
Lua
local function isprime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end local f, limit = 5, math.sqrt(n) while (f <= limit) do if n % f == 0 then return false end; f=f+2 if n % f == 0 then return false end; f=f+4 end return true end   local function carmichael3(p) local list = {} if not isprime(p) then return list end for h = 2, p-1 do for d = 1, h+p-1 do if ((h + p) * (p - 1)) % d == 0 and (-p * p) % h == (d % h) then local q = 1 + math.floor((p - 1) * (h + p) / d) if isprime(q) then local r = 1 + math.floor(p * q / h) if isprime(r) and (q * r) % (p - 1) == 1 then list[#list+1] = { p=p, q=q, r=r } end end end end end return list end   local found = 0 for p = 2, 61 do local list = carmichael3(p) found = found + #list table.sort(list, function(a,b) return (a.p<b.p) or (a.p==b.p and a.q<b.q) or (a.p==b.p and a.q==b.q and a.r<b.r) end) for k,v in ipairs(list) do print(string.format("%.f × %.f × %.f = %.f", v.p, v.q, v.r, v.p*v.q*v.r)) end end print(found.." found.")
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Haskell
Haskell
main :: IO () main = putStrLn . unlines $ [ show . foldr (+) 0 -- sum , show . foldr (*) 1 -- product , foldr ((++) . show) "" -- concatenation ] <*> [[1 .. 10]]
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#REXX
REXX
/*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */ parse arg N . /*Obtain the optional argument from CL.*/ if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/ numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/ @.=0; @.1=1 /*stem array default; define 1st value.*/   do i=1 for N; ip=i+1 do j=i by -1 for N; jm=j-1; @[email protected][email protected]; end /*j*/ @[email protected]; do k=ip by -1 for N; km=k-1; @[email protected][email protected]; end /*k*/ say @.ip - @.i /*display the Ith Catalan number. */ end /*i*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Ring
Ring
  n=15 cat = list(n+2) cat[1]=1 for i=1 to n for j=i+1 to 2 step -1 cat[j]=cat[j]+cat[j-1] next cat[i+1]=cat[i] for j=i+2 to 2 step -1 cat[j]=cat[j]+cat[j-1] next see "" + (cat[i+1]-cat[i]) + " " next  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Oforth
Oforth
: threeDogs | dog Dog DOG |   "Benjamin" ->dog "Samba" ->Dog "Bernie" ->DOG   System.Out "The three dogs are named " << dog << ", " << Dog << " and " << DOG << "." << cr ;
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Ol
Ol
  (define dog "Benjamin") (define Dog "Samba") (define DOG "Bernie")   (print "The three dogs are named " dog ", " Dog " and " DOG ".\n")  
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Julia
Julia
  # Product {1, 2} × {3, 4} collect(Iterators.product([1, 2], [3, 4])) # Product {3, 4} × {1, 2} collect(Iterators.product([3, 4], [1, 2]))   # Product {1, 2} × {} collect(Iterators.product([1, 2], [])) # Product {} × {1, 2} collect(Iterators.product([], [1, 2]))   # Product {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} collect(Iterators.product([1776, 1789], [7, 12], [4, 14, 23], [0, 1])) # Product {1, 2, 3} × {30} × {500, 100} collect(Iterators.product([1, 2, 3], [30], [500, 100])) # Product {1, 2, 3} × {} × {500, 100} collect(Iterators.product([1, 2, 3], [], [500, 100]))  
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Common_Lisp
Common Lisp
(defun catalan1 (n) ;; factorial. CLISP actually has "!" defined for this (labels ((! (x) (if (zerop x) 1 (* x (! (1- x)))))) (/ (! (* 2 n)) (! (1+ n)) (! n))))   ;; cache (defparameter *catalans* (make-array 5 :fill-pointer 0 :adjustable t :element-type 'integer)) (defun catalan2 (n) (if (zerop n) 1 ;; check cache (if (< n (length *catalans*)) (aref *catalans* n) (loop with c = 0 for i from 0 to (1- n) collect (incf c (* (catalan2 i) (catalan2 (- n 1 i)))) ;; lower values always get calculated first, so ;; vector-push-extend is safe finally (progn (vector-push-extend c *catalans*) (return c))))))   (defun catalan3 (n) (if (zerop n) 1 (/ (* 2 (+ n n -1) (catalan3 (1- n))) (1+ n))))   ;;; test all three methods (loop for f in (list #'catalan1 #'catalan2 #'catalan3) for i from 1 to 3 do (format t "~%Method ~d:~%" i) (dotimes (i 16) (format t "C(~2d) = ~d~%" i (funcall f i))))
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Kotlin
Kotlin
class MyClass { fun instanceMethod(s: String) = println(s)   companion object { fun staticMethod(s: String) = println(s) } }   fun main(args: Array<String>) { val mc = MyClass() mc.instanceMethod("Hello instance world!") MyClass.staticMethod("Hello static world!") }
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Latitude
Latitude
myObject someMethod (arg1, arg2, arg3). MyClass someMethod (arg1, arg2, arg3).
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Jsish
Jsish
#!/usr/local/bin/jsish load('byjsi.so');
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Julia
Julia
  #this example works on Windows ccall( (:GetDoubleClickTime, "User32"), stdcall, Uint, (), )   ccall( (:clock, "libc"), Int32, ())
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   PROC Euler(REAL POINTER e) REAL e0,fact,tmp,tmp2,one INT n   IntToReal(1,one) IntToReal(2,e) IntToReal(1,fact) n=2   DO RealAssign(e,e0) IntToReal(n,tmp) RealMult(fact,tmp,tmp2) RealAssign(tmp2,fact) n==+1 RealDiv(one,fact,tmp) RealAdd(e,tmp,tmp2) RealAssign(tmp2,e) UNTIL RealGreaterOrEqual(e0,e) OD RETURN   PROC Main() REAL e,calc,diff   Put(125) PutE() ;clear screen ValR("2.71828183",e) Euler(calc) RealSub(calc,e,diff) Print(" real e=") PrintRE(e) Print("calculated e=") PrintRE(calc) Print(" error=") PrintRE(diff) RETURN
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;   procedure Euler is Epsilon : constant  := 1.0E-15; Fact  : Long_Integer := 1; E  : Long_Float  := 2.0; E0  : Long_Float  := 0.0; N  : Long_Integer := 2;   begin   loop E0  := E; Fact := Fact * N; N  := N + 1; E  := E + (1.0 / Long_Float (Fact)); exit when abs (E - E0) < Epsilon; end loop;   Put ("e = "); Put (E, 0, 15, 0); New_Line;   end Euler;
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#BBC_BASIC
BBC BASIC
SYS "LoadLibrary", "MSVCRT.DLL" TO msvcrt% SYS "GetProcAddress", msvcrt%, "_strdup" TO `strdup` SYS "GetProcAddress", msvcrt%, "free" TO `free`   SYS `strdup`, "Hello World!" TO address% PRINT $$address% SYS `free`, address%  
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#C
C
  #include <stdlib.h> #include <stdio.h>   int main(int argc,char** argv) {   int arg1 = atoi(argv[1]), arg2 = atoi(argv[2]), sum, diff, product, quotient, remainder ;   __asm__ ( "addl %%ebx, %%eax;" : "=a" (sum) : "a" (arg1) , "b" (arg2) ); __asm__ ( "subl %%ebx, %%eax;" : "=a" (diff) : "a" (arg1) , "b" (arg2) ); __asm__ ( "imull %%ebx, %%eax;" : "=a" (product) : "a" (arg1) , "b" (arg2) );   __asm__ ( "movl $0x0, %%edx;" "movl %2, %%eax;" "movl %3, %%ebx;" "idivl %%ebx;" : "=a" (quotient), "=d" (remainder) : "g" (arg1), "g" (arg2) );   printf( "%d + %d = %d\n", arg1, arg2, sum ); printf( "%d - %d = %d\n", arg1, arg2, diff ); printf( "%d * %d = %d\n", arg1, arg2, product ); printf( "%d / %d = %d\n", arg1, arg2, quotient ); printf( "%d %% %d = %d\n", arg1, arg2, remainder );   return 0 ; }  
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Ada
Ada
# Note functions and subroutines are called procedures (or PROCs) in Algol 68 # # A function called without arguments: # f; # Algol 68 does not expect an empty parameter list for calls with no arguments, "f()" is a syntax error # # A function with a fixed number of arguments: # f(1, x);   # variable number of arguments: # # functions that accept an array as a parameter can effectively provide variable numbers of arguments # # a "literal array" (called a row-display in Algol 68) can be passed, as is often the case for the I/O # # functions - e.g.: # print( ( "the result is: ", r, " after ", n, " iterations", newline ) ); # the outer brackets indicate the parameters of print, the inner brackets indicates the contents are a "literal array" #   # ALGOL 68 does not support optional arguments, though in some cases an empty array could be passed to a function # # expecting an array, e.g.: # f( () );   # named arguments - see the Algol 68 sample in: http://rosettacode.org/wiki/Named_parameters #   # In "Talk:Call a function" a statement context is explained as "The function is used as an instruction (with a void context), rather than used within an expression." Based on that, the examples above are already in a statement context. Technically, when a function that returns other than VOID (i.e. is not a subroutine) is called in a statement context, the result of the call is "voided" i.e. discarded. If desired, this can be made explicit using a cast, e.g.: # VOID(f);   # A function's return value being used: # x := f(y);   # There is no distinction between built-in functions and user-defined functions. #   # A subroutine is simply a function that returns VOID. #   # If the function is declared with argument(s) of mode REF MODE, then those arguments are being passed by reference. # # Technically, all parameters are passed by value, however the value of a REF MODE is a reference... #
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Factor
Factor
USING: grouping.extras io kernel math sequences sequences.repeating ; IN: rosetta-code.cantor-set   CONSTANT: width 81 CONSTANT: depth 5   : cantor ( n -- seq ) dup 0 = [ drop { 0 1 } ] [ 1 - cantor [ 3 / ] map dup [ 2/3 + ] map append ] if ;   ! Produces a sequence of lengths from a Cantor set, depending on ! width. Even indices are solid; odd indices are blank. ! e.g. 2 cantor gaps -> { 9 9 9 27 9 9 9 } ! : gaps ( seq -- seq ) [ width * ] map [ - abs ] 2clump-map ;   : print-cantor ( n -- ) cantor gaps [ even? "#" " " ? swap repeat ] map-index concat print ;   depth <iota> [ print-cantor ] each
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Forth
Forth
warnings off   4 \ iterations : ** 1 swap 0 ?DO over * LOOP nip ; 3 swap ** constant width \ Make smallest step 1   create string here width char # fill width allot : print string width type cr ;   \ Overwrite string with new holes of size 'length'. \ Pointer into string at TOS. create length width , : reduce length dup @ 3 / swap ! ; : done? dup string - width >= ; : hole? dup c@ bl = ; : skip length @ + ; : whipe dup length @ bl fill skip ; : step hole? IF skip skip skip ELSE skip whipe skip THEN ; : split reduce string BEGIN step done? UNTIL drop ;   \ Main : done? length @ 1 <= ; : step split print ; : go print BEGIN step done? UNTIL ;   go bye
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#J
J
cw_next_term^:(<20)1x 1 1r2 2 1r3 3r2 2r3 3 1r4 4r3 3r5 5r2 2r5 5r3 3r4 4 1r5 5r4 4r7 7r3 3r8 (,. index_cw_term&>) 3r4 53r37 83116r51639 3r4 14 53r37 1081 83116r51639 123456789
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Julia
Julia
function calkin_wilf(n) cw = zeros(Rational, n + 1) for i in 2:n + 1 t = Int(floor(cw[i - 1])) * 2 - cw[i - 1] + 1 cw[i] = 1 // t end return cw[2:end] end   function continued(r::Rational) a, b = r.num, r.den res = [] while true push!(res, Int(floor(a / b))) a, b = b, a % b a == 1 && break end return res end   function term_number(cf) b, d = "", "1" for n in cf b = d^n * b d = (d == "1") ? "0" : "1" end return parse(Int, b, base=2) end   const cw = calkin_wilf(20) println("The first 20 terms of the Calkin-Wilf sequence are: $cw")   const r = 83116 // 51639 const cf = continued(r) const tn = term_number(cf) println("$r is the $tn-th term of the sequence.")  
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Perl
Perl
sub co9 { # Follows the simple procedure asked for in Part 1 my $n = shift; return $n if $n < 10; my $sum = 0; $sum += $_ for split(//,$n); co9($sum); }   sub showadd { my($n,$m) = @_; print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]", " = ", $n+$m," [",co9($n+$m),"]\n"; }   sub co9filter { my $base = shift; die unless $base >= 2; my($beg, $end, $basem1) = (1, $base*$base-1, $base-1); my @list = grep { $_ % $basem1 == $_*$_ % $basem1 } $beg .. $end; ($end, scalar(@list), @list); }   print "Part 1: Create a simple filter and demonstrate using simple example.\n"; showadd(6395, 1259);   print "\nPart 2: Use this to filter a range with co9(k) == co9(k^2).\n"; print join(" ", grep { co9($_) == co9($_*$_) } 1..99), "\n";   print "\nPart 3: Use efficient method on range.\n"; for my $base (10, 17) { my($N, $n, @l) = co9filter($base); printf "[@l]\nIn base %d, trying %d numbers instead of %d saves %.4f%%\n\n", $base, $n, $N, 100-($n/$N)*100; }
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Cases[Cases[ Cases[Table[{p1, h3, d}, {p1, Array[Prime, PrimePi@61]}, {h3, 2, p1 - 1}, {d, 1, h3 + p1 - 1}], {p1_Integer, h3_, d_} /; PrimeQ[1 + (p1 - 1) (h3 + p1)/d] && Divisible[p1^2 + d, h3] :> {p1, 1 + (p1 - 1) (h3 + p1)/d, h3}, Infinity], {p1_, p2_, h3_} /; PrimeQ[1 + Floor[p1 p2/h3]] :> {p1, p2, 1 + Floor[p1 p2/h3]}], {p1_, p2_, p3_} /; Mod[p2 p3, p1 - 1] == 1 :> Print[p1, "*", p2, "*", p3]]
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Nim
Nim
import strformat   func isPrime(n: int64): bool = if n == 2 or n == 3: return true elif n < 2 or n mod 2 == 0 or n mod 3 == 0: return false var `div` = 5i64 var `inc` = 2i64 while `div` * `div` <= n: if n mod `div` == 0: return false `div` += `inc` `inc` = 6 - `inc` return true   for p in 2i64 .. 61: if not isPrime(p): continue for h3 in 2i64 ..< p: var g = h3 + p for d in 1 ..< g: if g * (p - 1) mod d != 0 or (d + p * p) mod h3 != 0: continue var q = 1 + (p - 1) * g div d if not isPrime(q): continue var r = 1 + (p * q div h3) if not isPrime(r) or (q * r) mod (p - 1) != 1: continue echo &"{p:5} × {q:5} × {r:5} = {p * q * r:10}"
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Icon_and_Unicon
Icon and Unicon
procedure main(A) write(A[1],": ",curry(A[1],A[2:0])) end   procedure curry(f,A) r := A[1] every r := f(r, !A[2:0]) return r end