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/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Arturo
Arturo
digits: function [n][ res: new [] while -> n > 0 [ 'res ++ n % 10 n: n / 10 ] res ]   luhn?: function [n][ s1: new 0 s2: new 0 loop.with: 'i digits n 'd [ if? even? i -> 's1 + d else [ 'd * 2 if d > 9 -> 'd - 9 's2 + d ...
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Common_Lisp
Common Lisp
  (defun or-f (&optional a b) (or a b));necessary for reduce, as 'or' is implemented as a macro   (defun prime-p (n) (cond ((< n 4) (>= n 2)) ((zerop (rem n 2)) nil) (t (not (reduce #'or-f (mapcar (lambda (x) (zerop (rem n x))) (loop for i from 3 to (sqrt n) collect i)))))))   (defun mersenne-p (p) ...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#REXX
REXX
/*REXX program displays lucky or evenLucky integers (numbers or a number range).*/ parse arg bot top func _ . /*obtain required & optional arguments.*/ if func=='' then func= 'lucky' /*Not specified? Then use the default.*/ s= left('s', bot\==top & top\==",") ...
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Forth
Forth
256 value next-symbol   \ current string fragment   create w 256 allot \ counted string   : w=c ( c -- ) w 1+ c! 1 w c! ; : w+c ( c -- ) w count + c! w c@ 1+ w c! ;   \ Compression   \ dictionary of strings to symbols 0 value dict   : init-dict table to dict 256 to next-symbol dict set-current ;  ...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#jq
jq
# Create an m x n matrix def matrix(m; n; init): if m == 0 then [] elif m == 1 then [range(0;n)] | map(init) elif m > 0 then matrix(1;n;init) as $row | [range(0;m)] | map( $row ) else error("matrix\(m);_;_) invalid") end ;   def I(n): matrix(n;n;0) as $m | reduce range(0;n) as $i ($m; . | setpath( [...
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Picat
Picat
go => Limit = 500, Lychrel = [], Cache = new_set(), % caching the found Lychrel numbers Seeds = [], Palindromes = [], foreach(N in 1..10_000) if lychrel(N,Cache,Limit,Seed) then Lychrel := Lychrel ++ [N], if Seed then Seeds := Seeds ++ [N] end, if rev(N) == N then Palindromes := Palind...
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
text = Import[ InputString["Enter the filename of the story template:"]]; answers = AssociationMap[ InputString[ "Enter a" <> If[StringMatchQ[#, "<" ~~ Alternatives @@ Characters["aeiou"] ~~ ___], "n", ""] <> " " <> StringTrim[#, "<" | ">"] <> ":"] &, Union[StringCases[text, Reg...
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Arturo
Arturo
i: 42 n: 0   while [n<42][ if? prime? i [ n: n+1 print ["n =" pad to :string n 2 pad to :string i 20] i: i + i ] else [ i: i + 1 ] ]
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#AutoHotkey
AutoHotkey
i:= 42, n:= 1, result := "" while (n<43){ if isPrime(i) result .= n ":`t" RegExReplace(i, "\B(?=(\d{3})+$)", ",") "`n", i*=2, n++ else i++ } MsgBox, 262208, , % result return   isPrime(num){ if !Mod(num, 2) || !Mod(num, 3) return false lim := Sqrt(num), i := 5 while (i<lim){ if !Mod(num, i) return fal...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ACL2
ACL2
(defun spam () (declare (xargs :mode :program)) (if nil nil (prog2$ (cw "SPAM~%") (spam))))
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#Delphi
Delphi
  program with_multiple_ranges;   {$APPTYPE CONSOLE}   uses System.SysUtils;   var prod: Int64 = 1; sum: Int64 = 0;   function labs(value: Int64): Int64; begin Result := value; if value < 0 then Result := -Result; end;   procedure process(j: Int64); begin sum := sum + (abs(j)); if (labs(prod) < (1 shl...
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#ALGOL_68
ALGOL 68
INT i := 1024; WHILE i > 0 DO print(i); i := i OVER 2 OD
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#11l
11l
L(i) 1..5 L 1..i print(‘*’, end' ‘’) print()
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#6502_Assembly
6502 Assembly
define ArrayPointerLo $00  ;define some helpful labels. define ArrayPointerHi $01 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; setArray:  ;Easy6502 doesn't let us define arbitrary bytes so the best option is to fill the range at runtime. lda #$10 ldx #0 loop_setArray: sta $1200,x clc adc #$10 inx cpx #$08 bcc loop_setArr...
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Nim
Nim
import strutils   type LudicArray[N: static int] = array[1..N, int]   func initLudicArray[N: static int](): LudicArray[N] = ## Initialize an array of ludic numbers. result[1] = 1 for i in 2..N: var k = 0 for j in countdown(i - 1, 2): k = k * result[j] div (result[j] - 1) + 1 result[i] = k + 2   ...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#Action.21
Action!
PROC Main() BYTE i=[1]   DO PrintB(i) IF i=10 THEN EXIT FI Print(", ") i==+1 OD RETURN
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#Ada
Ada
with Ada.Text_IO;   procedure LoopsAndHalf is begin for i in 1 .. 10 loop Ada.Text_IO.put (i'Img); exit when i = 10; Ada.Text_IO.put (","); end loop; Ada.Text_IO.new_line; end LoopsAndHalf;
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#ALGOL_60
ALGOL 60
'BEGIN' 'COMMENT' Loops/Nested - ALGOL60 - 19/06/2018; 'INTEGER' SEED; 'INTEGER' 'PROCEDURE' RANDOM(N); 'VALUE' N; 'INTEGER' N; 'BEGIN' SEED:=(SEED*19157+12347) '/' 21647; RANDOM:=SEED-(SEED '/' N)*N+1 'END' RANDOM; 'INTEGER' 'ARRAY' A(/1:10,1:10/); 'INTEGER' I,J; SEED:=31569; 'FOR' I:=1 'STEP...
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#ALGOL_68
ALGOL 68
main: ( [10][10]INT a; INT i, j;   FOR i FROM LWB a TO UPB a DO FOR j FROM LWB a[i] TO UPB a[i] DO a[i][j] := ENTIER (random * 20 + 1) OD OD ; FOR i FROM LWB a TO UPB a DO FOR j FROM LWB a[i] TO UPB a[i] DO print(whole(a[i][j], -3)); IF a[i][j]...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#langur
langur
val .data = q:block END start stop increment comment -2 2 1 Normal -2 2 0 Zero increment -2 2 -1 Increments away from stop value -2 2 10 First increment is beyond stop value 2 ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Maple
Maple
# Normal seq(-2..2, 1);   # Zero increment seq(-2..2, 0);   # Increments away from stop value seq(-2..2, -1);   # First increment is beyond stop value seq(-2..2, 10);   # Start more than stop: positive increment seq(2..-2, 1);   # Start equal stop: positive increment seq(2..2, 1);   # Start equal stop: negative increme...
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Aime
Aime
# iterate over a list of integers integer i, v;   for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) { }
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#ALGOL_68
ALGOL 68
[]UNION(STRING, INT, PROC(REF FILE)VOID) collection = ("Mary","Had",1,"little","lamb.",new line);   FOR index FROM LWB collection TO UPB collection DO print((collection[index]," ")) OD
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#AutoHotkey
AutoHotkey
; Originally submitted by Laszlo: ; http://www.autohotkey.com/forum/post-229412.html#229412   MsgBox % LuhnTest(49927398716) MsgBox % LuhnTest(49927398717) MsgBox % LuhnTest(1234567812345678) MsgBox % LuhnTest(1234567812345670)   Return   ;-----------------------------   LuhnTest(Number) { MultFactor := 2 - ( StrLen(...
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Crystal
Crystal
require "big"   def is_prime(n) # P3 Prime Generator primality test return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true return false if n.gcd(6) != 1 # for n a P3 prime candidate (pc) pc1, pc2 = -1, 1 # use P3's prime candidates sequence ...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#Ring
Ring
  # Project : Lucky and even lucky numbers   lucky = list(50) dellucky = [] for n = 1 to 50 lucky[n] = 2*n-1 next see "the first 20 lucky numbers:" + nl luckynumbers(lucky) showarray(lucky) see nl   lucky = list(50) dellucky = [] for n = 1 to 50 lucky[n] = 2*n next see "the first 20 even lucky numbers:" +...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#Ruby
Ruby
def generator(even=false, nmax=1000000) start = even ? 2 : 1 Enumerator.new do |y| n = 1 ary = [0] + (start..nmax).step(2).to_a # adds [0] to revise the 0 beginnings. y << ary[n] while (m = ary[n+=1]) < ary.size y << m (m...ary.size).step(m){|i| ary[i]=nil} ary.compact! ...
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Fortran
Fortran
  ! ! lzw_shared_parameters.f90 ! ! LZW Common Variables Used by Coder and Decoder ! ! Author: Pedro Garcia Freitas <sawp@sawp.com.br> ! May, 2011 ! ! License: Creative Commons http://creativecommons.org/licenses/by-nc-nd/3.0/ ! MODULE LZW_SHARED_PARAMETERS IMPLICIT NONE ! ! PARAMETER definitions ! IN...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#Julia
Julia
julia> using LinearAlgebra; lu([1 3 5 ; 2 4 7 ; 1 1 0]) ( 3x3 Array{Float64,2}: 1.0 0.0 0.0 0.5 1.0 0.0 0.5 -1.0 1.0, 3x3 Array{Float64,2}: 2.0 4.0 7.0 0.0 1.0 1.5 0.0 0.0 -2.0, [2,1,3])
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#PicoLisp
PicoLisp
(de pali? (N) (let N (chop N) (= N (reverse N)) ) ) (de lychrel (A) (let (R NIL Lst (make (for X A (let (N X C 500) (while (and (inc 'N (format (flip (chop N)))) (gt0...
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another...
#Nanoquery
Nanoquery
def madlib(template) // loop through and find/remove all of the replacements replacements = {} ind = 0 while ind < len(template) // check if we have found a replacement to perform if template[ind] = "<" // get the name of the replacement and add it to the list // ...
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#AWK
AWK
  # syntax: GAWK -f LOOPS_INCREMENT_LOOP_INDEX_WITHIN_LOOP_BODY.AWK BEGIN { limit = 42 n = 0 for (i=limit; n<limit; i++) { if (is_prime(i)) { printf("%2d %19'd\n",++n,i) i += i - 1 } } exit(0) } function is_prime(n, d) { if (n % 2 == 0) { return(n == 2) } if (n %...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Action.21
Action!
PROC Main() DO PrintE("SPAM") OD RETURN
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ActionScript
ActionScript
while (true) { trace("SPAM"); }
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#EasyLang
EasyLang
prod = 1 sum = 0 x = 5 y = -5 z = -2 one = 1 three = 3 seven = 7 ranges[][] = [ [ -three (pow 3 3) three ] [ -seven seven x ] [ 555 (550 - y) ] [ 22 -28 (-three) ] [ 1927 1939 ] [ x y z ] [ (pow 11 x) (pow 11 x + one) ] ] # for i range len ranges[][] j = ranges[i][0] to = ranges[i][1] inc = 1 if len ranges[i][...
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   prod, sum, x, y, z, one, three, seven: INTEGER   make local process: PROCEDURE do prod := 1; x := 5; y := -5; z := -2; one := 1; three := 3; seven := 7 process := (agent (j: INTEGER) do print (j.out + ", ") sum := sum + j.abs ...
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#ALGOL_W
ALGOL W
begin integer i; i := 1024; while i > 0 do begin write( i ); i := i div 2 end end.
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#ALGOL-M
ALGOL-M
begin integer i; i := 1024; while i > 0 do begin write( i ); i := i / 2; end; end
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#360_Assembly
360 Assembly
  * Loops/For - BXH Algol 27/07/2015 LOOPFOR CSECT USING LOOPFORC,R12 LR R12,R15 set base register BEGIN LA R2,0 from 1 (from-step=0) LA R4,1 step 1 LA R5,5 to 5 LOOPI BXH R2,R4,ELOOPI fo...
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loopstep64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Objeck
Objeck
use Collection.Generic;   class Ludic { function : Main(args : String[]) ~ Nil { ludics := LudicUpTo(110); Show("First 25 Ludics: ", ludics, 0, ludics->Size()); System.IO.Console->Print("Ludics up to 1000: ")->PrintLine(LudicUpTo(1000)->Size()); ludics := LudicUpTo(22000); Show("2000th - 2005th L...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#Aime
Aime
integer i;   i = 0; while (1) { i += 1; o_integer(i); if (i == 10) { break; } o_text(", "); } o_text("\n");
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#ALGOL_60
ALGOL 60
'BEGIN' 'COMMENT' Loops N plus one half - Algol60 - 20/06/2018; 'INTEGER' I; 'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN' OUTINTEGER(1,I); 'IF' I 'NOTEQUAL' 10 'THEN' OUTSTRING(1,'(', ')') 'END' 'END'
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#AppleScript
AppleScript
on loopDemo(array, stopVal) set out to {} repeat with i from 1 to (count array) set inRow to item i of array set outRow to {} repeat with j from 1 to (count inRow) set n to item j of inRow set end of outRow to n if (n = stopVal) then exit repeat # <-- ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Table[i, {i, -2, 2, 1}] Table[i, {i, -2, 2, 0}] Table[i, {i, -2, 2, -1}] Table[i, {i, -2, 2, 10}] Table[i, {i, 2, -2, 1}] Table[i, {i, 2, 2, 1}] Table[i, {i, 2, 2, -1}] Table[i, {i, 2, 2, 0}] Table[i, {i, 0, 0, 0}]
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Nim
Nim
import sequtils, strformat   proc displayRange(first, last, step: int) =   stdout.write &"({first:>2}, {last:>2}, {step:>2}): "   echo if step > 0: ($toSeq(countup(first, last, step)))[1..^1] elif step < 0: ($toSeq(countdown(first, last, -step)))[1..^1] else: "not allowed."   for (f, l, s) in [(-2, ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Perl
Perl
for $i ( [ -2, 2, 1], #1 Normal [ -2, 2, 0], #2 Zero increment [ -2, 2, -1], #3 Increments away from stop value [ -2, 2, 10], #4 First increment is beyond stop value [ 2, -2, 1], #5 Start more than stop: positive increment [ 2, 2, 1], #6 Start equal stop:...
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#AmigaE
AmigaE
PROC main() DEF a_list : PTR TO LONG, a a_list := [10, 12, 14] FOR a := 0 TO ListLen(a_list)-1 WriteF('\d\n', a_list[a]) ENDFOR -> if the "action" fits a single statement, we can do instead ForAll({a}, a_list, `WriteF('\d\n', a)) ENDPROC
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Apex
Apex
  Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};   for (Integer i : myInts) { System.debug(i); }  
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#AutoIt
AutoIt
  Global $avarray[4] = [49927398716, 49927398717, 1234567812345678, 1234567812345670] For $i = 0 To 3 checkLuhn($avarray[$i]) Next   Func checkLuhn($number) $sum = 0 $numDigits = StringSplit($number, "") For $i = $numDigits[0] - 1 To 1 Step -2 $numDigits[$i] = $numDigits[$i] * 2 If $numDigits[$i] >= 10 Then $nu...
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#D
D
import std.stdio, std.math, std.bigint;   bool isPrime(in uint p) pure nothrow @safe @nogc { if (p < 2 || p % 2 == 0) return p == 2; foreach (immutable i; 3 .. cast(uint)real(p).sqrt + 1) if (p % i == 0) return false; return true; }   bool isMersennePrime(in uint p) pure nothrow ...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#Swift
Swift
struct LuckyNumbers : Sequence, IteratorProtocol { let even: Bool let through: Int   private var drainI = 0 private var n = 0 private var lst: [Int]   init(even: Bool = false, through: Int = 1_000_000) { self.even = even self.through = through self.lst = Array(stride(from: even ? 2 : 1, through:...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#Tcl
Tcl
#!/usr/bin/env tclsh8.6 package require Tcl 8.6   proc lgen {{even false} {nmax 200000}} { coroutine lgen.[incr ::lgen] apply {{start nmax} { set n 1 for {set i $start} {$i <= $nmax+1} {incr i 2} {lappend lst $i} yield [info coroutine] yield [lindex $lst 0] while {$n < [llength $lst] && [lindex $lst $n] < [lle...
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#FreeBASIC
FreeBASIC
' version 22-02-2019 ' compile with: fbc -s console   Type dict prefix As Integer B As String End Type   Sub init(dictionary() As dict, ByRef last As ULong)   For i As ULong = 0 To 255 dictionary(i).prefix = -1 dictionary(i).B = Chr(i) Next last = 255   End Sub   Function encod...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#Kotlin
Kotlin
// version 1.1.4-3   typealias Vector = DoubleArray typealias Matrix = Array<Vector>   operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(co...
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#PowerShell
PowerShell
  function Test-Palindrome ( [String]$String ) { # Default value $IsPalindrome = $True   # For each position in the string from the start to the middle ForEach ( $Index in ( 0..($String.Length -shr 1 ) ) ) { # Check if the character at this position matches the corresponding chara...
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another...
#Nim
Nim
import rdstdin, re, algorithm, sequtils, strutils   #let templ = readLineFromStdin "Enter your story: " const templ = """<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."""   echo "The story template is:\n", templ var fields = templ.findAll re"<[^>]+>" fields.sort(cmp) fie...
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#BASIC256
BASIC256
function isPrime(number) if (number % 2 = 0) or (number % 3 = 0) then return false lim = sqr(number)   for i = 5 to lim step 2 if number % i = 0 then return false next i   return true end function   i = 42 counter = 0 while counter < 42 if isPrime(i) then counter += 1 print "n = "; counter, i i += i - 1 ...
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#C
C
#include <stdio.h> #include <locale.h>   #define LIMIT 42   int is_prime(long long n) { if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; long long d = 5; while (d * d <= n) { if (n % d == 0) return 0; d += 2; if (n % d == 0) return 0; d += 4; } return...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Ada
Ada
loop Put_Line("SPAM"); end loop;
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Agena
Agena
do print( "SPAM" ) od
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#F.23
F#
  // Loops/With multiple ranges. Nigel Galloway: June 13th., 2022 let x,y,z,one,three,seven=5,-5,-2,1,3,7 let Range=[-three..three..pown 3 3]@[-7..x..seven]@[555..550-y]@[22..-three.. -28]@[1927..1939]@[x..z..y]@[pown 11 x..(pown 11 x)+1] printfn "Sum=%d Product=%d" (Range|>Seq.sumBy(abs)) (Range|>Seq.filter((<>)0)|>Se...
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#AmbientTalk
AmbientTalk
// print 1024 512 etc def i := 1024; while: { i > 0 } do: { system.print(" "+i); i := i/2; }
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#AmigaE
AmigaE
PROC main() DEF i = 1024 WHILE i > 0 WriteF('\d\n', i) i := i / 2 ENDWHILE ENDPROC
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#68000_Assembly
68000 Assembly
main: MOVEQ #1,D1 ;counter for how many times to print *, this is also the loop counter .outerloop: MOVE.W D1,D2 SUBQ.W #1,D2 .innerloop: MOVE.B #'*',D0 JSR PrintChar ;hardware-dependent printing routine DBRA D2,.innerloop ;DBRA loops until wraparound to $FFFF, which i...
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Action.21
Action!
PROC Main() BYTE i   FOR i=0 TO 70 STEP 7 DO PrintF("%B ",i) OD RETURN
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Oforth
Oforth
: ludic(n) | ludics l p | ListBuffer newSize(n) seqFrom(2, n) over addAll ->l ListBuffer newSize(n) dup add(1) dup ->ludics   while(l notEmpty) [ l removeFirst dup ludics add ->p l size p / p * while(dup 1 > ) [ dup l removeAt drop p - ] drop ] ;   : ludics | l i | ludic(22000) ->l "F...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#ALGOL_68
ALGOL 68
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#ALGOL_W
ALGOL W
begin integer i; i := 0; while begin i := i + 1; writeon( i ); i < 10 end do begin writeon( "," ) end end.
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program loopnested.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall     .equ NBVALUECOL, ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Phix
Phix
procedure test(integer start, stop, step, string legend, bool bFor) sequence res = {} if bFor then try for i=start to stop by step do res &= i if length(res)>9 then exit end if end for res = sprint(res) catch e res =...
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#AppleScript
AppleScript
repeat with fruit in {"Apple", "Orange", "Banana"} log contents of fruit end repeat
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Arturo
Arturo
arr: ["one" "two" "three"]   dict: #[ name: "John" surname: "Doe" age: 34 ]   loop arr 'item -> print item   loop dict [key val]-> print [key "=>" val]
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { A[1] = 49927398716; A[2] = 49927398717; A[3] = 1234567812345678; A[4] = 1234567812345670; A[5] = "01234567897"; A[6] = "01234567890"; A[7] = "00000000000"; for (k in A) print "isLuhn("A[k]"): ",isLuhn(A[k]); }   function isLuhn(cardno) { s = 0; m = "024...
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#DWScript
DWScript
function IsMersennePrime(p : Integer) : Boolean; var i, s, m_p : Integer; begin if p=2 then Result:=True else begin m_p := (1 shl p)-1; s := 4; for i:=3 to p do s:=(s*s-2) mod m_p; Result:=(s=0); end; end;   const upperBound = Round(Log2(High(Integer))/2);   PrintLn('F...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#Wren
Wren
import "os" for Process import "/trait" for Stepped import "/str" for Str   var luckyOdd = List.filled(1e5, 0) var luckyEven = List.filled(1e5, 0)   var init = Fn.new { for (i in 0...1e5) { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } }   var filterLuckyOdd = Fn.new { var n = 2 while...
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Go
Go
package main   import ( "fmt" "log" "strings" )   // Compress a string to a list of output symbols. func compress(uncompressed string) []int { // Build the dictionary. dictSize := 256 // We actually want a map of []byte -> int but // slices are not acceptable map key types. dictionary := make(map[string]int, di...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#Lobster
Lobster
import std   // derived from JAMA v1.03   // rectangular input array A is transformed in place to LU form   def LUDecomposition(LU): // Use a "left-looking", dot-product, Crout/Doolittle algorithm. let m = LU.length let n = LU[0].length let piv = map(m): _ var pivsign = 1 let LUcolj = map(m): 0.0 /...
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Prolog
Prolog
reverse_number(Number, Rev):- reverse_number(Number, 0, Rev).   reverse_number(0, Rev, Rev):-!. reverse_number(N, R, Rev):- R1 is R * 10 + N mod 10, N1 is N // 10, reverse_number(N1, R1, Rev).   lychrel(N, M, _, [], [], []):- M > N, !. lychrel(N, M, Cache, Seeds, Related, Palindromes):- reve...
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another...
#Oforth
Oforth
: madlibs | story i word |   "" while(System.Console askln dup notEmpty) [ + ] drop ->story   while(story indexOf('<') dup ->i notNull) [ story extract(i, story indexOfFrom('>', i)) ->word story replaceAll(word, "Word for" . word . System.Console askln) ->story ]   "Your story :" . story pri...
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#C.23
C#
  using System; using System.Globalization;   namespace PrimeNumberLoopcs { class Program { static bool isPrime(double number) { for(double i = number - 1; i > 1; i--) { if (number % i == 0) return false; } retur...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Aime
Aime
while (1) { o_text("SPAM\n"); }
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ALGOL_60
ALGOL 60
begin integer i; for i:=1 step 0 until 2 do outtext("spam") end
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#Factor
Factor
USING: formatting kernel locals math math.functions math.ranges sequences sequences.generalizations tools.memory.private ;   [let  ! Allow lexical variables. 1 :> prod!  ! Start with a product of unity. 0 :> sum!  ! " " " sum " zero. 5 ...
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#FreeBASIC
FreeBASIC
  Dim Shared As Long prod, sum   Sub process(x As Long) sum += Abs(x) If Abs(prod) < (2 ^ 27) And x <> 0 Then prod *= x End Sub   Dim j As Long prod = 1 sum = 0 Dim As Integer x = 5, y = -5, z = -2 Dim As Integer one = 1, three = 3, seven = 7   For j = -three To (3 ^ 3) Step three: process(j): Next j For j = -s...
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#AppleScript
AppleScript
set i to 1024 repeat while i > 0 log i set i to i / 2 end repeat
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#11l
11l
L(i) (10..0).step(-1) print(i)
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#11l
11l
V val = 0 L val++ print(val) I val % 6 == 0 L.break
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#8086_Assembly
8086 Assembly
StarSub:   mov ah,02h ;needed to prime the interrupt command for printing to screen mov ch,1 ;outer loop counter   outer_loop: mov cl,ch ;refresh the inner loop counter, by copying the value of the outer loop counter to it. ;each time the inner loop finishes, it will last one iteration longer the next...
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Ada
Ada
with Loopers; use Loopers;     procedure For_Main is begin Looper_1; Looper_2; Looper_3; end For_Main;     package Loopers is procedure Looper_1; procedure Looper_2; procedure Looper_3; end Loopers;   with Ada.Text_IO, Ada.Integer_Text_IO; use Ada.Text_IO, Ada.Integer_Tex...
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#PARI.2FGP
PARI/GP
  \\ Creating Vlf - Vector of ludic numbers' flags, \\ where the index of each flag=1 is the ludic number. \\ 2/28/16 aev ludic(maxn)={my(Vlf=vector(maxn,z,1),n2=maxn\2,k,j1); for(i=2,n2, if(Vlf[i], k=0; j1=i+1; for(j=j1,maxn, if(Vlf[j], k++); if(k==i, Vlf[j]=0; k=0)) ); ); return(Vlf); }   { \\ R...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#AmigaE
AmigaE
PROC main() DEF i FOR i := 1 TO 10 WriteF('\d', i) EXIT i = 10 WriteF(', ') ENDFOR ENDPROC
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program loopnplusone.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data szM...
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#AutoHotkey
AutoHotkey
Loop, 10 { i := A_Index Loop, 10 { j := A_Index Random, a%i%%j%, 1, 20 } }   Loop, 10 { i := A_Index Loop, 10 { j := A_Index If (a%i%%j% == 20) Goto finish } }   finish: MsgBox % "a[" . i . "][" . j . "]" is 20 Return
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#PL.2FI
PL/I
loops:procedure options (main); declare i fixed binary;   put skip list ('-2 to 2 by 1:'); do i = -2 to 2 by 1; put edit (i) (f(3)); end; put skip list ('-2 to 2 by 0: infinite loop, prints -2');   put skip list ('-2 to 2 by -1: [no values printed]'); do i = -2 to 2 by -1; put edit (i...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Python
Python
import re from itertools import islice # To limit execution if it would generate huge values # list(islice('ABCDEFG', 2)) --> ['A', 'B'] # list(islice('ABCDEFG', 4)) --> ['A', 'B', 'C', 'D']     data = ''' start stop increment Comment -2 2 1 Normal -2 2 0 Zero increment -2 2 -1 Increments away from stop va...
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#AutoHotkey
AutoHotkey
string = mary,had,a,little,lamb Loop, Parse, string, `, MsgBox %A_LoopField%
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Bash
Bash
#!/bin/bash   function luhn_validate # <numeric-string> { num=$1 shift 1   len=${#num} is_odd=1 sum=0 for((t = len - 1; t >= 0; --t)) { digit=${num:$t:1}   if [[ $is_odd -eq 1 ]]; then sum=$(( sum + $digit )) else sum=$(( $sum + ( $digit != 9 ? ( ...
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#EchoLisp
EchoLisp
  (require 'bigint) (define (mersenne-prime? odd-prime: p) (define mp (1- (expt 2 p))) (define s #4) (for [(i (in-range 3 (1+ p)))] (set! s (% (- (* s s) 2) mp))) (when (zero? s) (printf "M%d" p)))   ;; run it in the background (require 'tasks) (define LP (primes 10000)) ; list of candidate primes   (define (mp-t...
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers
Lucky and even lucky numbers
Note that in the following explanation list indices are assumed to start at one. Definition of lucky numbers Lucky numbers are positive integers that are formed by: Form a list of all the positive odd integers > 0 1 , 3 , 5 , 7 , 9 , 11 , 13 , 15 , 17 , 19 , 21 , 23 , 25 , 27 , 29 , 31 , 33 , 35 , 37 , 39... {...
#zkl
zkl
fcn lgen(a){ ns,idx:=[a..*,2],2; vm.yield(ns.next()); while(1){ n:=ns.next(); vm.yield(n); ns=ns.tweak(skipper.fp1(n,Ref(idx+=1))); // tack on another filter } } fcn skipper(n,skp,cnt){ z:=cnt.inc(); if(z%skp==0) Void.Skip else n }