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/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#BASIC
BASIC
DECLARE FUNCTION multiply% (a AS INTEGER, b AS INTEGER)   FUNCTION multiply% (a AS INTEGER, b AS INTEGER) multiply = a * b END FUNCTION
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Python
Python
from collections import deque from itertools import islice, count     def fusc(): q = deque([1]) yield 0 yield 1   while True: x = q.popleft() q.append(x) yield x   x += q[0] q.append(x) yield x     def longest_fusc(): sofar = 0 for i, f in zip(count(), fusc()): if f >= sofar: yield(i, f) sofar = 10 * sofar or 10     print('First 61:') print(list(islice(fusc(), 61)))   print('\nLength records:') for i, f in islice(longest_fusc(), 6): print(f'fusc({i}) = {f}')  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Limbo
Limbo
implement Lanczos7;   include "sys.m"; sys: Sys; include "draw.m"; include "math.m"; math: Math; lgamma, exp, pow, sqrt: import math;   Lanczos7: module { init: fn(nil: ref Draw->Context, nil: list of string); };   init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; math = load Math Math->PATH; # We ignore some floating point exceptions: math->FPcontrol(0, Math->OVFL|Math->UNFL); ns : list of real = -0.5 :: 0.1 :: 0.5 :: 1.0 :: 1.5 :: 2.0 :: 3.0 :: 10.0 :: 140.0 :: 170.0 :: nil;   sys->print("%5s %24s %24s\n", "x", "math->lgamma", "lanczos7"); while(ns != nil) { x := hd ns; ns = tl ns; # math->lgamma returns a tuple. (i, r) := lgamma(x); g := real i * exp(r); sys->print("%5.1f %24.16g %24.16g\n", x, g, lanczos7(x)); } }   lanczos7(z: real): real { t := z + 6.5; x := 0.99999999999980993 + 676.5203681218851/z - 1259.1392167224028/(z+1.0) + 771.32342877765313/(z+2.0) - 176.61502916214059/(z+3.0) + 12.507343278686905/(z+4.0) - 0.13857109526572012/(z+5.0) + 9.9843695780195716e-6/(z+6.0) + 1.5056327351493116e-7/(z+7.0); return sqrt(2.0) * sqrt(Math->Pi) * pow(t, z - 0.5) * exp(-t) * x; }  
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#SQL
SQL
  /* This code is an implementation of gapful numbers in SQL ORACLE 19c p_start -- start point p_count -- total number to be found */ WITH FUNCTION gapful_numbers(p_start IN INTEGER, p_count IN INTEGER) RETURN varchar2 IS v_start INTEGER := p_start; v_count INTEGER := 0; v_res varchar2(32767); BEGIN v_res := 'First '||p_count||' gapful numbers starting from '||p_start||': '; -- main cycle while TRUE loop IF MOD(v_start,to_number(substr(v_start,1,1)||substr(v_start,-1))) = 0 THEN v_res := v_res || v_start; v_count := v_count + 1; exit WHEN v_count = p_count; v_res := v_res || ', '; END IF; v_start := v_start + 1; END loop; -- RETURN v_res; -- END;   --Test SELECT gapful_numbers(100,30) AS res FROM dual UNION ALL SELECT gapful_numbers(1000000,15) AS res FROM dual UNION ALL SELECT gapful_numbers(1000000000,10) AS res FROM dual; /  
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Raku
Raku
sub gauss-jordan-solve (@a, @b) { @b.kv.map: { @a[$^k].append: $^v }; @a.&rref[*]»[*-1]; }   # reduced row echelon form sub rref (@m) { my ($lead, $rows, $cols) = 0, @m, @m[0];   for ^$rows -> $r { $lead < $cols or return @m; my $i = $r; until @m[$i;$lead] { ++$i == $rows or next; $i = $r; ++$lead == $cols and return @m; } @m[$i, $r] = @m[$r, $i] if $r != $i; @m[$r] »/=» $ = @m[$r;$lead]; for ^$rows -> $n { next if $n == $r; @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0); } ++$lead; } @m }   sub rat-or-int ($num) { return $num unless $num ~~ Rat; return $num.narrow if $num.narrow ~~ Int; $num.nude.join: '/'; }   sub say-it ($message, @array, $fmt = " %8s") { say "\n$message"; $_».&rat-or-int.fmt($fmt).put for @array; }   my @a = ( [ 1.00, 0.00, 0.00, 0.00, 0.00, 0.00 ], [ 1.00, 0.63, 0.39, 0.25, 0.16, 0.10 ], [ 1.00, 1.26, 1.58, 1.98, 2.49, 3.13 ], [ 1.00, 1.88, 3.55, 6.70, 12.62, 23.80 ], [ 1.00, 2.51, 6.32, 15.88, 39.90, 100.28 ], [ 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 ], ); my @b = ( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 );   say-it 'A matrix:', @a, "%6.2f"; say-it 'or, A in exact rationals:', @a; say-it 'B matrix:', @b, "%6.2f"; say-it 'or, B in exact rationals:', @b; say-it 'x matrix:', (my @gj = gauss-jordan-solve @a, @b), "%16.12f"; say-it 'or, x in exact rationals:', @gj, "%28s";  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Pascal
Pascal
program lowerCaseAscii(input, output, stdErr); var alphabet: set of char; begin // as per ISO 7185, 'a'..'z' do not necessarily have to be contiguous alphabet := [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; end.
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#PL.2FI
PL/I
goodbye:proc options(main); put list('Hello world!'); end goodbye;
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#VBA
VBA
Public lastsquare As Long Public nextsquare As Long Public lastcube As Long Public midcube As Long Public nextcube As Long Private Sub init() lastsquare = 1 nextsquare = -1 lastcube = -1 midcube = 0 nextcube = 1 End Sub   Private Function squares() As Long lastsquare = lastsquare + nextsquare nextsquare = nextsquare + 2 squares = lastsquare End Function   Private Function cubes() As Long lastcube = lastcube + nextcube nextcube = nextcube + midcube midcube = midcube + 6 cubes = lastcube End Function   Public Sub main() init cube = cubes For i = 1 To 30 Do While True square = squares Do While cube < square cube = cubes Loop If square <> cube Then Exit Do End If Loop If i > 20 Then Debug.Print square; End If Next i End Sub
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#JavaScript
JavaScript
function compose(f, g) { return function(x) { return f(g(x)); }; }
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Joy
Joy
g f
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Perl
Perl
use GD::Simple;   my ($width, $height) = (1000,1000); # image dimension my $scale = 6/10; # branch scale relative to trunk my $length = 400; # trunk size   my $img = GD::Simple->new($width,$height); $img->fgcolor('black'); $img->penSize(1,1);   tree($width/2, $height, $length, 270);   print $img->png;     sub tree { my ($x, $y, $len, $angle) = @_;   return if $len < 1;   $img->moveTo($x,$y); $img->angle($angle); $img->line($len);   ($x, $y) = $img->curPos();   tree($x, $y, $len*$scale, $angle+35); tree($x, $y, $len*$scale, $angle-35); }
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#Python
Python
def indexOf(haystack, needle): idx = 0 for straw in haystack: if straw == needle: return idx else: idx += 1 return -1   def getDigits(n, le, digits): while n > 0: r = n % 10 if r == 0 or indexOf(digits, r) >= 0: return False le -= 1 digits[le] = r n = int(n / 10) return True   def removeDigit(digits, le, idx): pows = [1, 10, 100, 1000, 10000] sum = 0 pow = pows[le - 2] i = 0 while i < le: if i == idx: i += 1 continue sum = sum + digits[i] * pow pow = int(pow / 10) i += 1 return sum   def main(): lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ] count = [0 for i in range(5)] omitted = [[0 for i in range(10)] for j in range(5)]   i = 0 while i < len(lims): n = lims[i][0] while n < lims[i][1]: nDigits = [0 for k in range(i + 2)] nOk = getDigits(n, i + 2, nDigits) if not nOk: n += 1 continue d = n + 1 while d <= lims[i][1] + 1: dDigits = [0 for k in range(i + 2)] dOk = getDigits(d, i + 2, dDigits) if not dOk: d += 1 continue nix = 0 while nix < len(nDigits): digit = nDigits[nix] dix = indexOf(dDigits, digit) if dix >= 0: rn = removeDigit(nDigits, i + 2, nix) rd = removeDigit(dDigits, i + 2, dix) if (1.0 * n / d) == (1.0 * rn / rd): count[i] += 1 omitted[i][digit] += 1 if count[i] <= 12: print "%d/%d = %d/%d by omitting %d's" % (n, d, rn, rd, digit) nix += 1 d += 1 n += 1 print i += 1   i = 2 while i <= 5: print "There are %d %d-digit fractions of which:" % (count[i - 2], i) j = 1 while j <= 9: if omitted[i - 2][j] == 0: j += 1 continue print "%6s have %d's omitted" % (omitted[i - 2][j], j) j += 1 print i += 1 return None   main()
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Java
Java
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class Fractran{   public static void main(String []args){   new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15;     Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); }     void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } }   void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; }   void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Batch_File
Batch File
@ECHO OFF SET /A result = 0 CALL :multiply 2 3 ECHO %result% GOTO :eof   :multiply SET /A result = %1 * %2 GOTO :eof   :eof
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Quackery
Quackery
  [ 1 & ] is odd ( n --> b )   [ 0 swap [ dip 1+ 10 / dup 0 = until ] drop ] is digits ( n --> n )   [ dup dup size dup odd iff [ dup 1 - 2 / dip [ 1 + 2 / peek over ] peek + ] else [ 2 / peek ] join ] is nextfusc ( [ --> [ )   say "First 61 terms." cr ' [ 0 1 ] 59 times nextfusc witheach [ echo sp ] cr cr say "Terms where the digit count increases." cr say "fusc(0) = 0" cr 1 ' [ 0 1 ] [ nextfusc dup -1 peek digits rot 2dup > iff [ drop swap say "fusc(" dup -1 peek echo say ") = " dup size 1 - echo cr ] else [ nip swap ] dup size 1000000 = until ] 2drop
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#R
R
firstNFuscNumbers <- function(n) { stopifnot(n > 0) if(n == 1) return(0) else fusc <- c(0, 1) if(n > 2) { for(i in seq(from = 3, to = n, by = 1)) { fusc[i] <- if(i %% 2) fusc[(i + 1) / 2] else fusc[i / 2] + fusc[(i + 2) / 2] } } fusc } first61 <- firstNFuscNumbers(61) cat("The first 61 Fusc numbers are:", "\n", first61, "\n")
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Lua
Lua
gamma, coeff, quad, qui, set = 0.577215664901, -0.65587807152056, -0.042002635033944, 0.16653861138228, -0.042197734555571 function recigamma(z) return z + gamma * z^2 + coeff * z^3 + quad * z^4 + qui * z^5 + set * z^6 end   function gammafunc(z) if z == 1 then return 1 elseif math.abs(z) <= 0.5 then return 1 / recigamma(z) else return (z - 1) * gammafunc(z-1) end end
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Swift
Swift
func isGapful(n: Int) -> Bool { guard n > 100 else { return true }   let asString = String(n) let div = Int("\(asString.first!)\(asString.last!)")!   return n % div == 0 }   let first30 = (100...).lazy.filter(isGapful).prefix(30) let mil = (1_000_000...).lazy.filter(isGapful).prefix(15) let bil = (1_000_000_000...).lazy.filter(isGapful).prefix(15)   print("First 30 gapful numbers: \(Array(first30))") print("First 15 >= 1,000,000: \(Array(mil))") print("First 15 >= 1,000,000,000: \(Array(bil))")
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Tcl
Tcl
proc ungap n { if {[string length $n] < 3} { return $n } return [string index $n 0][string index $n end] }   proc gapful n { return [expr {0 == ($n % [ungap $n])}] }   ## --> list of gapful numbers >= n proc GFlist {count n} { set r {} while {[llength $r] < $count} { if {[gapful $n]} { lappend r $n } incr n } return $r }   proc show {count n} { puts "The first $count gapful >= $n: [GFlist $count $n]" }   show 30 100 show 15 1000000 show 10 1000000000  
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#REXX
REXX
/* REXX --------------------------------------------------------------- * 07.08.2014 Walter Pachl translated from PL/I) * improved to get integer results for, e.g. this input: -6 -18 13 6 -6 -15 -2 -9 -231 2 20 9 2 16 -12 -18 -5 647 23 18 -14 -14 -1 16 25 -17 -907 -8 -1 -19 4 3 -14 23 8 248 25 20 -6 15 0 -10 9 17 1316 -13 -1 3 5 -2 17 14 -12 -1080 19 24 -21 -5 -19 0 -24 -17 1006 20 -3 -14 -16 -23 -25 -15 20 1496 *--------------------------------------------------------------------*/ Numeric Digits 20 Parse Arg t n=3 Parse Value '1 2 3 14' With a.1.1 a.1.2 a.1.3 b.1 Parse Value '2 1 3 13' With a.2.1 a.2.2 a.2.3 b.2 Parse Value '3 -2 -1 -4' With a.3.1 a.3.2 a.3.3 b.3 If t=6 Then Do n=6 Parse Value '1.00 0.00 0.00 0.00 0.00 0.00 ' With a.1.1 a.1.2 a.1.3 a.1.4 a.1.5 a.1.6 . Parse Value '1.00 0.63 0.39 0.25 0.16 0.10 ' With a.2.1 a.2.2 a.2.3 a.2.4 a.2.5 a.2.6 . Parse Value '1.00 1.26 1.58 1.98 2.49 3.13 ' With a.3.1 a.3.2 a.3.3 a.3.4 a.3.5 a.3.6 . Parse Value '1.00 1.88 3.55 6.70 12.62 23.80 ' With a.4.1 a.4.2 a.4.3 a.4.4 a.4.5 a.4.6 . Parse Value '1.00 2.51 6.32 15.88 39.90 100.28' With a.5.1 a.5.2 a.5.3 a.5.4 a.5.5 a.5.6 . Parse Value '1.00 3.14 9.87 31.01 97.41 306.02' With a.6.1 a.6.2 a.6.3 a.6.4 a.6.5 a.6.6 . Parse Value '-0.01 0.61 0.91 0.99 0.60 0.02' With b.1 b.2 b.3 b.4 b.5 b.6 . End Do i=1 To n Do j=1 To n sa.i.j=a.i.j End sb.i=b.i End Say 'The equations are:' do i = 1 to n; ol='' Do j=1 To n ol=ol format(a.i.j,4,4) End ol=ol' 'format(b.i,4,4) Say ol end   call Gauss_elimination   call Backward_substitution   Say 'Solutions:' Do i=1 To n Say 'x('i')='||x.i End   /* Check solutions: */ Say 'Residuals:' do i = 1 to n res=0 Do j=1 To n res=res+(sa.i.j*x.j) End res=res-sb.i Say 'res('i')='res End   Exit   Gauss_elimination: Do j=1 to n-1 ma=a.j.j Do ja=j+1 To n mb=a.ja.j Do i=1 To n new=a.j.i*mb-a.ja.i*ma a.ja.i=new End b.ja=b.j*mb-b.ja*ma End End Return   Backward_substitution: x.n = b.n / a.n.n do j = n-1 to 1 by -1 t = 0 do i = j+1 to n t = t + a.j.i*x.i end x.j = (b.j - t) / a.j.j end Return
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Perl
Perl
print 'a'..'z'
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phix
Phix
string az = "" for ch='a' to 'z' do az &= ch end for ?az ?tagset('z','a')
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#PL.2FM
PL/M
100H: /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; /* PRINT A $ TERMINATED STRING */ PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; /* HELLO, WORLD! IN MIXED CASE */ DECLARE HELLO$WORLD ( 14 ) BYTE INITIAL( 'H', 65H, 6CH, 6CH, 6FH, ',', ' ' , 'W', 6FH, 72H, 6CH, 64H, 21H, '$' ); CALL PRINT$STRING( .HELLO$WORLD ); EOF
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#Visual_Basic_.NET
Visual Basic .NET
Module Program Iterator Function IntegerPowers(exp As Integer) As IEnumerable(Of Integer) Dim i As Integer = 0 Do Yield CInt(Math.Pow(i, exp)) i += 1 Loop End Function   Function Squares() As IEnumerable(Of Integer) Return IntegerPowers(2) End Function   Function Cubes() As IEnumerable(Of Integer) Return IntegerPowers(3) End Function   Iterator Function SquaresWithoutCubes() As IEnumerable(Of Integer) Dim cubeSequence = Cubes().GetEnumerator() Dim nextGreaterOrEqualCube As Integer = 0 For Each curSquare In Squares() Do While nextGreaterOrEqualCube < curSquare cubeSequence.MoveNext() nextGreaterOrEqualCube = cubeSequence.Current Loop If nextGreaterOrEqualCube <> curSquare Then Yield curSquare Next End Function   Sub Main() For Each x In From i In SquaresWithoutCubes() Skip 20 Take 10 Console.WriteLine(x) Next End Sub End Module
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#jq
jq
  # apply g first and then f def compose(f; g): g | f;  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Julia
Julia
@show (asin ∘ sin)(0.5)
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Phix
Phix
-- -- demo\rosetta\FractalTree.exw -- ============================ -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas procedure drawTree(integer level, atom angle, len, integer x, y) integer xn = x + floor(len*cos(angle)), yn = y + floor(len*sin(angle)), red = 255-level*8, green = level*12+100 cdCanvasSetForeground(cddbuffer, red*#10000 + green*#100) cdCanvasSetLineWidth(cddbuffer,floor(5-level/3)) cdCanvasLine(cddbuffer, x, 480-y, xn, 480-yn) if level<12 then drawTree(level+1, angle-0.4, len*0.8, xn, yn) --left drawTree(level+1, angle+0.1, len*0.8, xn, yn) --right end if end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) drawTree(0, -PI/2.0, 80.0, 360, 460) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_PARCHMENT) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=640x480") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas,"RESIZE=NO") IupSetAttribute(dlg, "TITLE", "Fractal Tree") IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#Racket
Racket
#lang racket   (require racket/generator syntax/parse/define)   (define-syntax-parser for** [(_ [x:id {~datum <-} (e ...)] rst ...) #'(e ... (λ (x) (for** rst ...)))] [(_ e ...) #'(begin e ...)])   (define (permutations xs n yield #:lower [lower #f]) (let loop ([xs xs] [n n] [acc '()] [lower lower]) (cond [(= n 0) (yield (reverse acc))] [else (for ([x (in-list xs)] #:when (or (not lower) (>= x (first lower)))) (loop (remove x xs) (sub1 n) (cons x acc) (and lower (= x (first lower)) (rest lower))))])))   (define (list->number xs) (foldl (λ (e acc) (+ (* 10 acc) e)) 0 xs))   (define (calc n) (define rng (range 1 10)) (in-generator (for** [numer <- (permutations rng n)] [denom <- (permutations rng n #:lower numer)] (for* (#:when (not (equal? numer denom)) [crossed (in-list numer)] #:when (member crossed denom) [numer* (in-value (list->number (remove crossed numer)))] [denom* (in-value (list->number (remove crossed denom)))] [numer** (in-value (list->number numer))] [denom** (in-value (list->number denom))] #:when (= (* numer** denom*) (* numer* denom**))) (yield (list numer** denom** numer* denom* crossed))))))   (define (enumerate n) (for ([x (calc n)] [i (in-range 12)]) (apply printf "~a/~a = ~a/~a (~a crossed out)\n" x)) (newline))   (define (stats n) (define digits (make-hash)) (for ([x (calc n)]) (hash-update! digits (last x) add1 0)) (printf "There are ~a ~a-digit fractions of which:\n" (for/sum ([(k v) (in-hash digits)]) v) n) (for ([digit (in-list (sort (hash->list digits) < #:key car))]) (printf " The digit ~a was crossed out ~a times\n" (car digit) (cdr digit))) (newline))   (define (main) (enumerate 2) (enumerate 3) (enumerate 4) (enumerate 5) (stats 2) (stats 3) (stats 4) (stats 5))   (main)
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#JavaScript
JavaScript
// Parses the input string for the numerators and denominators function compile(prog, numArr, denArr) { let regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m; let result; while (result = regex.exec(prog)) { numArr.push(result[1]); denArr.push(result[2]); prog = result[3]; } return [numArr, denArr]; }   // Outputs the result of the compile stage function dump(numArr, denArr) { let output = ""; for (let i in numArr) { output += `${numArr[i]}/${denArr[i]} `; } return `${output}<br>`; }   // Step function step(val, numArr, denArr) { let i = 0; while (i < denArr.length && val % denArr[i] != 0) i++; return numArr[i] * val / denArr[i]; }   // Executes Fractran function exec(val, i, limit, numArr, denArr) { let output = ""; while (val && i < limit) { output += `${i}: ${val}<br>`; val = step(val, numArr, denArr); i++; } return output; }   // Main // Outputs to DOM (clears and writes at the body tag) let body = document.body; let [num, den] = compile("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", [], []); body.innerHTML = dump(num, den); body.innerHTML += exec(2, 0, 15, num, den);
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#BBC_BASIC
BBC BASIC
PRINT FNmultiply(6,7) END   DEF FNmultiply(a,b) = a * b
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Racket
Racket
#lang racket   (require racket/generator)   (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args)))))   (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))   (define (comma x) (string-join (reverse (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)]) (cond [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)] [else (string digit)]))) ""))   ;; Task 1 (displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " ")) (newline)   ;; Task 2 (define gen (in-generator (let loop ([prev 0] [i 0]) (define result (fusc i)) (define len (string-length (~a result))) (cond [(> len prev) (yield (list i result)) (loop len (add1 i))] [else (loop prev (add1 i))]))))   (for ([i (in-range 5)] [x gen]) (match-define (list index result) x) (printf "~a: ~a\n" (comma index) (comma result)))
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Raku
Raku
my @Fusc = 0, 1, 1, { |(@Fusc[$_ - 1] + @Fusc[$_], @Fusc[$_]) given ++$+1 } ... *;   sub comma { $^i.flip.comb(3).join(',').flip }   put "First 61 terms of the Fusc sequence:\n{@Fusc[^61]}" ~ "\n\nIndex and value for first term longer than any previous:";   for flat 'Index', 'Value', 0, 0, (1..4).map({ my $l = 10**$_; @Fusc.first(* > $l, :kv).map: &comma }) -> $i, $v { printf "%15s : %s\n", $i, $v }
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#M2000_Interpreter
M2000 Interpreter
  Module PrepareLambdaFunctions { Const e = 2.7182818284590452@ Exp= Lambda e (x) -> e^x gammaStirling=lambda e (x As decimal)->Sqrt(2.0 * pi / x) * ((x / e) ^ x) Rad2Deg =Lambda pidivby180=pi/180 (RadAngle)->RadAngle / pidivby180 Dim p(9) p(0)=0.99999999999980993@, 676.5203681218851@, -1259.1392167224028@, 771.32342877765313@ p(4)=-176.61502916214059@, 12.507343278686905@, -0.13857109526572012@, 0.0000099843695780195716@ p(8)=0.00000015056327351493116@ gammaLanczos =Lambda p(), Rad2Deg, Exp (x As decimal) -> { Def Decimal a, t If x < 0.5 Then =pi / (Sin(Rad2Deg(pi * x)) *Lambda(1-x)) : Exit x -= 1@ a=p(0) t = x + 7.5@ For i= 1@ To 8@ { a += p(i) / (x + i) } = Sqrt(2.0 * pi) * (t ^ (x + 0.5)) * Exp(-t) * a } Push gammaStirling, gammaLanczos } Call PrepareLambdaFunctions Read gammaLanczos, gammaStirling Font "Courier New" Form 120, 40 document doc$=" χ Stirling Lanczos"+{ } Print $(2,20),"x", "Stirling",@(55),"Lanczos", $(0) Print For d = 0.1 To 2 step 0.1 Print $("0.00"), d, Print $("0.000000000000000"), gammaStirling(d), Print $("0.0000000000000000000000000000"), gammaLanczos(d) doc$=format$("{0:-10} {1:-30} {2:-34}",str$(d,"0.00"), str$(gammaStirling(d),"0.000000000000000"), str$(gammaLanczos(d),"0.0000000000000000000000000000"))+{ } Next d Print $("") clipboard doc$  
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#UNIX_Shell
UNIX Shell
first-digit() { printf '%s\n' "${1:0:1}" }   last-digit() { printf '%s\n' $(( $1 % 10 )) }   bookend-number() { printf '%s%s\n' "$(first-digit "$@")" "$(last-digit "$@")" }   is-gapful() { (( $1 >= 100 && $1 % $(bookend-number "$1") == 0 )) }   gapfuls-in-range() { local gapfuls=() local -i i found for (( i=$1, found=0; found < $2; ++i )); do if is-gapful "$i"; then if (( found )); then printf ' '; fi printf '%s' "$i" (( found++ )) fi done printf '\n' }   report-ranges() { local range local -i start size for range; do IFS=, read start size <<<"$range" printf 'The first %d gapful numbers >= %d:\n' "$size" "$start" gapfuls-in-range "$start" "$size" printf '\n' done }   report-ranges 1,30 1000000,15 1000000000,10
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Ruby
Ruby
  require 'bigdecimal/ludcmp' include LUSolve   BigDecimal::limit(30)   a = [1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02].map{|i|BigDecimal(i,16)} b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02].map{|i|BigDecimal(i,16)}   n = 6 zero = BigDecimal("0.0") one = BigDecimal("1.0")   lusolve(a, b, ludecomp(a, n, zero,one), zero).each{|v| puts v.to_s('F')[0..20]}
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phixmonti
Phixmonti
0 tolist 'a' 'z' 2 tolist for tochar 0 put endfor print
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PHP
PHP
<?php $lower = range('a', 'z'); var_dump($lower); ?>
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#PL.2FSQL
PL/SQL
  SET serveroutput ON   BEGIN DBMS_OUTPUT.PUT_LINE('Hello world!'); END; /  
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#XPL0
XPL0
code ChOut=8, IntOut=11;   func Gen(M); \Generate Mth powers of positive integers int M; int N, R, I; [N:= [0, 0, 0, 0]; \provides own/static variables R:= 1; for I:= 1 to M do R:= R*N(M); N(M):= N(M)+1; return R; ];   func Filter; \Generate squares of positive integers that aren't cubes int S, C; [C:= [0]; \static variable = smallest cube > current square repeat S:= Gen(2); while S > C(0) do C(0):= Gen(3); until S # C(0); return S; ];   int I; [for I:= 1 to 20 do Filter; \drop first 20 values for I:= 1 to 10 do [IntOut(0, Filter); ChOut(0, ^ )]; \show next 10 values ]
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#K
K
compose:{'[x;y]}
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Klingphix
Klingphix
include ..\Utilitys.tlhy   :*2 2 * ; :++ 1 + ; :composite swap exec swap exec ;   @++ @*2 3 composite ? { result: 7 }   "End " input
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#PHP
PHP
  <?php header("Content-type: image/png");   $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg);   $depth = 8; function drawTree($x1, $y1, $angle, $depth){   global $img;   if ($depth != 0){ $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0); $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);   imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));   drawTree($x2, $y2, $angle - 20, $depth - 1); drawTree($x2, $y2, $angle + 20, $depth - 1); } }   drawTree($width/2, $height, -90, $depth);   imagepng($img); imagedestroy($img); ?>  
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#Raku
Raku
my %reduced; my $digits = 2..4;   for $digits.map: * - 1 -> $exp { my $start = sum (0..$exp).map( { 10 ** $_ * ($exp - $_ + 1) }); my $end = 10**($exp+1) - sum (^$exp).map( { 10 ** $_ * ($exp - $_) } ) - 1;   ($start ..^ $end).race(:8degree, :3batch).map: -> $den { next if $den.contains: '0'; next if $den.comb.unique <= $exp;   for $start ..^ $den -> $num { next if $num.contains: '0'; next if $num.comb.unique <= $exp;   my $set = ($den.comb.head(* - 1).Set ∩ $num.comb.skip(1).Set); next if $set.elems < 1;   for $set.keys { my $ne = $num.trans: $_ => '', :delete; my $de = $den.trans: $_ => '', :delete; if $ne / $de == $num / $den { print "\b" x 40, "$num/$den:$_ => $ne/$de"; %reduced{"$num/$den:$_"} = "$ne/$de"; } } } }     print "\b" x 40, ' ' x 40, "\b" x 40;   my $digit = $exp +1; my %d = %reduced.pairs.grep: { .key.chars == ($digit * 2 + 3) }; say "\n({+%d}) $digit digit reduceable fractions:"; for 1..9 { my $cnt = +%d.pairs.grep( *.key.contains: ":$_" ); next unless $cnt; say " $cnt with removed $_"; } say "\n 12 Random (or all, if less) $digit digit reduceable fractions:"; say " {.key.substr(0, $digit * 2 + 1)} => {.value} removed {.key.substr(* - 1)}" for %d.pairs.pick(12).sort; }
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Julia
Julia
function fractran(n::Integer, ratios::Vector{<:Rational}, steplim::Integer) rst = zeros(BigInt, steplim) for i in 1:steplim rst[i] = n if (pos = findfirst(x -> isinteger(n * x), ratios)) > 0 n *= ratios[pos] else break end end return rst end   using IterTools macro ratio_str(s) a = split(s, r"[\s,/]+") return collect(parse(BigInt, n) // parse(BigInt, d) for (n, d) in partition(a, 2)) end   fracs = ratio"""17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33, 77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13, 13 / 11, 15 / 14, 15 / 2, 55 / 1""" println("The first 20 in the series are ", fractran(2, fracs, 20))   prmfound = 0 n = big(2) while prmfound < 20 global n global prmfound if isinteger(log2(n)) prmfound += 1 println("Prime $prmfound found: $n is 2 ^ $(Int(log2(n)))") end n = fractran(n, fracs, 2)[2] end
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#bc
bc
define multiply(a, b) { return a*b }   print multiply(2, 3)
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#REXX
REXX
/*REXX program calculates and displays the fusc (or Stern's Diatomic) sequence. */ parse arg st # xw . /*obtain optional arguments from the CL*/ if st=='' | st=="," then st= 0 /*Not specified? Then use the default.*/ if #=='' | #=="," then #= 61 /* " " " " " " */ if xw=='' | xw=="," then xw= 0 /* " " " " " " */ list= xw<1 /*boolean value: LIST to show numbers*/ @.=; @.0= 0; @.1= 1 /*assign array default; assign low vals*/ mL= 0 /*the maximum length (digits) so far. */ $= /* " list of fusc numbers " " */ do j=0 for # /*process a bunch of integers from zero*/ if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end else do; _= j % 2; @.j= @._; end if list then if j>=st then $= $ commas(@.j) /*add it to a list*/ else nop /*NOP≡placeholder.*/ else do; if length(@.j)<=mL then iterate /*still too small.*/ mL= length(@.j) /*found increase. */ if mL==1 then say '═══index═══ ═══fusc number═══' say right( commas(j), 9) right( commas(@.j), 14) if mL==xw then leave /*Found max length? Then stop looking.*/ end /* [↑] display fusc #s of maximum len.*/ end /*j*/ /*$ has a superfluous leading blank. */ if $\=='' then say strip($) /*display a horizontal list of fusc #s.*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Maple
Maple
GAMMA(17/2); GAMMA(7*I); M := Matrix(2, 3, 'fill' = -3.6); MTM:-gamma(M);
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function FirstNum(n As Integer) As Integer REM Divide by ten until the leading digit remains. While n >= 10 n /= 10 End While Return n End Function   Function LastNum(n As Integer) As Integer REM Modulo gives you the last digit. Return n Mod 10 End Function   Sub FindGap(n As Integer, gaps As Integer) Dim count = 0 While count < gaps Dim i = FirstNum(n) * 10 + LastNum(n)   REM Modulo with our new integer and output the result. If n Mod i = 0 Then Console.Write("{0} ", n) count += 1 End If   n += 1 End While Console.WriteLine() Console.WriteLine() End Sub   Sub Main() Console.WriteLine("The first 30 gapful numbers are: ") FindGap(100, 30)   Console.WriteLine("The first 15 gapful numbers > 1,000,000 are: ") FindGap(1000000, 15)   Console.WriteLine("The first 10 gapful numbers > 1,000,000,000 are: ") FindGap(1000000000, 10) End Sub   End Module
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Rust
Rust
  // using a Vec<f32> might be a better idea // for now, let us create a fixed size array // of size: const SIZE: usize = 6;   pub fn eliminate(mut system: [[f32; SIZE+1]; SIZE]) -> Option<Vec<f32>> { // produce the row reduced echelon form // // for every row... for i in 0..SIZE-1 { // for every column in that row... for j in i..SIZE-1 { if system[i][i] == 0f32 { continue; } else { // reduce every element under that element to 0 let factor = system[j + 1][i] as f32 / system[i][i] as f32; for k in i..SIZE+1 { // potential optimization: set every element to zero, instead of subtracting // i think subtraction helps showcase the process better system[j + 1][k] -= factor * system[i][k] as f32; } } } }   // produce gaussian eliminated array // // the process follows a similar pattern // but this one reduces the upper triangular // elements for i in (1..SIZE).rev() { if system[i][i] == 0f32 { continue; } else { for j in (1..i+1).rev() { let factor = system[j - 1][i] as f32 / system[i][i] as f32; for k in (0..SIZE+1).rev() { system[j - 1][k] -= factor * system[i][k] as f32; } } } }   // produce solutions through back substitution let mut solutions: Vec<f32> = vec![]; for i in 0..SIZE { if system[i][i] == 0f32 { return None; } else { system[i][SIZE] /= system[i][i] as f32; system[i][i] = 1f32; println!("X{} = {}", i + 1, system[i][SIZE]); solutions.push(system[i][SIZE]) } } return Some(solutions); }   #[cfg(test)] mod tests { use super::*; // sample run of the program #[test] fn eliminate_seven_by_six() { let system: [[f32; SIZE +1]; SIZE] = [ [1.00 , 0.00 , 0.00 , 0.00 , 0.00 , 0.00 , -0.01 ] , [1.00 , 0.63 , 0.39 , 0.25 , 0.16 , 0.10 , 0.61 ] , [1.00 , 1.26 , 1.58 , 1.98 , 2.49 , 3.13 , 0.91 ] , [1.00 , 1.88 , 3.55 , 6.70 , 12.62 , 23.80 , 0.99 ] , [1.00 , 2.51 , 6.32 , 15.88 , 39.90 , 100.28 , 0.60 ] , [1.00 , 3.14 , 9.87 , 31.01 , 97.41 , 306.02 , 0.02 ] ] ; let solutions = eliminate(system).unwrap(); assert_eq!(6, solutions.len()); let assert_solns = vec![-0.01, 1.60278, -1.61320, 1.24549, -0.49098, 0.06576]; for (ans, key) in solutions.iter().zip(assert_solns.iter()) { if (ans - key).abs() > 1E-4 { panic!("Test Failed!") } } } }  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Picat
Picat
main => Alpha1 = (0'a..0'z).map(chr), println(Alpha1), Alpha2 = [chr(I) : I in 97..122], println(Alpha2).
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PicoLisp
PicoLisp
(mapcar char (range (char "a") (char "z")))
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Plain_English
Plain English
\This prints Hello World within the CAL-4700 IDE. \...and backslashes are comments! To run: Start up. Write "Hello World!" to the console. Wait for the escape key. Shut down.
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#Wren
Wren
var powers = Fn.new { |m| var i = 0 return Fn.new { var p = i.pow(m) i = i + 1 return p } }   var squaresNotCubes = Fn.new { |squares, cubes| var sq = squares.call() var cu = cubes.call() return Fn.new { var p while (true) { if (sq < cu) { p = sq sq = squares.call() return p } if (sq == cu) sq = squares.call() cu = cubes.call() } } }   var squares = powers.call(2) var cubes = powers.call(3) var sqNotCu = squaresNotCubes.call(squares, cubes) for (i in 0..29) { var p = sqNotCu.call() if (i > 19) System.write("%(p) ") } System.print()
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Kotlin
Kotlin
// version 1.0.6   fun f(x: Int): Int = x * x   fun g(x: Int): Int = x + 2   fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { f(g(it)) }   fun main(args: Array<String>) { val x = 10 println(compose(::f, ::g)(x)) }
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Lambdatalk
Lambdatalk
  {def compose {lambda {:f :g :x} {:f {:g :x}}}} -> compose   {def funcA {lambda {:x} {* :x 10}}} -> funcA   {def funcB {lambda {:x} {+ :x 5}}} -> funcB   {def f {compose funcA funcB}} -> f   {{f} 3} -> 80  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de fractalTree (Img X Y A D) (unless (=0 D) (let (R (*/ A pi 180.0) DX (*/ (cos R) D 0.2) DY (*/ (sin R) D 0.2)) (brez Img X Y DX DY) (fractalTree Img (+ X DX) (+ Y DY) (+ A 30.0) (dec D)) (fractalTree Img (+ X DX) (+ Y DY) (- A 30.0) (dec D)) ) ) )   (let Img (make (do 300 (link (need 400 0)))) # Create image 400 x 300 (fractalTree Img 200 300 -90.0 10) # Draw tree (out "img.pbm" # Write to bitmap file (prinl "P1") (prinl 400 " " 300) (mapc prinl Img) ) )
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Plain_English
Plain English
To run: Start up. Clear the screen to the lightest blue color. Pick a brownish color. Put the screen's bottom minus 1/2 inch into the context's spot's y coord. Draw a tree given 3 inches. Refresh the screen. Wait for the escape key. Shut down.   To draw a tree given a size: If the size is less than 1/32 inch, exit. Put the size divided by 1/4 inch into the pen size. If the size is less than 1/4 inch, pick a greenish color. Remember where we are. Stroke the size. Turn left 1/16 of the way. Draw another tree given the size times 2/3. Turn right 1/16 of the way. Turn right 1/16 of the way. Draw a third tree given the size times 2/3. Turn left 1/16 of the way. Go back to where we were.
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#REXX
REXX
/*REXX pgm reduces fractions by "crossing out" matching digits in nominator&denominator.*/ parse arg high show . /*obtain optional arguments from the CL*/ if high=='' | high=="," then high= 4 /*Not specified? Then use the default.*/ if show=='' | show=="," then show= 12 /* " " " " " " */ say center(' some samples of reduced fractions by crossing out digits ', 79, "═") $.=0 /*placeholder array for counts; init. 0*/ do L=2 to high; say /*do 2-dig fractions to HIGH-dig fract.*/ lim= 10**L - 1 /*calculate the upper limit just once. */ do n=10**(L-1) to lim /*generate some N digit fractions. */ if pos(0, n) \==0 then iterate /*Does it have a zero? Then skip it.*/ if hasDup(n) then iterate /* " " " " dup? " " " */   do d=n+1 to lim /*only process like-sized #'s */ if pos(0, d)\==0 then iterate /*Have a zero? Then skip it. */ if verify(d, n, 'M')==0 then iterate /*No digs in common? Skip it.*/ if hasDup(d) then iterate /*Any digs are dups? " " */ q= n/d /*compute quotient just once. */ do e=1 for L; xo= substr(n, e, 1) /*try crossing out each digit.*/ nn= space( translate(n, , xo), 0) /*elide from the numerator. */ dd= space( translate(d, , xo), 0) /* " " " denominator. */ if nn/dd \== q then iterate /*Not the same quotient? Skip.*/ $.L= $.L + 1 /*Eureka! We found one. */ $.L.xo= $.L.xo + 1 /*count the silly reduction. */ if $.L>show then iterate /*Too many found? Don't show.*/ say center(n'/'d " = " nn'/'dd " by crossing out the" xo"'s.", 79) end /*e*/ end /*d*/ end /*n*/ end /*L*/ say; @with= ' with crossed-out' /* [↓] show counts for any reductions.*/ do k=1 for 9 /*traipse through each cross─out digit.*/ if $.k==0 then iterate /*Is this a zero count? Then skip it. */ say; say center('There are ' $.k " "k'-digit fractions.', 79, "═") @for= ' For ' /*literal for SAY indentation (below). */ do #=1 for 9; if $.k.#==0 then iterate say @for k"-digit fractions, there are " right($.k.#, k-1) @with #"'s." end /*#*/ end /*k*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ hasDup: parse arg x; /* if L<2 then return 0 */ /*L will never be 1.*/ do i=1 for L-1; if pos(substr(x,i,1), substr(x,i+1)) \== 0 then return 1 end /*i*/; return 0
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   class Fraction(val num: BigInteger, val denom: BigInteger) { operator fun times(n: BigInteger) = Fraction (n * num, denom)   fun isIntegral() = num % denom == BigInteger.ZERO }   fun String.toFraction(): Fraction { val split = this.split('/') return Fraction(BigInteger(split[0]), BigInteger(split[1])) }   val BigInteger.isPowerOfTwo get() = this.and(this - BigInteger.ONE) == BigInteger.ZERO   val log2 = Math.log(2.0)   fun fractran(program: String, n: Int, limit: Int, primesOnly: Boolean): List<Int> { val fractions = program.split(' ').map { it.toFraction() } val results = mutableListOf<Int>() if (!primesOnly) results.add(n) var nn = BigInteger.valueOf(n.toLong()) while (results.size < limit) { val frac = fractions.find { (it * nn).isIntegral() } ?: break nn = nn * frac.num / frac.denom if (!primesOnly) { results.add(nn.toInt()) } else if (primesOnly && nn.isPowerOfTwo) { val prime = (Math.log(nn.toDouble()) / log2).toInt() results.add(prime) } } return results }   fun main(args: Array<String>) { val program = "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" println("First twenty numbers:") println(fractran(program, 2, 20, false)) println("\nFirst twenty primes:") println(fractran(program, 2, 20, true)) }
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#BCPL
BCPL
let multiply(a, b) = a * b
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Ring
Ring
  # Project: Fusc sequence   max = 60 fusc = list(36000) fusc[1] = 1 see "working..." + nl see "wait for done..." + nl see "The first 61 fusc numbers are:" + nl fuscseq(max) see "0" for m = 1 to max see " " + fusc[m] next   see nl see "The fusc numbers whose length > any previous fusc number length are:" + nl see "Index Value" + nl see " 0 0" + nl d = 10 for i = 1 to 36000 if fusc[i] >= d see " " + i + " " + fusc[i] + nl if d = 0 d = 1 ok d = d*10 ok next see "done..." + nl   func fuscseq(max) for n = 2 to 36000 if n%2 = 1 fusc[n] = fusc[(n-1)/2] + fusc[(n+1)/2] but n%2 = 0 fusc[n] = fusc[n/2] ok next  
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Ruby
Ruby
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end   fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end   puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Gamma[x]
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Maxima
Maxima
fpprec: 30$   gamma_coeff(n) := block([a: makelist(1, n)], a[2]: bfloat(%gamma), for k from 3 thru n do a[k]: bfloat((sum((-1)^j * zeta(j) * a[k - j], j, 2, k - 1) - a[2] * a[k - 1]) / (1 - k * a[1])), a)$   poleval(a, x) := block([y: 0], for k from length(a) thru 1 step -1 do y: y * x + a[k], y)$   gc: gamma_coeff(20)$   gamma_approx(x) := block([y: 1], while x > 2 do (x: x - 1, y: y * x), y / (poleval(gc, x - 1)))$   gamma_approx(12.3b0) - gamma(12.3b0); /* -9.25224705314470500985141176997b-15 */
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Vlang
Vlang
fn commatize(n u64) string { mut s := n.str() le := s.len for i := le - 3; i >= 1; i -= 3 { s = '${s[0..i]},$s[i..]' } return s }   fn main() { starts := [u64(1e2), u64(1e6), u64(1e7), u64(1e9), u64(7123)] counts := [30, 15, 15, 10, 25] for i in 0..starts.len { mut count := 0 mut j := starts[i] mut pow := u64(100) for { if j < pow*10 { break } pow *= 10 } println("First ${counts[i]} gapful numbers starting at ${commatize(starts[i])}:") for count < counts[i] { fl := (j/pow)*10 + (j % 10) if j%fl == 0 { print("$j ") count++ } j++ if j >= 10*pow { pow *= 10 } } println("\n") } }
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Wren
Wren
import "/fmt" for Fmt   var starts = [1e2, 1e6, 1e7, 1e9, 7123] var counts = [30, 15, 15, 10, 25] for (i in 0...starts.count) { var count = 0 var j = starts[i] var pow = 100 while (true) { if (j < pow * 10) break pow = pow * 10 } System.print("First %(counts[i]) gapful numbers starting at %(Fmt.dc(0, starts[i]))") while (count < counts[i]) { var fl = (j/pow).floor*10 + (j % 10) if (j%fl == 0) { System.write("%(j) ") count = count + 1 } j = j + 1 if (j >= 10*pow) pow = pow * 10 } System.print("\n") }
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Sidef
Sidef
func gauss_jordan_solve (a, b) {   var A = gather { ^b -> each {|i| take(a[i] + b[i]) } }   rref(A).map{ .last } }   var a = [ [ 1.00, 0.00, 0.00, 0.00, 0.00, 0.00 ], [ 1.00, 0.63, 0.39, 0.25, 0.16, 0.10 ], [ 1.00, 1.26, 1.58, 1.98, 2.49, 3.13 ], [ 1.00, 1.88, 3.55, 6.70, 12.62, 23.80 ], [ 1.00, 2.51, 6.32, 15.88, 39.90, 100.28 ], [ 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 ], ]   var b = [ -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 ]   var G = gauss_jordan_solve(a, b) say G.map { "%27s" % .as_rat }.join("\n")
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PL.2FI
PL/I
gen: procedure options (main); /* 7 April 2014. */ declare 1 ascii union, 2 letters (26) character (1), 2 iletters(26) unsigned fixed binary (8), letter character(1); declare i fixed binary;   letters(1), letter = lowercase('A');   do i = 2 to 26; iletters(i) = iletters(i-1) + 1; end; put edit (letters) (a);   end gen;
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PL.2FM
PL/M
100H: /* PRINT THE LOWERCASE LETTERS */   /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END; /* CONSOLE OUTPUT ROUTINES */ PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;   /* TASK */ DECLARE C BYTE, LC ( 27 )BYTE; DO C = 0 TO 25; LC( C ) = C + 32 + 'A'; END; LC( LAST( LC ) ) = '$'; /* STRING TERMINATOR */ CALL PR$STRING( .LC );   EOF
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Plan
Plan
#STEER LIST,BINARY #PROGRAM HLWD #LOWER MSG1A 11HHELLO WORLD MSG1B 11/MSG1A #PROGRAM #ENTRY 0 DISTY MSG1B SUSWT 2HHH #END #FINISH #STOP
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#zkl
zkl
fcn powers(m){ n:=0.0; while(1){vm.yield(n.pow(m).toInt()); n+=1} } var squared=Utils.Generator(powers,2), cubed=Utils.Generator(powers,3);   fcn filtered(sg,cg){s:=sg.next(); c:=cg.next(); while(1){ if(s>c){c=cg.next(); continue;} else if(s<c) vm.yield(s); s=sg.next() } } var f=Utils.Generator(filtered,squared,cubed); f.drop(20); f.walk(10).println();
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#LFE
LFE
  (defun compose (f g) (lambda (x) (funcall f (funcall g x))))   (defun compose (funcs) (lists:foldl #'compose/2 (lambda (x) x) funcs))   (defun check () (let* ((sin-asin (compose #'math:sin/1 #'math:asin/1)) (expected (math:sin (math:asin 0.5))) (compose-result (funcall sin-asin 0.5))) (io:format '"Expected answer: ~p~n" (list expected)) (io:format '"Answer with compose: ~p~n" (list compose-result))))  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Lingo
Lingo
-- in some movie script ---------------------------------------- -- Composes 2 call-functions, returns a new call-function -- @param {symbol|instance} f -- @param {symbol|instance} g -- @return {instance} ---------------------------------------- on compose (f, g) return script("Composer").new(f, g) end
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#PostScript
PostScript
%!PS %%BoundingBox: 0 0 300 300 %%EndComments /origstate save def /ld {load def} bind def /m /moveto ld /g /setgray ld /t /translate ld /r /rotate ld /l /lineto ld /rl /rlineto ld /s /scale ld %%EndProlog /PerturbateAngle {} def /PerturbateLength {} def % ** To add perturbations, define properly PerturbateAngle and PerturbateLength, e.g. % /PerturbateAngle {realtime 20 mod realtime 2 mod 1 eq {add} {sub} ifelse} def % /PerturbateLength {realtime 10 mod 100 div realtime 2 mod 1 eq {add} {sub} ifelse} def /fractree { % [INITLENGTH, SPLIT, SFACTOR, BRANCHES] dup 3 get 0 gt { 0 0 m dup 0 get 0 exch l gsave dup 0 get 0 exch t dup 1 get PerturbateAngle r dup 2 get dup PerturbateLength s dup aload pop 1 sub 4 array astore fractree stroke grestore gsave dup 0 get 0 exch t dup 1 get neg PerturbateAngle r dup 2 get dup PerturbateLength s dup aload pop 1 sub 4 array astore fractree stroke grestore } if pop } def % /BRANCHES 14 def /INITLENGTH 50 def /SPLIT 35 def /SFACTOR .75 def % % BB check %0 0 m 300 0 rl 0 300 rl -300 0 rl closepath stroke % 0 g 150 0 t [INITLENGTH SPLIT SFACTOR BRANCHES] fractree stroke % showpage origstate restore %%EOF
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#POV-Ray
POV-Ray
#include "colors.inc" #include "transforms.inc"   #declare CamLoc = <0, 5, 0>; #declare CamLook = <0,0,0>; camera { location CamLoc look_at CamLook rotate y*90 }   light_source { CamLoc color White }   #declare Init_Height = 10; #declare Spread_Ang = 35; #declare Branches = 14; #declare Scaling_Factor = 0.75;   #macro Stick(P0, P1) cylinder { P0, P1, 0.02 texture { pigment { Green } } } #end   #macro FractalTree(O, D, S, R, B) #if (B > 0) Stick(O, O+D*S) FractalTree(O+D*S, vtransform(D, transform{rotate y*R}), S*Scaling_Factor, R, B-1) FractalTree(O+D*S, vtransform(D, transform{rotate -y*R}), S*Scaling_Factor, R, B-1) #end #end   union { FractalTree(<-2,0,0>, <1,0,0>, 1, Spread_Ang, Branches) }
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#Ruby
Ruby
def indexOf(haystack, needle) idx = 0 for straw in haystack if straw == needle then return idx else idx = idx + 1 end end return -1 end   def getDigits(n, le, digits) while n > 0 r = n % 10 if r == 0 or indexOf(digits, r) >= 0 then return false end le = le - 1 digits[le] = r n = (n / 10).floor end return true end   POWS = [1, 10, 100, 1000, 10000] def removeDigit(digits, le, idx) sum = 0 pow = POWS[le - 2] i = 0 while i < le if i == idx then i = i + 1 next end sum = sum + digits[i] * pow pow = (pow / 10).floor i = i + 1 end return sum end   def main lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ] count = Array.new(5, 0) omitted = Array.new(5) { Array.new(10, 0) }   i = 0 for lim in lims n = lim[0] while n < lim[1] nDigits = [0] * (i + 2) nOk = getDigits(n, i + 2, nDigits) if not nOk then n = n + 1 next end d = n + 1 while d <= lim[1] + 1 dDigits = [0] * (i + 2) dOk = getDigits(d, i + 2, dDigits) if not dOk then d = d + 1 next end nix = 0 while nix < nDigits.length digit = nDigits[nix] dix = indexOf(dDigits, digit) if dix >= 0 then rn = removeDigit(nDigits, i + 2, nix) rd = removeDigit(dDigits, i + 2, dix) if (1.0 * n / d) == (1.0 * rn / rd) then count[i] = count[i] + 1 omitted[i][digit] = omitted[i][digit] + 1 if count[i] <= 12 then print "%d/%d = %d/%d by omitting %d's\n" % [n, d, rn, rd, digit] end end end nix = nix + 1 end d = d + 1 end n = n + 1 end print "\n" i = i + 1 end   i = 2 while i <= 5 print "There are %d %d-digit fractions of which:\n" % [count[i - 2], i] j = 1 while j <= 9 if omitted[i - 2][j] == 0 then j = j + 1 next end print "%6s have %d's omitted\n" % [omitted[i - 2][j], j] j = j + 1 end print "\n" i = i + 1 end end   main()
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
fractionlist = {17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1}; n = 2; steplimit = 20; j = 0; break = False; While[break == False && j <= steplimit, newlist = n fractionlist; isintegerlist = IntegerQ[#] & /@ newlist; truepositions = Position[isintegerlist, True]; If[Length[truepositions] == 0, break = True, Print[ToString[j] <> ": " <> ToString[n]]; n = newlist[[truepositions[[1, 1]]]]; j++; ] ]
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#BlitzMax
BlitzMax
function multiply:float( a:float, b:float ) return a*b end function   print multiply(3.1416, 1.6180)
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Rust
Rust
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence = vec![0, 1]; let mut n = 0; std::iter::from_fn(move || { if n > 1 { sequence.push(match n % 2 { 0 => sequence[n / 2], _ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2], }); } let result = sequence[n]; n += 1; Some(result) }) }   fn main() { println!("First 61 fusc numbers:"); for n in fusc_sequence().take(61) { print!("{} ", n) } println!();   let limit = 1000000000; println!( "Fusc numbers up to {} that are longer than any previous one:", limit ); let mut max = 0; for (index, n) in fusc_sequence().take(limit).enumerate() { if n >= max { max = std::cmp::max(10, max * 10); println!("index = {}, fusc number = {}", index, n); } } }
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Sidef
Sidef
func fusc(n) is cached {   return 0 if n.is_zero return 1 if n.is_one   n.is_even ? fusc(n/2) : (fusc((n-1)/2) + fusc(((n-1)/2)+1)) }   say ("First 61 terms of the Stern-Brocot sequence: ", 61.of(fusc).join(' '))   say "\nIndex and value for first term longer than any previous:" printf("%15s : %s\n", "Index", "Value");   var (index=0, len=0)   5.times { index = (index..Inf -> first_by { fusc(_).len > len }) len = fusc(index).len printf("%15s : %s\n", index.commify, fusc(index).commify) }
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#.D0.9C.D0.9A-61.2F52
МК-61/52
П9 9 П0 ИП9 ИП9 1 + * Вx L0 05 1 + П9 ^ ln 1 - * ИП9 1 2 * 1/x + e^x <-> / 2 пи * ИП9 / КвКор * ^ ВП 3 + Вx - С/П
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Modula-3
Modula-3
MODULE Gamma EXPORTS Main;   FROM IO IMPORT Put; FROM Fmt IMPORT Extended, Style;   PROCEDURE Taylor(x: EXTENDED): EXTENDED = CONST a = ARRAY [0..29] OF EXTENDED { 1.00000000000000000000X0, 0.57721566490153286061X0, -0.65587807152025388108X0, -0.04200263503409523553X0, 0.16653861138229148950X0, -0.04219773455554433675X0, -0.00962197152787697356X0, 0.00721894324666309954X0, -0.00116516759185906511X0, -0.00021524167411495097X0, 0.00012805028238811619X0, -0.00002013485478078824X0, -0.00000125049348214267X0, 0.00000113302723198170X0, -0.00000020563384169776X0, 0.00000000611609510448X0, 0.00000000500200764447X0, -0.00000000118127457049X0, 0.00000000010434267117X0, 0.00000000000778226344X0, -0.00000000000369680562X0, 0.00000000000051003703X0, -0.00000000000002058326X0, -0.00000000000000534812X0, 0.00000000000000122678X0, -0.00000000000000011813X0, 0.00000000000000000119X0, 0.00000000000000000141X0, -0.00000000000000000023X0, 0.00000000000000000002X0 }; VAR y := x - 1.0X0; sum := a[LAST(a)];   BEGIN FOR i := LAST(a) - 1 TO FIRST(a) BY -1 DO sum := sum * y + a[i]; END; RETURN 1.0X0 / sum; END Taylor;   BEGIN FOR i := 1 TO 10 DO Put(Extended(Taylor(FLOAT(i, EXTENDED) / 3.0X0), style := Style.Sci) & "\n"); END; END Gamma.
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#XBS
XBS
func isgapful(n:number):boolean{ set s:string = tostring(n); set d = toint(`{s::at(0)}{s::at(?s-1)}`); send (n%d)==0 }   func findGapfulNumbers(start,amount){ set gapful=[]; set ind = start; while(true){ if(isgapful(ind)){ gapful::insert(ind); } ind++; if((?gapful)>=amount){ stop; } } log(`First {amount} gapful ints at {start}: {gapful::join(", ")}`); }   findGapfulNumbers(100,30); findGapfulNumbers(1000000,15); findGapfulNumbers(1000000000,15);
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#XPL0
XPL0
func Gapful(N0); \Return 'true' if gapful number int N0, N, First, Last; [N:= N0; N:= N/10; Last:= rem(0); repeat N:= N/10; First:= rem(0); until N = 0; N:= First*10 + Last; return rem(N0/N) = 0; ];   proc ShowGap(Start, Limit); \Display gapful numbers int Start, Limit, Count, N; [Text(0, "First "); IntOut(0, Limit); Text(0, " gapful numbers starting from "); IntOut(0, Start); Text(0, ":^m^j"); Count:= 0; N:= Start; loop [if Gapful(N) then [IntOut(0, N); ChOut(0, ^ ); Count:= Count+1; if Count >= Limit then quit; ]; N:= N+1; ]; CrLf(0); ];   [ShowGap(100, 30); ShowGap(1_000_000, 15); ShowGap(1_000_000_000, 10); ]
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Stata
Stata
void gauss(real matrix a, real matrix b, real scalar det) { real scalar i,j,n,s real vector js   det = 1 n = rows(a) for (i=1; i<n; i++) { maxindex(abs(a[i::n,i]), 1, js=., .) j = js[1]+i-1 if (j!=i) { a[(i\j),i..n] = a[(j\i),i..n] b[(i\j),.] = b[(j\i),.] det = -det } for (j=i+1; j<=n; j++) { s = a[j,i]/a[i,i] a[j,i+1..n] = a[j,i+1..n]-s*a[i,i+1..n] b[j,.] = b[j,.]-s*b[i,.] } }   for (i=n; i>=1; i--) { for (j=i+1; j<=n; j++) { b[i,.] = b[i,.]-a[i,j]*b[j,.] } b[i,.] = b[i,.]/a[i,i] det = det*a[i,i] } }
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PL.2FSQL
PL/SQL
Declare sbAlphabet varchar2(100); Begin For nuI in 97..122 loop if sbAlphabet is null then sbAlphabet:=chr(nuI); Else sbAlphabet:=sbAlphabet||','||chr(nuI); End if; End loop; Dbms_Output.Put_Line(sbAlphabet); End;
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Plain_English
Plain English
To run: Start up. Generate the lowercase ASCII alphabet giving a string. Write the string on the console. Wait for the escape key. Shut down.   To generate the lowercase ASCII alphabet giving a string: Put the little-a byte into a letter. Loop. Append the letter to the string. If the letter is the little-z byte, exit. Add 1 to the letter. Repeat.
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Pony
Pony
actor Main new create(env: Env) => env.out.print("Hello world!")
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#LOLCODE
LOLCODE
HAI 1.3   I HAS A fx, I HAS A gx   HOW IZ I composin YR f AN YR g fx R f, gx R g HOW IZ I composed YR x FOUND YR I IZ fx YR I IZ gx YR x MKAY MKAY IF U SAY SO FOUND YR composed IF U SAY SO   HOW IZ I incin YR num FOUND YR SUM OF num AN 1 IF U SAY SO   HOW IZ I sqrin YR num FOUND YR PRODUKT OF num AN num IF U SAY SO   I HAS A incsqrin ITZ I IZ composin YR incin AN YR sqrin MKAY VISIBLE I IZ incsqrin YR 10 MKAY BTW, prints 101   I HAS A sqrincin ITZ I IZ composin YR sqrin AN YR incin MKAY VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121   KTHXBYE
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Lua
Lua
function compose(f, g) return function(...) return f(g(...)) end end
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Prolog
Prolog
fractal :- new(D, window('Fractal')), send(D, size, size(800, 600)), drawTree(D, 400, 500, -90, 9), send(D, open).     drawTree(_D, _X, _Y, _Angle, 0).   drawTree(D, X1, Y1, Angle, Depth) :- X2 is X1 + cos(Angle * pi / 180.0) * Depth * 10.0, Y2 is Y1 + sin(Angle * pi / 180.0) * Depth * 10.0, new(Line, line(X1, Y1, X2, Y2, none)), send(D, display, Line), A1 is Angle - 30, A2 is Angle + 30, De is Depth - 1, drawTree(D, X2, Y2, A1, De), drawTree(D, X2, Y2, A2, De).    
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function IndexOf(n As Integer, s As Integer()) As Integer For ii = 1 To s.Length Dim i = ii - 1 If s(i) = n Then Return i End If Next Return -1 End Function   Function GetDigits(n As Integer, le As Integer, digits As Integer()) As Boolean While n > 0 Dim r = n Mod 10 If r = 0 OrElse IndexOf(r, digits) >= 0 Then Return False End If le -= 1 digits(le) = r n \= 10 End While Return True End Function   Function RemoveDigit(digits As Integer(), le As Integer, idx As Integer) As Integer Dim pows = {1, 10, 100, 1000, 10000} Dim sum = 0 Dim pow = pows(le - 2) For ii = 1 To le Dim i = ii - 1 If i = idx Then Continue For End If sum += digits(i) * pow pow \= 10 Next Return sum End Function   Sub Main() Dim lims = {{12, 97}, {123, 986}, {1234, 9875}, {12345, 98764}} Dim count(5) As Integer Dim omitted(5, 10) As Integer Dim upperBound = lims.GetLength(0) For ii = 1 To upperBound Dim i = ii - 1 Dim nDigits(i + 2 - 1) As Integer Dim dDigits(i + 2 - 1) As Integer Dim blank(i + 2 - 1) As Integer For n = lims(i, 0) To lims(i, 1) blank.CopyTo(nDigits, 0) Dim nOk = GetDigits(n, i + 2, nDigits) If Not nOk Then Continue For End If For d = n + 1 To lims(i, 1) + 1 blank.CopyTo(dDigits, 0) Dim dOk = GetDigits(d, i + 2, dDigits) If Not dOk Then Continue For End If For nixt = 1 To nDigits.Length Dim nix = nixt - 1 Dim digit = nDigits(nix) Dim dix = IndexOf(digit, dDigits) If dix >= 0 Then Dim rn = RemoveDigit(nDigits, i + 2, nix) Dim rd = RemoveDigit(dDigits, i + 2, dix) If (n / d) = (rn / rd) Then count(i) += 1 omitted(i, digit) += 1 If count(i) <= 12 Then Console.WriteLine("{0}/{1} = {2}/{3} by omitting {4}'s", n, d, rn, rd, digit) End If End If End If Next Next Next Console.WriteLine() Next   For i = 2 To 5 Console.WriteLine("There are {0} {1}-digit fractions of which:", count(i - 2), i) For j = 1 To 9 If omitted(i - 2, j) = 0 Then Continue For End If Console.WriteLine("{0,6} have {1}'s omitted", omitted(i - 2, j), j) Next Console.WriteLine() Next End Sub   End Module
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Nim
Nim
  import strutils import bignum   const PrimeProg = "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"   iterator values(prog: openArray[Rat]; init: Natural): Int = ## Run the program "prog" with initial value "init" and yield the values. var n = newInt(init) var next: Rat while true: for fraction in prog: next = n * fraction if next.denom == 1: break n = next.num yield n   func toFractions(fractList: string): seq[Rat] = ## Convert a string to a list of fractions. for f in fractList.split(): result.add(newRat(f))   proc run(progStr: string; init, maxSteps: Natural = 0) = ## Run the program described by string "progStr" with initial value "init", ## stopping after "maxSteps" (0 means for ever). ## Display the value after each step. let prog = progStr.toFractions() var stepCount = 0 for val in prog.values(init): inc stepCount echo stepCount, ": ", val if stepCount == maxSteps: break   iterator primes(n: Natural): int = # Yield the list of first "n" primes. let prog = PrimeProg.toFractions() var count = 0 for val in prog.values(2): if isZero(val and (val - 1)): # This is a power of two. yield val.digits(2) - 1 # Compute the exponent as number of binary digits minus one. inc count if count == n: break   # Run the program to compute primes displaying values at each step and stopping after 10 steps. echo "First ten steps for program to find primes:" PrimeProg.run(2, 10)   # Find the first 20 primes. echo "\nFirst twenty prime numbers:" for val in primes(20): echo val  
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Boo
Boo
def multiply(x as int, y as int): return x * y   print multiply(3, 2)
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Swift
Swift
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0   mutating func next() -> Int? { defer { i += 1 }   guard i > 1 else { return arr[i] }   switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2]) case _: fatalError() }   return arr.last! } }   let first = FuscSeq().prefix(61)   print("First 61: \(Array(first))")   var max = -1   for (i, n) in FuscSeq().prefix(20_000_000).enumerated() { let f = String(n).count   if f > max { max = f   print("New max: \(i): \(n)") } }
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Tcl
Tcl
proc fusc n { if {$n < 2} { return $n }   if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) }   if {$n % 2} { ;# n is odd set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ;# n is even set r [fusc [expr {$n/2}]] }   if {$n < 999999} { set ::g_fusc($n) $r }   return $r }   proc ,,, {str {sep ,} {grouplen 3}} { set strlen [string length $str] set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}] set r [regsub -all ... [string repeat " " $padlen]$str &$sep] return [string range $r $padlen end-[string length $sep]] }   proc tabline {a b c} { puts "[format %2s $a] [format %10s $b] [format %8s $c]" }   proc doit {{nmax 20000000}} { for {set i 0} {$i < 61} {incr i} { puts -nonewline " [fusc $i]" } puts "" tabline L n fusc(n) set maxL 0 for {set n 0} {$n < $nmax} {incr n} { set f [fusc $n] set L [string length $f] if {$L > $maxL} { set maxL $L tabline $L [,,, $n] [,,, $f] } } } doit
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Nim
Nim
import math, strformat   const A = [ 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675, -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511, -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824, -0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776, 0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049, 0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562, 0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812, 0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119, 0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002 ]   proc gamma(x: float): float = let y = x - 1 result = A[^1] for n in countdown(A.high - 1, A.low): result = result * y + A[n] result = 1 / result   echo "Our gamma function Nim gamma function Difference" echo "------------------ ------------------ ----------" for i in 1..10: let val1 = gamma(i.toFloat / 3) let val2 = math.gamma(i.toFloat / 3) echo &"{val1:18.16f} {val2:18.16f} {val1 - val2:11.4e}"
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Yabasic
Yabasic
sub is_gapful(n) m = n l = mod(n, 10) while (m >= 10) m = int(m / 10) wend return (m * 10) + l end sub   sub muestra_gapful(n, gaps) inc = 0 print "Primeros ", gaps, " numeros gapful >= ", n while inc < gaps if mod(n, is_gapful(n)) = 0 then print " " , n , inc = inc + 1 end if n = n + 1 wend print chr$(10) end sub   muestra_gapful(100, 30) muestra_gapful(1000000, 15) muestra_gapful(1000000000, 10) muestra_gapful(7123,25) end
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#zkl
zkl
fcn gapfulW(start){ //--> iterator [start..].tweak( fcn(n){ if(n % (10*n.toString()[0] + n%10)) Void.Skip else n }) }
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Swift
Swift
func gaussEliminate(_ sys: [[Double]]) -> [Double]? { var system = sys   let size = system.count   for i in 0..<size-1 where system[i][i] != 0 { for j in i..<size-1 { let factor = system[j + 1][i] / system[i][i]   for k in i..<size+1 { system[j + 1][k] -= factor * system[i][k] } } }   for i in (1..<size).reversed() where system[i][i] != 0 { for j in (1..<i+1).reversed() { let factor = system[j - 1][i] / system[i][i]   for k in (0..<size+1).reversed() { system[j - 1][k] -= factor * system[i][k] } } }   var solutions = [Double]()   for i in 0..<size { guard system[i][i] != 0 else { return nil }   system[i][size] /= system[i][i] system[i][i] = 1 solutions.append(system[i][size]) }   return solutions }   let sys = [ [1.00, 0.00, 0.00, 0.00, 0.00, 0.00, -0.01], [1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 0.61], [1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 0.91], [1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 0.99], [1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 0.60], [1.00, 3.14, 9.87, 31.01, 97.41, 306.02, 0.02] ]   guard let sols = gaussEliminate(sys) else { fatalError("No solutions") }   for (i, f) in sols.enumerated() { print("X\(i + 1) = \(f)") }