factorize(n){
	if n = 1
		return 1
	if n < 1
		return false
	result := 0, m := n, k := 2
	While n >= k{
		while !Mod(m, k){
			result .= " * " . k, m /= k
		}
		k++
	}
	return SubStr(result, 5)
}
Loop 22
   out .= A_Index ": " factorize(A_index) "`n"
MsgBox % out


(load "@lib/http.l")

(in "text.csv"
   (<table> 'myStyle NIL NIL
      (prinl)
      (while (split (line) ",")
         (<row> NIL (ht:Prin (pack (car @))) (ht:Prin (pack (cadr @))))
         (prinl) ) ) )


Import-Csv -Path .\csv_html_test.csv | ConvertTo-Html -Fragment | Out-File .\csv_html_test.html


public class Count{
    public static void main(String[] args){
        for(int i = 0;i >= 0;i++){
            System.out.println(Integer.toOctalString(i)); //optionally use "Integer.toString(i, 8)"
        }
    }
}


for (var n = 0; n < 1e14; n++) { // arbitrary limit that's not too big
    document.writeln(n.toString(8)); // not sure what's the best way to output it in JavaScript
}


# generate octals as strings, beginning with "0"
def octals:
  # input and output: array of octal digits in reverse order
  def octal_add1:
    [foreach (.[], null) as $d ({carry: 1};
     if $d then ($d + .carry ) as $r
     | if $r > 7
       then {carry: 1, emit: ($r - 8)}
       else {carry: 0, emit: $r }
       end
     elif (.carry == 0) then .emit = null
     else .emit = .carry
     end;
  select(.emit).emit)];

  [0] | recurse(octal_add1) | reverse | join("");

octals


for i in one(Int64):typemax(Int64)
    print(oct(i), " ")
    sleep(0.1)
end


include ..\Utilitys.tlhy

:octal "" >ps [dup 7 band tostr ps> chain >ps 8 / int] [dup abs 0 >] while ps> tonum bor ;

( 0 10 ) sequence @octal map pstack

" " input


(let* ((str1 "hi")
       (str1-ref str1)
       (str2 (copy-sequence str1)))
  (eq str1 str1-ref) ;=> t
  (eq str1 str2) ;=> nil
  (equal str1 str1-ref) ;=> t
  (equal str1 str2)) ;=> t


sequence first = "ABC"
sequence newOne = first


let str = "hello"
let additionalReference = str
let deepCopy = System.String.Copy( str )

printfn "%b" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true
printfn "%b" <| System.Object.ReferenceEquals( str, deepCopy )            // prints false


# syntax: GAWK -f COUNT_IN_FACTORS.AWK
BEGIN {
    fmt = "%d=%s\n"
    for (i=1; i<=16; i++) {
      printf(fmt,i,factors(i))
    }
    i = 2144; printf(fmt,i,factors(i))
    i = 6358; printf(fmt,i,factors(i))
    exit(0)
}
function factors(n,  f,p) {
    if (n == 1) {
      return(1)
    }
    p = 2
    while (p <= n) {
      if (n % p == 0) {
        f = sprintf("%s%s*",f,p)
        n /= p
      }
      else {
        p++
      }
    }
    return(substr(f,1,length(f)-1))
}


 100  FOR I = 1 TO 20
 110      GOSUB 200"FACTORIAL
 120      PRINT I" = "FA$
 130  NEXT I
 140  END

 200 FA$ = "1"
 210  LET NUM = I
 220  LET O = 5 - (I = 1) * 4
 230  FOR F = 2 TO I
 240      LET M =  INT (NUM / F) * F
 250      IF NUM - M GOTO 300
 260          LET NUM = NUM / F
 270          LET F$ =  STR $(F)
 280         FA$ = FA$ + " X " +  F$
 290          LET F = F - 1

 300  NEXT F
 310 FA$ =  MID$ (FA$,O)
 320  RETURN


csv_html :-
	L = "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!",

	csv_html(L, Out, []),
	string_to_list(Str, Out),
	writeln(Str).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% simple HTML
%
csv_html(L) -->
	"
\n",
	csv_tr(L),
	"
".

csv_tr([]) --> [].

csv_tr(L) -->
	"
\n",
	csv_td(L, S),
	"\n
\n",
	csv_tr(S).

csv_td(L, S) -->
	"",
	csv_td_in(L, S),
	"	".

csv_td_in([], []) --> [].

csv_td_in([10|L], L) --> [].

csv_td_in([44|L], S) -->
	"	",
	csv_td_in(L,S).

csv_td_in([60|T], S) -->
	"<",
	csv_td_in(T, S).

csv_td_in([62|T], S) -->
	">",
	csv_td_in(T, S).

csv_td_in([H|T], S) -->
	[H],
	csv_td_in(T, S).


//  version 1.1

//  counts up to 177 octal i.e. 127 decimal
fun main(args: Array<String>) {
    (0..Byte.MAX_VALUE).forEach { println("%03o".format(it)) }
}


'%4o '__number_format set
0 do dup 1 compress . "\n" . 1 + loop


(: lists foreach
  (lambda (x)
    (: io format '"~p~n" (list (: erlang integer_to_list x 8))))
  (: lists seq 0 2000))


"This is a mutable string." dup ! reference
"Let's make a deal!" dup clone  ! copy
"New" " string" append .               ! new string
    "New string"


\ Allocate two string buffers
create stringa 256 allot
create stringb 256 allot

\ Copy a constant string into a string buffer
s" Hello" stringa place

\ Copy the contents of one string buffer into another
stringa count  stringb place


' FB 1.05.0 Win64

Dim s As String = "This is a string"
Dim t As String = s
' a separate copy of the string contents has been made as can be seen from the addresses
Print s, StrPtr(s)
Print t, StrPtr(t)
' to refer to the same string a pointer needs to be used
Dim u As String Ptr = @s
Print
Print *u, StrPtr(*u)
Sleep


      FOR i% = 1 TO 20
        PRINT i% " = " FNfactors(i%)
      NEXT
      END

      DEF FNfactors(N%)
      LOCAL P%, f$
      IF N% = 1 THEN = "1"
      P% = 2
      WHILE P% <= N%
        IF (N% MOD P%) = 0 THEN
          f$ += STR$(P%) + " x "
          N% DIV= P%
        ELSE
          P% += 1
        ENDIF
      ENDWHILE
      = LEFT$(f$, LEN(f$) - 3)


csvtxt = '''\
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!\
'''

from cgi import escape

def _row2tr(row, attr=None):
    cols = escape(row).split(',')
    return ('
'
            + ''.join('%s	' % data for data in cols)
            + '
')

def csv2html(txt):
    htmltxt = '
\n'
    for rownum, row in enumerate(txt.split('\n')):
        htmlrow = _row2tr(row)
        htmlrow = '
%s
\n' % htmlrow
        htmltxt += htmlrow
    htmltxt += '
\n'
    return htmltxt

htmltxt = csv2html(csvtxt)
print(htmltxt)


File <- "~/test.csv"
Opened <- readLines(con = File)
Size <- length(Opened)

HTML <- "~/test.html"

Table <- list()

for(i in 1:Size)
{
  #i=1
  Split <- unlist(strsplit(Opened[i],split = ","))
  Table[i] <- paste0("",Split,"	",collapse = "")
  Table[i] <- paste0("
",Table[i],"
")
}

Table[1] <- paste0("
",Table[1])
Table[length(Table)] <- paste0(Table[length(Table)],"
")

writeLines(as.character(Table), HTML)


    'the method used here uses the base-conversion from RC Non-decimal radices/Convert
    'to terminate hit <CTRL<BRK>

    global      alphanum$
    alphanum$   ="01234567"

    i =0

    while 1
        print toBase$( 8, i)
        i =i +1
    wend

    end

    function toBase$( base, number) '   Convert decimal variable to number string.
        maxIntegerBitSize   =len( str$( number))
        toBase$             =""
        for i =10 to 1 step -1
            remainder   =number mod base
            toBase$     =mid$( alphanum$, remainder +1, 1) +toBase$
            number      =int( number /base)
            if number <1 then exit for
        next i
        toBase$ =right$( "             " +toBase$, 10)
    end function


to increment_octal :n
  ifelse [empty? :n] [
    output 1
  ] [
    local "last
    make "last last :n
    local "butlast
    make "butlast butlast :n
    make "last sum :last 1
    ifelse [:last < 8] [
      output word :butlast :last
    ] [
      output word (increment_octal :butlast) 0
    ]
  ]
end

make "oct 0
while ["true] [
  print :oct
  make "oct increment_octal :oct
]


HAI 1.3

HOW IZ I octal YR num
    I HAS A digit, I HAS A oct ITZ ""
    IM IN YR octalizer
        digit R MOD OF num AN 8
        oct R SMOOSH digit oct MKAY
        num R QUOSHUNT OF num AN 8
        NOT num, O RLY?
            YA RLY, FOUND YR oct
        OIC
    IM OUTTA YR octalizer
IF U SAY SO

IM IN YR printer UPPIN YR num
    VISIBLE I IZ octal YR num MKAY
IM OUTTA YR printer

KTHXBYE


include "NSLog.incl"

CFStringRef original, copy

original = @"Hello!"
copy = fn StringWithString( original )

NSLog( @"%@", copy )

HandleEvents


Public Sub main()
Dim src As String
Dim dst As String

src = "Hello"
dst = src

Print src
Print dst
End


#In GAP strings are lists of characters. An affectation simply copy references
a := "more";
b := a;
b{[1..4]} := "less";
a;
# "less"

# Here is a true copy
a := "more";
b := ShallowCopy(a);
b{[1..4]} := "less";
a;
# "more"


#include <stdio.h>
#include <stdlib.h>

typedef unsigned long long ULONG;

ULONG get_prime(int idx)
{
        static long n_primes = 0, alloc = 0;
        static ULONG *primes = 0;
        ULONG last, p;
        int i;

        if (idx >= n_primes) {
                if (n_primes >= alloc) {
                        alloc += 16; /* be conservative */
                        primes = realloc(primes, sizeof(ULONG) * alloc);
                }
                if (!n_primes) {
                        primes[0] = 2;
                        primes[1] = 3;
                        n_primes = 2;
                }

                last = primes[n_primes-1];
                while (idx >= n_primes) {
                        last += 2;
                        for (i = 0; i < n_primes; i++) {
                                p = primes[i];
                                if (p * p > last) {
                                        primes[n_primes++] = last;
                                        break;
                                }
                                if (last % p == 0) break;
                        }
                }
        }
        return primes[idx];
}

int main()
{
        ULONG n, x, p;
        int i, first;

        for (x = 1; ; x++) {
                printf("%lld = ", n = x);

                for (i = 0, first = 1; ; i++) {
                        p = get_prime(i);
                        while (n % p == 0) {
                                n /= p;
                                if (!first) printf(" x ");
                                first = 0;
                                printf("%lld", p);
                        }
                        if (n <= p * p) break;
                }

                if (first)      printf("%lld\n", n);
                else if (n > 1) printf(" x %lld\n", n);
                else            printf("\n");
        }
        return 0;
}


#lang racket

(define e.g.-CSV
  (string-join
   '("Character,Speech"
     "The multitude,The messiah! Show us the messiah!"
     "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>"
     "The multitude,Who are you?"
     "Brians mother,I'm his mother; that's who!"
     "The multitude,Behold his mother! Behold his mother!")
   "\n"))

(define (CSV-lines->HTML-table csv)
  (define csv-rows
    (regexp-split "\n" csv))
  (define csv-row-cells
    (map (lambda (row) (regexp-split "," row)) csv-rows))
  (define (cell-data->HTML-data data)
    `(td () ,data))
  (define (row-data->HTML-row CSV-row)
    `(tr () ,@(map cell-data->HTML-data CSV-row) "\n"))
  `(table
    (thead
     ,(row-data->HTML-row (car csv-row-cells)))
    (tbody ,@(map row-data->HTML-row (cdr csv-row-cells)))))

(require xml)
(display (xexpr->string (CSV-lines->HTML-table e.g.-CSV)))


my $str = "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!";

# comment the next line out, if you want to read from standard input instead of the hard-coded $str above
# my $str = $*IN.slurp;

my &escape = *.trans(« & < > » => « & < > »); # a function with one argument that escapes the entities
my &tag    = {"<$^tag>"~$^what~"</$^tag>"};

printf
'<!DOCTYPE html>

<title>Some Text</title>

%s

', [~]                                # concatenation reduction ('a', 'b', 'c') → 'abc'
(escape($str).split(/\n/)             # escape the string and split at newline
  ==> map -> $line {tag 'tr',         # feed that into a map, that map function will tag as 'tr, and has an argument called $line
    ([~] $line.split(/','/)\          # split $line at ',',
                                      # that / at the end is just an unspace, you can omit it, but then you have to delete
                                      # all whitespace  and comments between split(…) and .map
      .map({tag 'td', $^cell}))})\    # map those cells as td
		       .join("\n");   # append a newline for nicer output


for l=1,2147483647 do
  print(string.format("%o",l))
end


octcount := proc (n)
 seq(printf("%a \n", convert(i, octal)), i = 1 .. n);
 end proc;


title  OCTAL - Count in octal.
subttl PDP-10 assembly (MACRO-10 on TOPS-20). KJX 2022.
search monsym,macsym

comment \
        If you want to see the overflow happening without waiting for
        too long, change "movei b,1" to "move b,[377777,,777770]".
        \

a=:1                                            ;Names for accumulators.
b=:2
c=:3

define crlf <tmsg <
>>                                              ;Macro to print newline.

start:: reset%                                  ;Initialize process.
        movei b,1                               ;B is the counter.
        movei c,^d8                             ;Octal output (nout%).
        do.
           movei a,.priou                       ;Use standard-output (nout%).
           nout%                                ;Print number in B.
              jrst [ tmsg <Output error.>       ;   NOUT can fail, print err-msg
                     jrst endprg ]              ;   and stop in that case.
           crlf                                 ;Print newline.
           aos b                                ;Add one to B.
           jfcl 10,[ tmsg <Arithmetic Overflow (AROV).> ;Handle overflow.
                     jrst endprg ]
           loop.                                ;Do again.
        enddo.

endprg: haltf%                                  ;Halt program.
        jrst start                              ;Allow continue-command.

end start


def string = 'Scooby-doo-bee-doo'    // assigns string object to a variable reference
def stringRef = string               // assigns another variable reference to the same object
def stringCopy = new String(string)  // copies string value into a new object, and assigns to a third variable reference


Start.Programs,Accessories,Notepad,
Type:Hello world[pling],Highlight:Hello world[pling],
Menu,Edit,Copy,Menu,Edit,Paste


cSource := "Hello World"
cDestination := cSource


using System;
using System.Collections.Generic;

namespace prog
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			for( int i=1; i<=22; i++ )
			{
				List<int> f = Factorize(i);
				Console.Write( i + ":  " + f[0] );
				for( int j=1; j<f.Count; j++ )
				{
					Console.Write( " * " + f[j] );
				}
				Console.WriteLine();
			}
		}

		public static List<int> Factorize( int n )
		{
			List<int> l = new List<int>();

			if ( n == 1 )
			{
				l.Add(1);
			}
			else
			{
				int k = 2;
				while( n > 1 )
				{
					while( n % k == 0 )
					{
						l.Add( k );
						n /= k;
					}
					k++;
				}
			}
			return l;
		}
	}
}


Red []

csv: {Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!}

add2html: func [ bl ] [append html rejoin bl ]  ;; helper function to add block data to html string

;;----------------------------------------------------------------------
csv2html: func ["function to generate string with html table from csv data file"
;;----------------------------------------------------------------------
    s [string!] "input .csv data"
][
arr: split s newline    ;; generate array (series) from string
html: copy "
^/" ;; init html string

forall arr  [  ;; i use forall here so that i can test for head? of series ...
  either head? arr [ append html "
"]
                      [ append html "
"]
  replace/all first arr "<" "<"    ;; escape "<" and ">" characters
  replace/all first arr ">" ">"
  foreach col split first arr "," [
      either head? arr [
        add2html [' col '	]
      ][
        add2html [' col '	]
      ]
  ]
  add2html ['
 newline]
]
return add2html ['
]
]
;;----------------------------------------------------------------------

print csv2html csv                 ;; call function
write %data.html csv2html csv   ;; write to file


remapping off
"Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!" remapping on
keepString constant CSV

: display  ( c- )
  [ ', = ] [ drop "	" puts ] when
  [ 10 = ] [ drop "
\n
" puts ] when
  [ '< = ] [ drop "<"  puts ] when
  [ '> = ] [ drop ">"  puts ] when
  [ '& = ] [ drop "&" puts ] when
  putc ;

: displayHTML  ( $- )
  "
\n
" puts
  [ @ display ] ^types'STRING [email protected]
  "
\n
" puts ;

CSV displayHTML


    n = 0;
    while (1)
        dec2base(n,8)
        n = n+1;
    end;


:- module count_in_octal.
:- interface.
:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

main(!IO) :-
    count_in_octal(0, !IO).

:- pred count_in_octal(int::in, io::di, io::uo) is det.

count_in_octal(N, !IO) :-
    io.format("%o\n", [i(N)], !IO),
    count_in_octal(N + 1, !IO).


(
  (dup 0 ==) (pop () 0 shorten)
  (((8 mod) (8 div)) cleave) 'cons linrec
  reverse 'print! foreach newline
) :octal

0 (dup octal succ)
9.223e18 int times ; close to max int value


MODULE octal;

IMPORT  InOut;

VAR     num             : CARDINAL;

BEGIN
  num := 0;
  REPEAT
    InOut.WriteOct (num, 12);           InOut.WriteLn;
    INC (num)
  UNTIL num = 0
END octal.


//Strings are immutable in 'i'.
software {
	a = "Hello World"
	b = a //This copies the string.

	a += "s"

	print(a)
	print(b)
}


procedure main()
    a := "qwerty"
    b := a
    b[2+:4] := "uarterl"
    write(a," -> ",b)
end


#include <iostream>
#include <iomanip>
using namespace std;

void getPrimeFactors( int li )
{
    int f = 2; string res;
    if ( li == 1 ) res = "1";
    else
    {
	while ( true )
	{
	    if( !( li % f ) )
	    {
		res += to_string(f);
		li /= f; if( li == 1 ) break;
		res += " x ";
	    }
	    else f++;
	}
    }
    cout << res << "\n";
}

int main( int argc, char* argv[] )
{
    for ( int x = 1; x < 101; x++ )
    {
	cout << right << setw( 4 ) << x << ": ";
	getPrimeFactors( x );
    }
    cout << 2144 << ": "; getPrimeFactors( 2144 );
    cout << "\n\n";
    return system( "pause" );
}


/*REXX program converts   CSV  ───►  HTML  table   representing  the  CSV  data.        */
arg header_ .                                    /*obtain an uppercase version of args. */
wantsHdr= (header_=='HEADER')                    /*is the arg (low/upp/mix case)=HEADER?*/
                                                 /* [↑]  determine if user wants a hdr. */
                  iFID= 'CSV_HTML.TXT'           /*the   input  fileID  to be used.     */
if wantsHdr  then oFID= 'OUTPUTH.HTML'           /*the  output  fileID  with     header.*/
             else oFID= 'OUTPUT.HTML'            /* "      "      "     without     "   */

    do rows=0  while  lines(iFID)\==0            /*read the rows from a (text/txt) file.*/
    row.rows= strip( linein(iFID) )
    end   /*rows*/

convFrom= '&      <     >     "'                 /*special characters to be converted.  */
convTo  = '&  <  >  "'            /*display what they are converted into.*/

call write , ''
call write , '
'

  do j=0 for rows;    call write 5, '
'
                           tx= 'td'
  if wantsHdr & j==0  then tx= 'th'              /*if user wants a header, then oblige. */

       do  while  row.j\=='';          parse var row.j yyy "," row.j
           do k=1  for words(convFrom)
           yyy=changestr( word( convFrom, k), yyy, word( convTo, k))
           end   /*k*/
       call write 10, '<'tx">"yyy'</'tx">"
       end       /*forever*/
  end            /*j*/

call write 5, '
'
call write  , '
'
call write  , ''
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
write:   call lineout  oFID,  left('', 0 || arg(1) )arg(2);                         return


i = 0
while i < 2^64
    println format("%o", i)
    i += 1
end


/* NetRexx */
options replace format comments java crossref symbols binary

import java.math.BigInteger

-- allow an option to change the output radix.
parse arg radix .
if radix.length() == 0 then radix = 8
k_ = BigInteger
k_ = BigInteger.ZERO

loop forever
  say k_.toString(int radix)
  k_ = k_.add(BigInteger.ONE)
  end


; file:   ocount.lsp
; url:    http://rosettacode.org/wiki/Count_in_octal
; author: oofoe 2012-01-29

; Although NewLISP itself uses a 64-bit integer representation, the
; format function relies on underlying C library's printf function,
; which can only handle a 32-bit octal number on this implementation.

(for (i 0 (pow 2 32)) (println (format "%o" i)))

(exit)


import strutils
for i in 0 ..< int.high:
  echo toOct(i, 16)


MODULE CountInOctal;
IMPORT
  NPCT:Tools,
  Out := NPCT:Console;
VAR
  i: INTEGER;

BEGIN
  FOR i := 0 TO MAX(INTEGER) DO;
    Out.String(Tools.IntToOct(i));Out.Ln
  END
END CountInOctal.


String src = "Hello";
String newAlias = src;
String strCopy = new String(src);

//"newAlias == src" is true
//"strCopy == src" is false
//"strCopy.equals(src)" is true


var container = {myString: "Hello"};
var containerCopy = container; // Now both identifiers refer to the same object

containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"


def demo:
  "abc" as $s    # assignment of a string to a variable
  | $s as $t     # $t points to the same string as $s
  | "def" as $s  # This $s shadows the previous $s
  | $t           # $t still points to "abc"
;

demo


(ns listfactors
  (:gen-class))

(defn factors
  "Return a list of factors of N."
  ([n]
   (factors n 2 ()))
  ([n k acc]
   (cond
     (= n 1) (if (empty? acc)
               [n]
               (sort acc))
     (>= k n) (if (empty? acc)
                    [n]
                    (sort (cons n acc)))
    (= 0 (rem n k)) (recur (quot n k) k (cons k acc))
    :else (recur n (inc k) acc))))

(doseq [q (range 1 26)]
  (println q " = " (clojure.string/join " x "(factors q))))


count_primes = (max) ->
  # Count through the natural numbers and give their prime
  # factorization.  This algorithm uses no division.
  # Instead, each prime number starts a rolling odometer
  # to help subsequent factorizations.  The algorithm works similar
  # to the Sieve of Eratosthenes, as we note when each prime number's
  # odometer rolls a digit.  (As it turns out, as long as your computer
  # is not horribly slow at division, you're better off just doing simple
  # prime factorizations on each new n vs. using this algorithm.)
  console.log "1 = 1"
  primes = []
  n = 2
  while n <= max
    factors = []
    for prime_odometer in primes
      # digits are an array w/least significant digit in
      # position 0;  for example, [3, [0]] will roll as
      # follows:
      #    [0] -> [1] -> [2] -> [0, 1]
      [base, digits] = prime_odometer
      i = 0
      while true
        digits[i] += 1
        break if digits[i] < base
        digits[i] = 0
        factors.push base
        i += 1
        if i >= digits.length
          digits.push 0

    if factors.length == 0
      primes.push [n, [0, 1]]
      factors.push n
    console.log "#{n} = #{factors.join('*')}"
    n += 1

  primes.length

num_primes = count_primes 10000
console.log num_primes


csv$ = "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"

k	= instr(csv$,",")                                 ' 2 exra lines to get heading
csv$  = left$(csv$,k - 1) + "	 + mid$(csv$,k + 1)

csv$ = strRep$(csv$,",","	")
html "

";strRep$(csv$,chr$(13),"

");"
</table"
wait
' --------------------------------
' string replace rep str with
' --------------------------------
FUNCTION strRep$(strRep$,rep$,with$)
ln	= len(rep$)
k	= instr(strRep$,rep$)
while k
	strRep$	= left$(strRep$,k - 1) + with$ + mid$(strRep$,k + ln)
	k	= instr(strRep$,rep$)
WEND
END FUNCTION


let () =
  for i = 0 to max_int do
    Printf.printf "%o\n" i
  done


program StrAdd;
{$Mode Delphi}
{$Optimization ON}
uses
  sysutils;//IntToStr

const
  maxCntOct = (SizeOf(NativeUint)*8+(3-1)) DIV 3;

procedure IntToOctString(i: NativeUint;var res:Ansistring);
var
  p : array[0..maxCntOct] of byte;
  c,cnt: LongInt;
begin
  cnt := maxCntOct;
  repeat
    c := i AND 7;
    p[cnt] := (c+Ord('0'));
    dec(cnt);
    i := i shr 3;
  until (i = 0);
  i := cnt+1;
  cnt := maxCntOct-cnt;
  //most time consuming with Ansistring
  //call fpc_ansistr_unique
  setlength(res,cnt);
  move(p[i],res[1],cnt);
end;

procedure IncStr(var s:String;base:NativeInt);
var
  le,c,dg:nativeInt;
begin
  le := length(s);
  IF le = 0 then
  Begin
    s := '1';
    EXIT;
  end;

  repeat
    dg := ord(s[le])-ord('0') +1;
    c  := ord(dg>=base);
    dg := dg-(base AND (-c));
    s[le] := chr(dg+ord('0'));
    dec(le);
  until (c = 0) or (le<=0);

  if (c = 1) then
  begin
    le := length(s);
    setlength(s,le+1);
    move(s[1],s[2],le);
    s[1] := '1';
  end;
end;

const
  MAX = 8*8*8*8*8*8*8*8*8;//8^9
var
  sOct,
  s  : AnsiString;
  i : nativeInt;
  T1,T0: TDateTime;
Begin
  sOct := '';
  For i := 1 to 16 do
  Begin
    IncStr(sOct,8);
    writeln(i:10,sOct:10);
  end;
  writeln;

  For i := 1 to 16 do
  Begin
    IntToOctString(i,s);
    writeln(i:10,s:10);
  end;

  sOct := '';
  T0 := time;
  For i := 1 to MAX do
    IncStr(sOct,8);
  T0 := (time-T0)*86400;
  writeln(sOct);

  T1 := time;
  For i := 1 to MAX do
    IntToOctString(i,s);
  T1 := (time-T1)*86400;
  writeln(s);
  writeln;
  writeln(MAX);
  writeln('IncStr         ',T0:8:3);
  writeln('IntToOctString ',T1:8:3);
end.


s = "Rosetta Code"
t = s

println("s = \"", s, "\" and, after \"t = s\", t = \"", t, "\"")

s = "Julia at "*s

println("s = \"", s, "\" and, after this change, t = \"", t, "\"")


Var:String str1 = "Hello";
Var:String str2 = str1;


val s = "Hello"
val alias = s      // alias === s
val copy = "" + s  // copy !== s


(defparameter *primes*
  (make-array 10 :adjustable t :fill-pointer 0 :element-type 'integer))

(mapc #'(lambda (x) (vector-push x *primes*)) '(2 3 5 7))

(defun extend-primes (n)
  (let ((p (+ 2 (elt *primes* (1- (length *primes*))))))
    (loop for i = p then (+ 2 i)
	  while (<= (* i i) n) do
	  (if (primep i t) (vector-push-extend i *primes*)))))

(defun primep (n &optional skip)
  (if (not skip) (extend-primes n))
  (if (= n 1) nil
      (loop for p across *primes* while (<= (* p p) n)
	    never (zerop (mod n p)))))

(defun factors (n)
  (extend-primes n)
  (loop with res for x across *primes* while (> n (* x x)) do
	(loop while (zerop (rem n x)) do
	      (setf n (/ n x))
	      (push x res))
	finally (return (if (> n 1) (cons n res) res))))

(loop for n from 1 do
      (format t "~a: ~{~a~^ × ~}~%" n (reverse (factors n))))


static INPUT : &'static str  =
"Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!";

fn main() {
    print!("
\n
");
    for c in INPUT.chars() {
        match c {
            '\n' => print!("
\n
"),
            ','  => print!("	"),
            '<'  => print!("<"),
            '>'  => print!(">"),
            '&'  => print!("&"),
            _    => print!("{}", c)
        }
    }
    println!("
\n
");
}


object CsvToHTML extends App {
  val header =
    <title>CsvToHTML</title>

  val csv =
    """Character,Speech
      |The multitude,The messiah! Show us the messiah!
      |Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
      |The multitude,Who are you?
      |Brians mother,I'm his mother; that's who!
      |The multitude,Behold his mother! Behold his mother!""".stripMargin

  def csv2html(csv: String, withHead: Boolean) = {

    def processRow(text: String) =

      {text.split(',').map(s =>
        {s}
      	)}

    val (first :: rest) = csv.lines.toList // Separate the header and the rest

    def tableHead = if (withHead)

        {processRow(first)}

    else processRow(first)

      {header}

        {tableHead}{rest.map(processRow)}

  }

  println(csv2html(csv, true))
}


use POSIX;
printf "%o\n", $_ for (0 .. POSIX::UINT_MAX);


without javascript_semantics
integer i = 0
constant ESC = #1B
while not find(get_key(),{ESC,'q','Q'}) do
    printf(1,"%o\n",i)
    i += 1
end while


go =>
  gen(N),
  println(to_oct_string(N)),
  fail.

gen(I) :-
  gen(0, I).
gen(I, I).
gen(I, J) :-
  I2 is I + 1,
  gen(I2, J).


(for (N 0  T  (inc N))
   (prinl (oct N)) )


local(x = 'I saw a rhino!')
local(y = #x)

#x //I saw a rhino!
'\r'
#y //I saw a rhino!

'\r\r'
#x = 'I saw one too'
#x //I saw one too
'\r'
#y //I saw a rhino!

'\r\r'
#y = 'it was grey.'
#x //I saw one too
'\r'
#y //it was grey.


a := "Hello".
b := a.
c := a clone.
println: a == b.  ; True
println: a == c.  ; True
println: a === b. ; True
println: a === c. ; False


        .ORIG      0x3000

        LEA        R1,SRC
        LEA        R2,COPY

LOOP    LDR        R3,R1,0
        STR        R3,R2,0
        BRZ        DONE
        ADD        R1,R1,1
        ADD        R2,R2,1
        BRNZP      LOOP

DONE    LEA        R0,COPY
        PUTS

        HALT

SRC     .STRINGZ   "What, has this thing appeared again tonight?"

COPY    .BLKW      128

        .END


(let* ((a '"data assigned to a")
       (b a))
  (: io format '"Contents of 'b': ~s~n" (list b)))


src$ = "Hello"
dest$ = src$
print src$
print dest$


int[] factorize(in int n) pure nothrow
in {
    assert(n > 0);
} body {
    if (n == 1) return [1];
    int[] result;
    int m = n, k = 2;
    while (n >= k) {
        while (m % k == 0) {
            result ~= k;
            m /= k;
        }
        k++;
    }
    return result;
}

void main() {
    import std.stdio;
    foreach (i; 1 .. 22)
        writefln("%d: %(%d × %)", i, i.factorize());
}


$ close /nolog primes
$ on control_y then $ goto clean
$
$ n = 1
$ outer_loop:
$  x = n
$  open primes primes.txt
$
$  loop1:
$   read /end_of_file = prime primes prime
$   prime = f$integer( prime )
$   loop2:
$    t = x / prime
$    if t * prime .eq. x
$    then
$     if f$type( factorization ) .eqs. ""
$     then
$      factorization = f$string( prime )
$     else
$      factorization = factorization + "*" + f$string( prime )
$     endif
$     if t .eq. 1 then $ goto done
$     x = t
$     goto loop2
$    else
$     goto loop1
$    endif
$ prime:
$  if f$type( factorization ) .eqs. ""
$  then
$   factorization = f$string( x )
$  else
$   factorization = factorization + "*" + f$string( x )
$  endif
$ done:
$  write sys$output f$fao( "!4SL = ", n ), factorization
$  delete /symbol factorization
$  close primes
$  n = n + 1
$  if n .le. 2144 then $ goto outer_loop
$  exit
$
$ clean:
$ close /nolog primes


$ include "seed7_05.s7i";
  include "html_ent.s7i";

const string: csvData is "\
    \Character,Speech\n\
    \The multitude,The messiah! Show us the messiah!\n\
    \Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n\
    \The multitude,Who are you?\n\
    \Brians mother,I'm his mother; that's who!\n\
    \The multitude,Behold his mother! Behold his mother!\n";

const proc: main is func
  local
    var string: line is "";
    var string: column is "";
    const array [boolean] string: columnStartTag is [boolean] ("", "");
    const array [boolean] string: columnEndTag is [boolean] ("	", "	");
    var boolean: firstLine is TRUE;
  begin
    writeln("
");
    for line range split(csvData, '\n') do
      write("
");
      for column range split(line, ',') do
        write(columnStartTag[firstLine] <& encodeHtmlContent(column) <& columnEndTag[firstLine]);
      end for;
      writeln("
");
      firstLine := FALSE;
    end for;
    writeln("
");
  end func;


int i=1;
while(true)
    write("0%o\n", i++);


/* Do the actual counting in octal. */
count: procedure options (main);
   declare v(5) fixed(1) static initial ((5)0);
   declare (i, k) fixed;

   do k = 1 to 999;
      call inc;
      put skip edit ( (v(i) do i = 1 to 5) ) (f(1));
   end;

inc: proc;
   declare (carry, i) fixed binary;

   carry = 1;
   do i = 5 to 1 by -1;
      v(i) = v(i) + carry;
      if v(i) > 7 then
         do; v(i) = v(i) - 8; if i = 1 then stop; carry = 1; end;
      else
         carry = 0;
   end;
end inc;

end count;


100H: /* PRINT INTEGERS IN OCTAL */
   BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
      DECLARE FN BYTE, ARG ADDRESS;
      GOTO 5;
   END BDOS;
   PR$CHAR:  PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
   PR$NL:    PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
   PR$OCTAL: PROCEDURE( N );
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, O$STR( 7 ) BYTE, W BYTE;
      V = N;
      O$STR( W := 0 ) = '0' + ( V AND 7 );
      DO WHILE( ( V := SHR( V, 3 ) ) > 0 );
         O$STR( W := W + 1 ) = '0' + ( V AND 7 );
      END;
      W = W + 1;
      DO WHILE( W <> 0 );
         CALL PR$CHAR( O$STR( W := W - 1 ) );
      END;
   END PR$OCTAL;

   DECLARE N ADDRESS;
   N = 0;
   CALL PR$OCTAL( N );
   CALL PR$NL;
   DO WHILE( ( N := N + 1 ) > 0 ); /* AFTER 65535 N WILL WRAP 'ROUND TO 0 */
      CALL PR$OCTAL( N );
      CALL PR$NL;
   END;
EOF


+ scon : STRING_CONSTANT;
+ svar : STRING;

scon := "sample";
svar := STRING.create 20;
svar.copy scon;
svar.append "!\n";

svar.print;


string a = "A string";
string b = a;
a =~ s/$/\./;
puts(a);
puts(b);


put "foo" into bar
put bar into baz
answer bar && baz


make "a "foo
make "b "foo
print .eq :a :b   ; true, identical symbols are reused

make "c :a
print .eq :a :c   ; true, copy a reference

make "c word :b "||  ; force a copy of the contents of a word by appending the empty word
print equal? :b :c   ; true
print .eq :b :c     ; false


function Factorize(n : Integer) : String;
begin
   if n <= 1 then
      Exit('1');
   var k := 2;
   while n >= k do begin
      while (n mod k) = 0 do begin
         Result += ' * '+IntToStr(k);
         n := n div k;
      end;
      Inc(k);
   end;
   Result:=SubStr(Result, 4);
end;

var i : Integer;
for i := 1 to 22 do
   PrintLn(IntToStr(i) + ': ' + Factorize(i));


func escape(str) { str.trans(« & < > », « & < > ») }
func tag(t, d)   { "<#{t}>#{d}</#{t}>" }

func csv2html(str) {

    var template = <<-'EOT'
    <!DOCTYPE html>

    <title>Some Text</title>

    %s

    EOT

    template.sprintf(escape(str).lines.map{ |line|
            tag('tr', line.split(',').map{|cell| tag('td', cell) }.join)
        }.join("\n")
    )
}

var str = <<'EOT';
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
EOT

print csv2html(str)


package require Tcl 8.5
package require csv
package require html
package require struct::queue

set csvData "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"

struct::queue rows
foreach line [split $csvData "\n"] {
    csv::split2queue rows $line
}
html::init
puts [subst {
    [html::openTag table {summary="csv2html program output"}]
    [html::while {[rows size]} {
	[html::row {*}[html::quoteFormValue [rows get]]]
    }]
    [html::closeTag]
}]


[int64]$i = 0
While ( $True )
    {
    [Convert]::ToString( ++$i, 8 )
    }


o(O) :- member(O, [0,1,2,3,4,5,6,7]).

octal([O]) :- o(O).
octal([A|B]) :-
	octal(O),
	o(T),
	append(O, [T], [A|B]),
	dif(A, 0).

octalize :-
	forall(
		octal(X),
		(maplist(write, X), nl)
	).


Procedure.s octal(n.q)
  Static Dim digits(20)
  Protected i, j, result.s
  For i = 0 To 20
    digits(i) = n % 8
    n / 8
    If n < 1
      For j = i To 0 Step -1
        result + Str(digits(j))
      Next
      Break
    EndIf
  Next

  ProcedureReturn result
EndProcedure

Define n.q
If OpenConsole()
  While n >= 0
    PrintN(octal(n))
    n + 1
  Wend

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


a = "string"
b = a
print(a == b) -->true
print(b) -->string


> s := "some string";
                           s := "some string"

> t := "some string";
                           t := "some string"

> evalb( s = t ); # they are equal
                                  true

> addressof( s ) = addressof( t ); # not just equal data, but the same address in memory
                        3078334210 = 3078334210

> u := t: # copy reference


/* It's possible in Maxima to access individual characters by subscripts, but it's not the usual way.
Also, the result is "Lisp character", which cannot be used by other Maxima functions except cunlisp. The usual
way to access characters is charat, returning a "Maxima character" (actually a one characte string). With the latter,
it's impossible to modify a string in place, thus scopy is of little use. */

a: "loners"$
b: scopy(a)$
c: a$

c[2]: c[5]$

a;
"losers"

b;
"loners"

c;
"losers"


(define (task (nfrom 2) (range 20))
 (for ((i (in-range nfrom (+ nfrom range))))
     (writeln i "=" (string-join (prime-factors i) " x "))))


class
	COUNT_IN_FACTORS

feature

	display_factor (p: INTEGER)
			-- Factors of all integers up to 'p'.
		require
			p_positive: p > 0
		local
			factors: ARRAY [INTEGER]
		do
			across
				1 |..| p as c
			loop
				io.new_line
				io.put_string (c.item.out + "%T")
				factors := factor (c.item)
				across
					factors as f
				loop
					io.put_integer (f.item)
					if f.is_last = False then
						io.put_string (" x ")
					end
				end
			end
		end

        factor (p: INTEGER): ARRAY [INTEGER]
			-- Prime decomposition of 'p'.
		require
			p_positive: p > 0
		local
			div, i, next, rest: INTEGER
		do
			create Result.make_empty
			if p = 1 then
				Result.force (1, 1)
			end
			div := 2
			next := 3
			rest := p
			from
				i := 1
			until
				rest = 1
			loop
				from
				until
					rest \\ div /= 0
				loop
					Result.force (div, i)
					rest := (rest / div).floor
					i := i + 1
				end
				div := next
				next := next + 2
			end
		ensure
			is_divisor: across Result as r all p \\ r.item = 0 end
		end
end


$$ MODE TUSCRIPT
MODE DATA
$$ csv=*
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
$$ htmlhead=*
<!DOCTYPE html system>

<title>Life of Brian</title>

$$ BUILD X_TABLE txt2html=*
 << <
 >> >
$$ MODE TUSCRIPT
file="brian.html"
ERROR/STOP CREATE (file,FDF-o,-std-)
csv=EXCHANGE (csv,txt2html)
x=SPLIT (csv,":,:",row1,row2)
ACCESS html: WRITE/ERASE/RECORDS/UTF8 $file s,html
WRITE html htmlhead
LOOP n,td1=row1,td2=row2
IF (n==1) THEN
row=CONCAT ("
",td1,"	",td2,"
")
ELSE
row=CONCAT ("
",td1,"	",td2,"
")
ENDIF
WRITE html row
ENDLOOP
WRITE html "
"
ENDACCESS/PRINT html


@(collect)
@char,@speech
@(end)
@(output :filter :to_html)

@  (repeat)

     @char
     @speech

@  (end)

@(end)


import sys
for n in xrange(sys.maxint):
    print oct(n)


#lang racket
(for ([i (in-naturals)])
  (displayln (number->string i 8)))


/*REXX program counts in octal until the number exceeds the number of program statements*/

        /*┌────────────────────────────────────────────────────────────────────┐
          │ Count all the protons  (and electrons!)  in the universe.          │
          │                                                                    │
          │ According to Sir Arthur Eddington in 1938 at his Tamer Lecture at  │
          │ Trinity College (Cambridge),  he postulated that there are exactly │
          │                                                                    │
          │                              136 ∙ 2^256                           │
          │                                                                    │
          │ protons in the universe,  and the same number of electrons,  which │
          │ is equal to around  1.57477e+79.                                   │
          │                                                                    │
          │ [Although, a modern estimate is around  10^80.]                    │
          └────────────────────────────────────────────────────────────────────┘*/

numeric digits 100000                            /*handle almost any sized big numbers. */
numIn= right('number in', 20)                    /*used for indentation of the output.  */
w= length( sourceline() )                        /*used for formatting width of numbers.*/

  do #=0  to 136 * (2**256)                      /*Sir Eddington, here we come !        */
  != x2b( d2x(#) )
  _= right(!,  3 * (length(_) % 3 + 1),  0)
  o=
                do k=1  to length(_)  by 3
                o= o'0'substr(_, k, 3)
                end   /*k*/

  say numIn  'base ten = '   right(#,w) numIn    "octal = "   right( b2x(o) + 0, w + w)
  if #>sourceline()  then leave                  /*stop if # of protons > pgm statements*/
  end   /*#*/
                                                 /*stick a fork in it,  we're all done. */


string s, a;
s := "hello";
a := s;
s := s & " world";
message s;  % writes "hello world"
message a;  % writes "hello"
end


phrase = "hi"
copy = phrase
print phrase
print copy


.data

.text

strcpy:
  addi $sp, $sp, -4
  sw $s0, 0($sp)
  add $s0, $zero, $zero

L1:
  add $t1, $s0, $a1
  lb $t2, 0($t1)
  add $t3, $s0, $a0
  sb $t2, 0($t3)
  beq $t2, $zero, L2
  addi $s0, $s0, 1
  j L1

L2:
  lw $s0, 0($sp)
  addi $sp, $sp, 4
  jr $ra


src = "Hello"
new_alias = src

puts 'interned strings are equal' if src == new_alias

str_copy = String.new(src)
puts 'non-interned strings are not equal' if str_copy != src
puts 'compare strings with equals()' if str_copy.equals(src)


defmodule RC do
  def factor(n), do: factor(n, 2, [])

  def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
  def factor(n, i, fact) do
    if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
                    else: factor(n, i+1, fact)
  end
end

Enum.each(1..20, fn n ->
  IO.puts "#{n}: #{Enum.join(RC.factor(n)," x ")}" end)


function factorize(integer n)
    sequence result
    integer k
    if n = 1 then
        return {1}
    else
        k = 2
        result = {}
        while n > 1 do
            while remainder(n, k) = 0 do
                result &= k
                n /= k
            end while
            k += 1
        end while
        return result
    end if
end function

sequence factors
for i = 1 to 22 do
    printf(1, "%d: ", i)
    factors = factorize(i)
    for j = 1 to length(factors)-1 do
        printf(1, "%d * ", factors[j])
    end for
    printf(1, "%d\n", factors[$])
end for


csv2html() {
    IFS=,
    echo "
"

    echo "
"
    read -a fields
    htmlrow th "${fields[@]}"
    echo "
"

    echo "
"
    while read -a fields
    do htmlrow td "${fields[@]}"
    done
    echo "
"
    echo "
"
}

htmlrow() {
  cell=$1
  shift
  echo "
"
  for field
  do echo "<$cell>$(escape_html "$field")</$cell>"
  done
  echo "
"
}

escape_html() {
    str=${1//\&/&}
    str=${str//</<}
    str=${str//>/>}
    echo "$str"
}

csv2html <<-END
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
END


Public Sub CSV_TO_HTML()
    input_ = "Character,Speech\n" & _
        "The multitude,The messiah! Show us the messiah!\n" & _
        "Brians mother,<angry>Now you listen here! He's not the messiah; " & _
            "he's a very naughty boy! Now go away!</angry>\n" & _
        "The multitude,Who are you?\n" & _
        "Brians mother,I'm his mother; that's who!\n" & _
        "The multitude,Behold his mother! Behold his mother!"

    Debug.Print "
" & vbCrLf & "
"
    For i = 1 To Len(input_)
        Select Case Mid(input_, i, 1)
            Case "\"
                If Mid(input_, i + 1, 1) = "n" Then
                    Debug.Print "
" & vbCrLf & "
";
                    i = i + 1
                Else
                    Debug.Print Mid(input_, i, 1);
                End If
            Case ",": Debug.Print "	";
            Case "<": Debug.Print "<";
            Case ">": Debug.Print ">";
            Case "&": Debug.Print "&";
            Case Else: Debug.Print Mid(input_, i, 1);
        End Select
    Next i
    Debug.Print "
" & vbCrLf & "
"
End Sub


size = 30
for n = 1 to size
    see octal(n) + nl
next

func octal m
     output = ""
     w = m
     while fabs(w) > 0
           oct = w & 7
           w = floor(w / 8)
           output = string(oct) + output
     end
     return output


n = 0
loop do
  puts "%o" % n
  n += 1
end

# or
for n in 0..Float::INFINITY
  puts n.to_s(8)
end

# or
0.upto(1/0.0) do |n|
  printf "%o\n", n
end

# version 2.1 later
0.step do |n|
  puts format("%o", n)
end


input "Begin number:";b
input "  End number:";e

for i = b to e
  print i;" ";toBase$(8,i)
next i
end

function toBase$(base,base10)
for i = 10 to 1 step -1
  toBase$   = str$(base10 mod base) +toBase$
  base10    = int(base10 / base)
  if base10 < 1 then exit for
next i
end function


fn main() {
    for i in 0..std::usize::MAX {
        println!("{:o}", i);
    }
}


VAR src: TEXT := "Foo";
VAR dst: TEXT := src;


using System;
using System.Console;
using Nemerle;

module StrCopy
{
    Main() : void
    {
        mutable str1 = "I am not changed";      // str1 is bound to literal
        def str2 = lazy(str1);                  // str2 will be bound when evaluated
        def str3 = str1;                        // str3 is bound to value of str1
        str1 = "I am changed";                  // str1 is bound to new literal
        Write($"$(str1)\n$(str2)\n$(str3)\n");  // str2 is bound to value of str1
        // Output: I am changed
        //         I am changed
        //         I am not changed
    }
}


let factorsOf (num) =
    Seq.unfold (fun (f, n) ->
        let rec genFactor (f, n) =
            if f > n then None
            elif n % f = 0 then Some (f, (f, n/f))
            else genFactor (f+1, n)
        genFactor (f, n)) (2, num)

let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})

showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))


USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;

: .factors ( n -- )
    dup pprint ": " write factors
    [ " × " write ] [ pprint ] interleave nl ;

"1: 1" print 2 20 [a,b] [ .factors ] each


Set objfso = CreateObject("Scripting.FileSystemObject")

parent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & "\"

Set objcsv = objfso.OpenTextFile(parent_folder & "in.csv",1,False)
Set objhtml = objfso.OpenTextFile(paren_folder & "out.html",2,True)

objhtml.Write(csv_to_html(objcsv.ReadAll))

objcsv.Close
objhtml.Close
Set objfso = Nothing

Function csv_to_html(s)
	row = Split(s,vbCrLf)
	'write the header
	tmp = "
"
	For i = 0 To UBound(row)
		field = Split(row(i),",")
		If i = 0 Then
			tmp = tmp & "
" & replace_chars(field(0)) & "	" & replace_chars(field(1)) & "
"
		Else
			tmp = tmp & "
" & replace_chars(field(0)) & "	" & replace_chars(field(1)) & "
"
		End If
	Next
	'write the footer
	tmp = tmp & "
"
	csv_to_html = tmp
End Function

Function replace_chars(s)
	replace_chars = Replace(Replace(s,"<","<"),">",">")
End Function


if (BB < 0) {           // block not set
    BB(0)               // convert entire file
    BE(File_Size)
}

// Convert special characters into entities
Replace_Block("&","&", BB, BE, BEGIN+ALL+NOERR)
Replace_Block("<","<", BB, BE, BEGIN+ALL+NOERR)
Replace_Block(">",">", BB, BE, BEGIN+ALL+NOERR)

// Convert CSV into HTML table
Goto_Pos(BB)
IT('
') IN
#80 = Cur_Pos
Goto_Pos(BE)
IT("
")
#81 = Cur_Line
IN
Goto_Pos(#80)
while (Cur_Line < #81) {
    IT("
")
    Replace_Block(",","	",Cur_Pos,EOL_Pos,ALL+NOERR)
    EOL
    IT("
")
    Line(1)
}
BB(Clear)


rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)

rem - return octal representation of n
function oct$(n = integer) = string
var s = string
s = ""
while n > 0 do
  begin
     s = chr(mod(n,8) + '0') + s
     n = n / 8
  end
end = s

rem - count in octal until overflow
var i = integer
i = 1
while i > 0 do
  begin
    print oct$(i)
    i = i + 1
  end

end


Stream from 0 foreach (i => println(i.toOctalString))


(do ((i 0 (+ i 1))) (#f) (display (number->string i 8)) (newline))


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: i is 0;
  begin
    repeat
      writeln(i radix 8);
      incr(i);
    until FALSE;
  end func;


/* NetRexx */
options replace format comments java crossref symbols nobinary

s1 = 'This is a Rexx string'
s2 = s1

s2 = s2.changestr(' ', '_')

say s1
say s2


(define (assert f msg) (if (not f) (println msg)))

(setq  s "Greetings!"  c (copy s))
(reverse c) ; Modifies c in place.

(assert (= s c) "Strings not equal.")

; another way
; Nehal-Singhal 2018-05-25

> (setq a "abcd")
"abcd"
> (setq b a)
"abcd"
> b
"abcd"
> (= a b)
true


var
  c = "This is a string"
  d = c # Copy c into a new string


: .factors ( n -- )
  2
  begin  2dup dup * >=
  while  2dup /mod swap
         if   drop  1+ 1 or    \ next odd number
         else -rot nip  dup . ." x "
         then
  repeat
  drop . ;

: main ( n -- )
  ." 1 : 1" cr
  1+ 2 ?do i . ." : " i .factors cr loop ;

15 main bye


!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Thu Jun  6 23:29:06
!
!a=./f && make $a && echo -2 | OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
! assert           1 = */           1
! assert           2 = */           2
! assert           3 = */           3
! assert           4 = */           2           2
! assert           5 = */           5
! assert           6 = */           2           3
! assert           7 = */           7
! assert           8 = */           2           2           2
! assert           9 = */           3           3
! assert          10 = */           2           5
! assert          11 = */          11
! assert          12 = */           3           2           2
! assert          13 = */          13
! assert          14 = */           2           7
! assert          15 = */           3           5
! assert          16 = */           2           2           2           2
! assert          17 = */          17
! assert          18 = */           3           2           3
! assert          19 = */          19
! assert          20 = */           2           2           5
! assert          21 = */           3           7
! assert          22 = */           2          11
! assert          23 = */          23
! assert          24 = */           3           2           2           2
! assert          25 = */           5           5
! assert          26 = */           2          13
! assert          27 = */           3           3           3
! assert          28 = */           2           2           7
! assert          29 = */          29
! assert          30 = */           5           2           3
! assert          31 = */          31
! assert          32 = */           2           2           2           2           2
! assert          33 = */           3          11
! assert          34 = */           2          17
! assert          35 = */           5           7
! assert          36 = */           3           3           2           2
! assert          37 = */          37
! assert          38 = */           2          19
! assert          39 = */           3          13
! assert          40 = */           5           2           2           2

module prime_mod

  ! sieve_table stores 0 in prime numbers, and a prime factor in composites.
  integer, dimension(:), allocatable :: sieve_table
  private :: PrimeQ

contains

  ! setup routine must be called first!
  subroutine sieve(n) ! populate sieve_table.  If n is 0 it deallocates storage, invalidating sieve_table.
    integer, intent(in) :: n
    integer :: status, i, j
    if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
    if (n .lt. 1) return
    allocate(sieve_table(n), stat=status)
    if (status .ne. 0) stop 'cannot allocate space'
    sieve_table(1) = 1
    do i=2,int(sqrt(real(n)))+1
       if (sieve_table(i) .eq. 0) then
          do j = i*i, n, i
             sieve_table(j) = i
          end do
       end if
    end do
  end subroutine sieve

  subroutine check_sieve(n)
    integer, intent(in) :: n
    if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
  end subroutine check_sieve

  logical function isPrime(p)
    integer, intent(in) :: p
    call check_sieve(p)
    isPrime = PrimeQ(p)
  end function isPrime

  logical function isComposite(p)
    integer, intent(in) :: p
    isComposite = .not. isPrime(p)
  end function isComposite

  logical function PrimeQ(p)
    integer, intent(in) :: p
    PrimeQ = sieve_table(p) .eq. 0
  end function PrimeQ

  subroutine prime_factors(p, rv, n)
    integer, intent(in) :: p ! number to factor
    integer, dimension(:), intent(out) :: rv ! the prime factors
    integer, intent(out) :: n ! number of factors returned
    integer :: i, m
    call check_sieve(p)
    m = p
    i = 1
    if (p .ne. 1) then
       do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
          rv(i) = sieve_table(m)
          m = m/rv(i)
          i = i+1
       end do
    end if
    if (i .le. size(rv)) rv(i) = m
    n = i
  end subroutine prime_factors

end module prime_mod

program count_in_factors
  use prime_mod
  integer :: i, n
  integer, dimension(8) :: factors
  call sieve(40)                ! setup
  do i=1,40
     factors = 0
     call prime_factors(i, factors, n)
     write(6,*)'assert',i,'= */',factors(:n)
  end do
  call sieve(0)                 ! release memory
end program count_in_factors


Imports Microsoft.VisualBasic.FileIO

Module Program
    Sub Main(args As String())
        Dim parser As TextFieldParser
        Try
            If args.Length > 1 Then
                parser = My.Computer.FileSystem.OpenTextFieldParser(args(1), ",")
            Else
                parser = New TextFieldParser(Console.In) With {.Delimiters = {","}}
            End If

            Dim getLines =
            Iterator Function() As IEnumerable(Of String())
                Do Until parser.EndOfData
                    Yield parser.ReadFields()
                Loop
            End Function

            Dim result = CSVTOHTML(getLines(), If(args.Length > 0, Boolean.Parse(args(0)), False))

            Console.WriteLine(result)
        Finally
            If parser IsNot Nothing Then parser.Dispose()
        End Try
    End Sub

    Function CSVTOHTML(lines As IEnumerable(Of IEnumerable(Of String)), useTHead As Boolean) As XElement
        Dim getRow = Function(row As IEnumerable(Of String)) From field In row Select <%= field %>

        CSVTOHTML =

    <%= From l In lines.Select(
            Function(line, i)
                If useTHead AndAlso i = 0 Then
                    Return
<%= getRow(line) %>

                Else
                    Return
<%= getRow(line) %>

                End If
            End Function) %>

    End Function
End Module


BEGIN

    PROCEDURE OUTOCT(N); INTEGER N;
    BEGIN
        PROCEDURE OCT(N); INTEGER N;
        BEGIN
            IF N > 0 THEN BEGIN
                OCT(N//8);
                OUTCHAR(CHAR(RANK('0')+MOD(N,8)));
            END;
        END OCT;
        IF N < 0 THEN BEGIN OUTCHAR('-'); OUTOCT(-N); END
        ELSE IF N = 0 THEN OUTCHAR('0')
        ELSE OCT(N);
    END OUTOCT;

    INTEGER I;
    WHILE I < MAXINT DO BEGIN
        OUTINT(I,0);
        OUTTEXT(" => ");
        OUTOCT(I);
        OUTIMAGE;
        I := I+1;
    END;
END.


0 to:Integer infinity do:[:n |
    n printOn:Stdout radix:8.
    Stdout cr.
]


for (var i = 0; true; i++) {
    printf("%o\n", i);
}


local
  fun count n = (print (Int.fmt StringCvt.OCT n ^ "\n"); count (n+1))
in
  val _ = count 0
end


import Foundation

func octalSuccessor(value: String) -> String {
   if value.isEmpty {
        return "1"
   } else {
     let i = value.startIndex, j = value.endIndex.predecessor()
     switch (value[j]) {
       case "0": return value[i..<j] + "1"
       case "1": return value[i..<j] + "2"
       case "2": return value[i..<j] + "3"
       case "3": return value[i..<j] + "4"
       case "4": return value[i..<j] + "5"
       case "5": return value[i..<j] + "6"
       case "6": return value[i..<j] + "7"
       case "7": return octalSuccessor(value[i..<j]) + "0"
       default:
         NSException(name:"InvalidDigit", reason: "InvalidOctalDigit", userInfo: nil).raise();
         return ""
     }
  }
}

var n = "0"
while strtoul(n, nil, 8) < UInt.max {
  println(n)
  n = octalSuccessor(n)
}


package require Tcl 8.5;   # arbitrary precision integers; we can count until we run out of memory!
while 1 {
    puts [format "%llo" [incr counter]]
}


MODULE CopyString;
TYPE
	String = ARRAY 128 OF CHAR;
VAR
	a,b: String;

BEGIN
	a := "plain string";
	COPY(a,b);
END CopyString.


' FB 1.05.0 Win64

Sub getPrimeFactors(factors() As UInteger, n As UInteger)
  If n < 2 Then Return
  Dim factor As UInteger = 2
  Do
    If n Mod factor = 0 Then
      Redim Preserve factors(0 To UBound(factors) + 1)
      factors(UBound(factors)) = factor
      n \= factor
      If n = 1 Then Return
    Else
      factor += 1
    End If
  Loop
End Sub

Dim factors() As UInteger

For i As UInteger = 1 To 20
  Print Using "##"; i;
  Print " = ";
  If i > 1 Then
    Erase factors
    getPrimeFactors factors(), i
    For j As Integer = LBound(factors) To UBound(factors)
      Print factors(j);
      If j < UBound(factors) Then Print " x ";
    Next j
    Print
  Else
    Print i
  End If
Next i

Print
Print "Press any key to quit"
Sleep


var csv =
    "Character,Speech\n" +
    "The multitude,The messiah! Show us the messiah!\n" +
    "Brians mother,<angry>Now you listen here! He's not the messiah; " +
    "he's a very naughty boy! Now go away!</angry>\n" +
    "The multitude,Who are you?\n" +
    "Brians mother,I'm his mother; that's who!\n" +
    "The multitude,Behold his mother! Behold his mother!"

var i = "   "    // indent
var ii = i + i   // double indent
var iii = ii + i // triple indent
var sb = "
\n%(i)
\n%(ii)"
for (c in csv) {
    sb = sb + ((c == "\n") ? "	\n%(i)
\n%(i)
\n%(ii)" :
               (c == ",")  ? "	\n%(ii)" :
               (c == "&")  ? "&"  :
               (c == "'")  ? "'" :
               (c == "<")  ? "<"   :
               (c == ">")  ? ">"   : c)
}
sb = sb + "	\n%(i)
\n
"
System.print(sb)
System.print()

// now using first row as a table header
sb = "
\n%(i)
\n%(ii)
\n%(iii)"
var hLength = csv.indexOf("\n") + 1  // find length of first row including CR
for (c in csv.take(hLength)) {
    sb = sb + ((c == "\n") ? "	\n%(ii)
\n%(i)
\n%(i)
\n%(ii)
\n%(iii)" :
               (c == ",")  ? "	\n%(iii)" : c)
}
for (c in csv.skip(hLength)) {
    sb = sb + ((c == "\n") ? "	\n%(ii)
\n%(ii)
\n%(iii)" :
               (c == ",")  ? "	\n%(iii)" :
               (c == "&")  ? "&"  :
               (c == "'")  ? "'" :
               (c == "<")  ? "<"   :
               (c == ">")  ? ">"   : c)
}
sb = sb + "	\n%(ii)
\n%(i)
\n
"
System.print(sb)


#!/bin/sh
num=0
while true; do
  echo $num
  num=`echo "obase=8;ibase=8;$num+1"|bc`
done


Sub CountOctal()
Dim i As Integer
i = 0
On Error GoTo OctEnd
Do
    Debug.Print Oct(i)
    i = i + 1
Loop
OctEnd:
Debug.Print "Integer overflow - count terminated"
End Sub


For i = 0 To 20
	WScript.StdOut.WriteLine Oct(i)
Next


let counter = 0
while counter >= 0
    echon printf("%o\n", counter)
    let counter += 1
endwhile


import math
fn main() {
    for i := i8(0); ; i++ {
        println("${i:o}")
        if i == math.max_i8 {
            break
        }
    }
}


NSString *original = @"Literal String";
NSString *new = [original copy];
NSString *anotherNew = [NSString stringWithString:original];
NSString *newMutable = [original mutableCopy];


i = 1
while true
{
    println[join[" x ", factorFlat[i]]]
    i = i + 1
}


package main

import "fmt"

func main() {
    fmt.Println("1: 1")
    for i := 2; ; i++ {
        fmt.Printf("%d: ", i)
        var x string
        for n, f := i, 2; n != 1; f++ {
            for m := n % f; m == 0; m = n % f {
                fmt.Print(x, f)
                x = "×"
                n /= f
            }
        }
        fmt.Println()
    }
}


<xsl:stylesheet
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xcsvt="http://www.seanbdurkin.id.au/xslt/csv-to-xml.xslt"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:xcsv="http://www.seanbdurkin.id.au/xslt/xcsv.xsd"
   version="2.0"
   exclude-result-prefixes="xsl xs xcsvt xcsv">
 <xsl:import href="csv-to-xml.xslt" />
 <xsl:output indent="yes" encoding="UTF-8" method="html" doctype-system="about:legacy-compat" />
 <xsl:import-schema schema-location="http://www.seanbdurkin.id.au/xslt/xcsv.xsd"
                    use-when="system-property('xsl:is-schema-aware')='yes'" />
 <xsl:param name="url-of-csv" as="xs:string" select="'roseta.csv'" />

 <xsl:variable name="phase-1-result">
   <xsl:call-template name="xcsvt:main" />
 </xsl:variable>

 <xsl:template match="/">

     <title>CSV to HTML translation - Extra Credit</title>

       <xsl:apply-templates select="$phase-1-result" mode="phase-2" />

 </xsl:template>

 <xsl:template match="xcsv:comma-separated-single-line-values" mode="phase-2">

    <xsl:apply-templates mode="phase-2" />

 </xsl:template>

 <xsl:template match="xcsv:row[1]" mode="phase-2">

    <xsl:apply-templates mode="phase-2" />

 </xsl:template>

 <xsl:template match="xcsv:row" mode="phase-2">

    <xsl:apply-templates mode="phase-2" />

 </xsl:template>

 <xsl:template match="xcsv:value" mode="phase-2">

    <xsl:apply-templates mode="phase-2" />

 </xsl:template>

 <xsl:template match="xcsv:notice" mode="phase-2" />

 </xsl:stylesheet>


csvData:=Data(0,Int,"Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!");

html:=csvData.pump("
\n",fcn(line){
   line.replace("&","&").replace("<","<") // <angry/> --> <angry/>
   .split(",")
   .pump("
\n","strip",String.fpM("101","  ","	\n"))+"
\n"
}) + "
";
html.println();


import "/fmt" for Conv

var i = 0
while (true) {
    System.print(Conv.oct(i))
    i = i + 1
}


include c:\cxpl\codes;     \intrinsic code declarations

proc OctOut(N);    \Output N in octal
int N;
int R;
[R:= N&7;
N:= N>>3;
if N then OctOut(N);
ChOut(0, R+^0);
];

int I;
[I:= 0;
repeat  OctOut(I); CrLf(0);
        I:= I+1;
until KeyHit or I=0;
]


const std = @import("std");
const fmt = std.fmt;
const warn = std.debug.warn;

pub fn main() void {
    var i: u8 = 0;
    var buf: [3]u8 = undefined;

    while (i < 255) : (i += 1) {
        _ = fmt.formatIntBuf(buf[0..], i, 8, false, 0); // buffer, value, base, uppercase, width
        warn("{}\n", buf);
    }
}


(define a "The String.")

; copy the string
(define b (runes->string (string->runes a)))
(print "a: " a)
(print "b: " b)
(print "b is an a: " (eq? a b))
(print "b same as a: " (equal? a b))

; another way: marshal the string
(define c (fasl-decode (fasl-encode a) #f))
(print "a: " a)
(print "c: " c)
(print "c is an a: " (eq? a c))
(print "c same as a: " (equal? a c))


def factors(number) {
    if (number == 1) {
        return [1]
    }
    def factors = []
    BigInteger value = number
    BigInteger possibleFactor = 2
    while (possibleFactor <= value) {
        if (value % possibleFactor == 0) {
            factors << possibleFactor
            value /= possibleFactor
        } else {
            possibleFactor++
        }
    }
    factors
}
Number.metaClass.factors = { factors(delegate) }

((1..10) + (6351..6359)).each { number ->
    println "$number = ${number.factors().join(' x ')}"
}


	xor a          ;LD A,0
	ld b,&40       ;how many numbers to print.
loop_showOctal:
	push af
		push af
			call ShowOctal
			ld a,' '
			call PrintChar  ;put a blank space after the value
		pop af

;;;;;;;;;;;;;;;;;;;;; this code starts a new line after every 8th output.
		ld a,b
		and &07
		dec a
		call z,NewLine
;;;;;;;;;;;;;;;;;;;;;;
	pop af
	inc a  ;next number
	djnz loop_showOctal

	jp $   ;end program

ShowOctal:
	push bc
		ld c,a
		add a
		push af
			ld a,7
			and c
			ld c,a
		pop af
		and &F0
		or c
		and &7F
	pop bc
	jp ShowHex

ShowHex:	 ;this isn't directly below ShowOctal, it's somewhere else entirely.
                 ;thanks to Keith of Chibiakumas for this routine!
	push af
		and %11110000
		ifdef gbz80
			swap a     ;game boy can use this, but Zilog Z80 cannot.
		else
			rrca
			rrca
			rrca
			rrca
		endif
		call PrintHexChar
	pop af
	and %00001111
        ;execution flows into the subroutine below, effectively calling it for us without having to actually do so.
PrintHexChar:
	or a	       ;Clear Carry Flag
	daa
	add a,&F0
	adc a,&40      ;this sequence of instructions converts hexadecimal values to ASCII.
	jp PrintChar   ;hardware-specific routine, omitted. Thanks to Keith of Chibiakumas for this one!


foreach n in ([0..]){println("%.8B".fmt(n))}


10 PRINT "DEC.  OCT."
20 FOR i=0 TO 20
30 LET o$="": LET n=i
40 LET o$=STR$ FN m(n,8)+o$
50 LET n=INT (n/8)
60 IF n>0 THEN GO TO 40
70 PRINT i;TAB 3;" = ";o$
80 NEXT i
90 STOP
100 DEF FN m(a,b)=a-INT (a/b)*b


program in,out;

type

   pString = ^string;

var

   s1,s2 : string ;
   pStr  : pString ;

begin

   /* direct copy */
   s1 := 'Now is the time for all good men to come to the aid of their party.'
   s2 := s1 ;

   writeln(s1);
   writeln(s2);

   /* By Reference */
   pStr := @s1 ;
   writeln(pStr^);

   pStr := @s2 ;
   writeln(pStr^);

end;


my $original = 'Hello.';
my $new = $original;
$new = 'Goodbye.';
print "$original\n";   # prints "Hello."


string one = "feed"
string two = one     -- (two becomes "feed", one remains "feed")
two[2..3] = "oo"     -- (two becomes "food", one remains "feed")
one[1] = 'n'         -- (two remains "food", one becomes "need")
?{one,two}


import Data.List (intercalate)

showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
-- Pointfree form
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)


go =>
  S1 = "string",
  println(s1=S1),
  S2 = S1,
  S2[1] := 'x', % also changes S1
  println(s1=S1),
  println(s2=S2),
  nl,

  S3 = "string",
  S4 = copy_term(S3),
  S4[1] := 'x', % no change of S3
  println(s3=S3),
  println(s4=S4),

  nl.


(setq Str1 "abcdef")
(setq Str2 Str1)                       # Create a reference to that symbol
(setq Str3 (name Str1))                # Create new symbol with name "abcdef"


int main(){
   string hi = "Hello World.";
   string ih = hi;
}


   declare (s1, s2) character (20) varying;
   s1 = 'now is the time';
   s2 = s1;


procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
   writes(i," : [")
   every writes(" ",!f|"]\n")
   }
end

link factors


100 PROGRAM "Factors.bas"
110 FOR I=1 TO 30
120   PRINT I;"= ";FACTORS$(I)
130 NEXT
140 DEF FACTORS$(N)
150   LET F$=""
160   IF N=1 THEN
170     LET FACTORS$="1"
180   ELSE
190     LET P=2
200     DO WHILE P<=N
210       IF MOD(N,P)=0 THEN
220         LET F$=F$&STR$(P)&"*"
230         LET N=INT(N/P)
240       ELSE
250         LET P=P+1
260       END IF
270     LOOP
280     LET FACTORS$=F$(1:LEN(F$)-1)
290   END IF
300 END DEF


vars src, dst;
'Hello' -> src;
copy(src) -> dst;


editvar /newvar /value=a /userinput=1 /title=Enter a string to be copied:
editvar /newvar /value=b /userinput=1 /title=Enter current directory of the string:
editvar /newvar /value=c /userinput=1 /title=Enter file to copy to:
copy -a- from -b- to -c-


?- A = "A test string", A = B.
A = B, B = "A test string".


public class CountingInFactors{
    public static void main(String[] args){
        for(int i = 1; i<= 10; i++){
            System.out.println(i + " = "+ countInFactors(i));
        }

        for(int i = 9991; i <= 10000; i++){
        	System.out.println(i + " = "+ countInFactors(i));
        }
    }

    private static String countInFactors(int n){
        if(n == 1) return "1";

        StringBuilder sb = new StringBuilder();

        n = checkFactor(2, n, sb);
        if(n == 1) return sb.toString();

        n = checkFactor(3, n, sb);
        if(n == 1) return sb.toString();

        for(int i = 5; i <= n; i+= 2){
            if(i % 3 == 0)continue;

            n = checkFactor(i, n, sb);
            if(n == 1)break;
        }

        return sb.toString();
    }

    private static int checkFactor(int mult, int n, StringBuilder sb){
        while(n % mult == 0 ){
            if(sb.length() > 0) sb.append(" x ");
            sb.append(mult);
            n /= mult;
        }
        return n;
    }
}


>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True


#lang racket

(let* ([s1 "Hey"]
       [s2 s1]
       [s3 (string-copy s1)]
       [s4 s3])
  (printf "s1 and s2 refer to ~a strings\n"
          (if (eq? s1 s2) "the same" "different")) ; same
  (printf "s1 and s3 refer to ~a strings\n"
          (if (eq? s1 s3) "the same" "different")) ; different
  (printf "s3 and s4 refer to ~a strings\n"
          (if (eq? s3 s4) "the same" "different")) ; same
  (string-fill! s3 #\!)
  (printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!"


for(i = 1; i <= 10; i++)
    console.log(i + " : " + factor(i).join(" x "));

function factor(n) {
    var factors = [];
    if (n == 1) return [1];
    for(p = 2; p <= n; ) {
	if((n % p) == 0) {
	    factors[factors.length] = p;
	    n /= p;
	}
	else p++;
    }
    return factors;
}


# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);

# Input: a non-negative integer determining when to stop
def count_in_factors:
  "1: 1",
  (range(2;.) | "\(.): \([factors] | join("x"))");

def count_in_factors($m;$n):
  if  . == 1 then  "1: 1" else empty end,
  (range($m;$n) | "\(.): \([factors] | join("x"))");


my $original = 'Hello.';
my $copy = $original;
say $copy;            # prints "Hello."
$copy = 'Goodbye.';
say $copy;            # prints "Goodbye."
say $original;        # prints "Hello."


rebol [
    Title: "String Copy"
    URL: http://rosettacode.org/wiki/Copy_a_string
]

x: y: "Testing."
y/2: #"X"
print ["Both variables reference same string:" mold x "," mold y]

x: "Slackeriffic!"
print ["Now reference different strings:" mold x "," mold y]

y: copy x        ; String copy here!
y/3: #"X"        ; Modify string.
print ["x copied to y, then modified:" mold x "," mold y]

y: copy/part x 7 ; Copy only the first part of y to x.
print ["Partial copy:" mold x "," mold y]

y: copy/part  skip x 2  3
print ["Partial copy from offset:" mold x "," mold y]


Red[]
originalString: "hello wordl"
copiedString: originalString
; OR
copiedString2: copy originalString


using Primes, Printf
function strfactor(n::Integer)
    n > -2 || return "-1 × " * strfactor(-n)
    isprime(n) || n < 2 && return dec(n)
    f = factor(Vector{typeof(n)}, n)
    return join(f, " × ")
end

lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
    @printf("%5d = %s\n", n, strfactor(n))
end


// version 1.1.2

fun isPrime(n: Int) : Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun getPrimeFactors(n: Int): List<Int> {
    val factors = mutableListOf<Int>()
    if (n < 1) return factors
    if (n == 1 || isPrime(n)) {
        factors.add(n)
        return factors
    }
    var factor = 2
    var nn = n
    while (true) {
        if (nn % factor == 0) {
            factors.add(factor)
            nn /= factor
            if (nn == 1) return factors
            if (isPrime(nn)) factor = nn
        }
        else if (factor >= 3) factor += 2
        else factor = 3
    }
}

fun main(args: Array<String>) {
    val list = (MutableList(22) { it + 1 } + 2144) + 6358
    for (i in list)
        println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}")
}


cStr1 = "Hello!"   # create original string
cStr2 = cStr1      # make new string from original


>> s1 = "A string"
A string
>> s2 = s1
A string


set "$string1" to "This is a string"
set "$string2" to "$string1"
* "&$string2&"


original = "hello"
reference = original          # copies reference
copy1 = original.dup          # instance of original.class
copy2 = String.new(original)  # instance of String

original << " world!"         # append
p reference                   #=> "hello world!"
p copy1                       #=> "hello"
p copy2                       #=> "hello"


'see Run BASIC solution
for i = 1000 to 1016
  print i;" = "; factorial$(i)
next
wait
function factorial$(num)
 if num = 1 then factorial$ = "1"
 fct = 2
 while fct <= num
 if (num mod fct) = 0 then
   factorial$ = factorial$ ; x$ ; fct
   x$  = " x "
   num = num / fct
  else
   fct = fct + 1
 end if
 wend
end function


function factorize( n )
    if n == 1 then return {1} end

    local k = 2
    res = {}
    while n > 1 do
	while n % k == 0 do
	    res[#res+1] = k
 	    n = n / k
	end
 	k = k + 1
    end
    return res
end

for i = 1, 22 do
    io.write( i, ":  " )
    fac = factorize( i )
    io.write( fac[1] )
    for j = 2, #fac do
	io.write( " * ", fac[j] )
    end
    print ""
end


origString$ = "Hello!"     ' create original string
newString$  = origString$  ' make new strig from original


fn main() {
    let s1 = "A String";
    let mut s2 = s1;

    s2 = "Another String";

    println!("s1 = {}, s2 = {}", s1, s2);
}


class MAIN is
  main is
    s  ::= "a string";
    s1 ::= s;
    -- s1 is a copy
  end;
end;


  val src = "Hello"
  // Its actually not a copy but a reference
  // That is not a problem because String is immutable
  // In fact its a feature
  val des = src
  assert(src eq des) // Proves the same reference is used.
  // To make a real copy makes no sense.
  // Actually its hard to make a copy, the compiler is too smart.
  // mkString, toString makes also not a real copy
  val cop = src.mkString.toString
  assert((src eq cop))                 // Still no copyed image
  val copy = src.reverse.reverse       // Finally double reverse makes a copy
  assert(src == copy && !(src eq copy))// Prove, but it really makes no sense.


var string: dest is "";

dest := "Hello";


Module Count_in_factors    {
	Inventory [email protected], [email protected]
	IsPrime=lambda  Known1 (x as decimal) -> {
		=0=1
		if exist(Known1, x) then =1=1 : exit
		if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x  : =1=1
		Break}
		if frac(x/2) else exit
		if frac(x/3) else exit
		x1=sqrt(x):d = [email protected]
		{if frac(x/d ) else exit
			d += 2: if d>x1 then Append Known1, x : =1=1 : exit
			if frac(x/d) else exit
			d += 4: if d<= x1 else Append Known1, x :  =1=1: exit
			loop
		}
	}
	decompose=lambda IsPrime (n as decimal) -> {
		Factors=(,)
		{
			[email protected]
			While frac(n/k)=0
				n/=k
				Append Factors, (k,)
			End While
			if n=1 then exit
			k++
			While frac(n/k)=0
				n/=k
				Append Factors, (k,)
			End While
			if n=1 then exit
			{
				k+=2
				while not isprime(k) {k+=2}
				While frac(n/k)=0
					n/=k : Append Factors, (k,)
				End While
				if n=1 then exit
				loop
			}
		}
		=Factors
	}
	fold=lambda (a, f$)->{
		Push if$(len(f$)=0->f$, f$+"x")+str$(a,"")
	}
	Print "1=1"
	[email protected]
	do
		i++
		Print str$(i,"")+"="+Decompose(i)#fold$(fold,"")
	always
}
Count_in_factors


(* In SenseTalk, assignments normally always make copies of values. *)

put "glorious" into myWord
put myWord into yourWord

(* Assignments can also be made by reference if desired. *)

put a reference to myWord into myRef
set another to refer to myRef

put "ly" after myWord
put "in" before another

put "myWord:   " & myWord
put "yourWord: " & yourWord
put "myRef:    " & myRef
put "another:  " & another


var original = "hello";               # new String object
var reference = original;             # points at the original object
var copy1 = String.new(original);     # creates a new String object
var copy2 = original+'';              # ==//==


BEGIN
    TEXT ORIGINAL, REFERENCE, COPY1;

    ORIGINAL :- "THIS IS CONSTANT TEXT";
    ORIGINAL.SETPOS(1);
    REFERENCE :- ORIGINAL;

! RUN TIME ERROR:
!   ORIGINAL.PUTCHAR('X');
!   "copy-a-string.sim", line 9: ./copy-a-string: Putchar: Constant text object
;

    OUTTEXT(ORIGINAL);
    OUTIMAGE;

    ! CONTENT EQUAL? => T ;
    OUTTEXT(IF ORIGINAL = REFERENCE THEN "T" ELSE "F");
    OUTIMAGE;

    ! SAME TEXT OBJECT? => T ;
    OUTTEXT(IF ORIGINAL == REFERENCE THEN "T" ELSE "F");
    OUTIMAGE;

    COPY1 :- COPY(ORIGINAL);
    COPY1.SETPOS(1);
    COPY1.PUTCHAR('X');
    OUTTEXT(COPY1);
    OUTIMAGE;
END;


[ | :s | s == s copy] applyTo: {'hello'}. "returns False"


|s1 s2|
"bind the var s1 to the object string on the right"
s1 := 'i am a string'.
"bind the var s2 to the same object..."
s2 := s1.
"bind s2 to a copy of the object bound to s1"
s2 := (s1 copy).


factorNum := proc(n)
	local i, j, firstNum;
	if n = 1 then
		printf("%a", 1);
	end if;
	firstNum := true:
	for i in ifactors(n)[2] do
		for j to i[2] do
			if firstNum then
				printf ("%a", i[1]);
				firstNum := false:
			else
				printf(" x %a", i[1]);
			end if;
		end do;
	end do;
	printf("\n");
	return NULL;
end proc:

for i from 1 to 10 do
	printf("%2a: ", i);
	factorNum(i);
end do;


n = 2;
While[n < 100,
 Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
 n++]


/* NetRexx */
options replace format comments java crossref symbols nobinary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method factor(val) public static
  rv = 1
  if val > 1 then do
    rv = ''
    loop n_ = val until n_ = 1
      parse checkFactor(2, n_, rv) n_ rv
      if n_ = 1 then leave n_
      parse checkFactor(3, n_, rv) n_ rv
      if n_ = 1 then leave n_
      loop m_ = 5 to n_ by 2 until n_ = 1
        if m_ // 3 = 0 then iterate m_
        parse checkFactor(m_, n_, rv) n_ rv
        end m_
      end n_
    end
  return rv

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method checkFactor(mult = long, n_ = long, fac) private static binary
  msym = 'x'
  loop while n_ // mult = 0
    fac = fac msym mult
    n_ = n_ % mult
    end
  fac = (fac.strip).strip('l', msym).space
  return n_ fac

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  -- input is a list of pairs of numbers - no checking is done
  if arg = '' then arg = '1 11    89 101    1000 1020    10000 10010'
  loop while arg \= ''
    parse arg lv rv arg
    say
    say '-'.copies(60)
    say lv.right(8) 'to' rv
    say '-'.copies(60)
    loop fv = lv to rv
      fac = factor(fv)
      pv = ''
      if fac.words = 1 & fac \= 1 then pv = '<prime>'
      say fv.right(8) '=' fac pv
      end fv
    end
  return


* copy a to b
          b = a = "test"
          output = a
          output = b
* change the copy
          b "t" = "T"
          output = b
end


val src = "Hello";
val srcCopy = CharArray.array (size src, #"x"); (* 'x' is just dummy character *)
CharArray.copyVec {src = src, dst = srcCopy, di = 0};
src = CharArray.vector srcCopy; (* evaluates to true *)


" hello" is-data a
a string.clone is-data b


var primes = newSeq[int]()

proc getPrime(idx: int): int =
  if idx >= primes.len:
    if primes.len == 0:
      primes.add 2
      primes.add 3

    var last = primes[primes.high]
    while idx >= primes.len:
      last += 2
      for i, p in primes:
        if p * p > last:
          primes.add last
          break
        if last mod p == 0:
          break

  return primes[idx]

for x in 1 ..< int32.high.int:
  stdout.write x, " = "
  var n = x
  var first = true

  for i in 0 ..< int32.high:
    let p = getPrime(i)
    while n mod p == 0:
      n = n div p
      if not first: stdout.write " x "
      first = false
      stdout.write p

    if n <= p * p:
      break

  if first > 0: echo n
  elif n > 1:   echo " x ", n
  else:         echo ""


class CountingInFactors {
  function : Main(args : String[]) ~ Nil {
    for(i := 1; i <= 10; i += 1;){
    count := CountInFactors(i);
    ("{$i} = {$count}")->PrintLine();
  };

  for(i := 9991; i <= 10000; i += 1;){
    count := CountInFactors(i);
    ("{$i} = {$count}")->PrintLine();
    };
  }

  function : CountInFactors(n : Int) ~ String {
    if(n = 1) {
      return "1";
    };

    sb := "";
    n := CheckFactor(2, n, sb);
    if(n = 1) {
      return sb;
    };

    n := CheckFactor(3, n, sb);
    if(n = 1) {
      return sb;
    };

    for(i := 5; i <= n; i += 2;) {
      if(i % 3 <> 0) {
        n := CheckFactor(i, n, sb);
        if(n = 1) {
          break;
        };
      };
    };

    return sb;
  }

  function : CheckFactor(mult : Int, n : Int, sb : String) ~ Int {
    while(n % mult = 0 ) {
      if(sb->Size() > 0) {
        sb->Append(" x ");
      };
      sb->Append(mult);
      n /= mult;
    };

    return n;
  }
}


#lang transd

MainModule : {
  _start: (λ
    (with s "Hello!" s1 "" s2 ""
        (= s1 s)             // duplication of 's' content
        (rebind s2 s)        // another reference to 's'
        (= s "Good bye!")
        (lout s)
        (lout s1)
        (lout s2)
    )
  )
}


foo="Hello"
bar=$foo    # This is a copy of the string


open Big_int

let prime_decomposition x =
  let rec inner c p =
    if lt_big_int p (square_big_int c) then
      [p]
    else if eq_big_int (mod_big_int p c) zero_big_int then
      c :: inner c (div_big_int p c)
    else
      inner (succ_big_int c) p
  in
  inner (succ_big_int (succ_big_int zero_big_int)) x

let () =
  let rec aux v =
    let ps = prime_decomposition v in
    print_string (string_of_big_int v);
    print_string " = ";
    print_endline (String.concat " x " (List.map string_of_big_int ps));
    aux (succ_big_int v)
  in
  aux unit_big_int


for (n = 1:20)
    printf ("%i: ", n)
    printf ("%i ", factor (n))
    printf ("\n")
endfor


Sub copystring()
    a = "Hello World!"
    b = a
    a = "I'm gone"
    Debug.Print b
    Debug.Print a
End Sub


let str1 = "original string"
let str2 = str1
let str1 = "new string"

echo "String 1:" str1
echo "String 2:" str2


'Immutable Strings
Dim a = "Test string"
Dim b = a 'reference to same string
Dim c = New String(a.ToCharArray) 'new string, normally not used

'Mutable Strings
Dim x As New Text.StringBuilder("Test string")
Dim y = x 'reference
Dim z = New Text.StringBuilder(x.ToString) 'new string


var s = "wren"
var t = s
System.print("Are 's' and 't' equal? %(s == t)")


section .data
    string db "Hello World", 0

section .bss
    string2 resb 12

section .text
global _main
_main:
    mov ecx, 0
    looping:
        mov al, [string + ecx]
        mov [string2 + ecx], al
        inc ecx
        cmp al, 0 ;copy until we find the terminating 0
        je end
        jmp looping
    end:
        xor eax, eax
        ret


option casemap:none
option literals:on

printf    proto :dword, :VARARG
exit      proto :dword

.data
  s   db "Goodbye, World!",0

.data?
  d   db 20 dup (?)
  dp  dq ?
  tb  dd ?

.code
main proc
  lea rsi, s                    ;; Put the address of var S into the source index(RSI)
  xor rcx, rcx                  ;; Zero out RCX
  _getsize:
    inc rcx                     ;; Advanced the index by 1
    cmp byte ptr [rsi+rcx],0    ;; check the current byte for terminating 0
    jne _getsize                ;; nope, jump back and check again

  mov tb, ecx                   ;; tb = Total bytes, Keep a copy of the size of the string
  lea rsi, s                    ;; Copy the address of s into the source index(rsi)
  lea rdi, d                    ;; Copy the address of d into the destination index(rdi)
  rep movsb                     ;; Copy bytes from ESI to EDI until RCX is 0

  lea rax, s                    ;; Get the address of S
  mov dp, rax                   ;; Copy it from RAX to dp

  mov rbx,rdi                   ;; Make a copy of RDI, cause over writes due to ABI call args T_T
  invoke printf, CSTR("-> s (0x%x) = %s",10), rsi, addr s
  invoke printf, CSTR("-> d (0x%x) = %s",10), rbx, addr d
  invoke printf, CSTR("-> dp (0x%x) = %s",10), addr dp, dp
  invoke printf, CSTR("-> bytes copied: %i",10), tb
  xor rsi, rsi
  call exit
  ret
main endp

end


proc StrCopy(A, B);     \Copy string: A --> B
char A, B;              \Strings: B must already have enough space "Reserved"
int  I;                 \Beware if strings overlap
for I:= 0 to -1>>1-1 do
    [B(I):= A(I);
    if A(I) >= $80 then return
    ];

char S1, S2, S3(13);
[S1:= "Hello, world!";  \S1 now points to the string
S2:= S1;                \S2 now also points to the string
StrCopy(S1, S3);        \S3 points to a separate copy of the string
]


ld hl,MyString
ld (PointerVariable),hl

MyString:          ;assembler equates this label to a memory location at compile time
byte "Hello",0

PointerVariable:
word 0             ;placeholder for the address of the above string, gets written to by the code above.


const std = @import("std");

const debug = std.debug;
const mem = std.mem;

test "copy a string" {
    const source = "A string.";

    // Variable `dest1` will have the same type as `source`, which is
    // `*const [9:0]u8`.
    const dest1 = source;

    // Variable `dest2`'s type is [9]u8.
    //
    // The difference between the two is that `dest1` string is null-terminated,
    // while `dest2` is not.
    var dest2: [source.len]u8 = undefined;
    mem.copy(u8, dest2[0..], source[0..]);

    debug.assert(mem.eql(u8, dest1[0..], "A string."));
    debug.assert(mem.eql(u8, dest2[0..], "A string."));
}


program CountInFactors(output);

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}

type
  TdynArray = array of integer;

function factorize(number: integer): TdynArray;
var
  k: integer;
begin
  if number = 1 then
  begin
    setlength(Result, 1);
    Result[0] := 1
  end
  else
  begin
    k := 2;
    while number > 1 do
    begin
      while number mod k = 0 do
      begin
        setlength(Result, length(Result) + 1);
        Result[high(Result)] := k;
        number := number div k;
      end;
      inc(k);
    end;
  end
end;

var
  i, j: integer;
  fac: TdynArray;

begin
  for i := 1 to 22 do
  begin
    write(i, ':  ' );
    fac := factorize(i);
    write(fac[0]);
    for j := 1 to high(fac) do
      write(' * ', fac[j]);
    writeln;
  end;
end.


module Main;
var
	s,r: string;
	c: array 60 of char;
begin
	s := "plain string";r := s; writeln(s);
	(* copy string to array of char *)
	copy(s,c);c[0] := 'P';
	(* copy array of char to string *)
	copy(c,r);writeln(r);
end Main.


var a
var b
a = "World"
b = a
a = "Hello"
print (a," ",b)


10 LET a$ = "Hello": REM a$ is the original string
20 LET b$ = a$: REM b$ is the copy


#include <hopper.h>
main:
   s = "string to copy"
   t = s
   {s,"\n",t}println
exit(0)


with javascript_semantics
procedure factorise(integer n)
    sequence res = prime_factors(n,true)
    res = join(apply(res,sprint)," x ")
    printf(1,"%2d: %s\n",{n,res})
end procedure

papply(tagset(10)&{2144,1000000000},factorise)


(de factor (N)
   (make
      (let (D 2  L (1 2 2 . (4 2 4 2 4 6 2 6 .))  M (sqrt N))
         (while (>= M D)
            (if (=0 (% N D))
               (setq M (sqrt (setq N (/ N (link D)))))
               (inc 'D (pop 'L)) ) )
         (link N) ) ) )

(for N 20
   (prinl N ": " (glue " * " (factor N))) )


cnt: procedure options (main);
	declare (i, k, n) fixed binary;
	declare first bit (1) aligned;

   do n = 1 to 40;
      put skip list (n || ' =');
      k = n; first = '1'b;
repeat:
      do i = 2 to k-1;
		if mod(k, i) = 0 then
			do;
				k = k/i;
                                if ^first then put edit (' x ')(A);
                                first = '0'b;
                                put edit (trim(i)) (A);
				go to repeat;
			end;

	end;
        if ^first then put edit (' x ')(A);
        if n = 1 then i = 1;
        put edit (trim(i)) (A);
   end;
end cnt;


function eratosthenes ($n) {
    if($n -ge 1){
        $prime = @(1..($n+1) | foreach{$true})
        $prime[1] = $false
        $m = [Math]::Floor([Math]::Sqrt($n))
        for($i = 2; $i -le $m; $i++) {
            if($prime[$i]) {
                for($j = $i*$i; $j -le $n; $j += $i) {
                    $prime[$j] = $false
                }
            }
        }
        1..$n | where{$prime[$_]}
    } else {
        "$n must be equal or greater than 1"
    }
}
function prime-decomposition ($n) {
    $array = eratosthenes $n
    $prime = @()
    foreach($p in $array) {
        while($n%$p -eq 0) {
            $n /= $p
            $prime += @($p)
        }
    }
    $prime
}
$OFS = " x "
"$(prime-decomposition  2144)"
"$(prime-decomposition  100)"
"$(prime-decomposition  12)"


Procedure Factorize(Number, List Factors())
  Protected I = 3, Max
  ClearList(Factors())
  While Number % 2 = 0
    AddElement(Factors())
    Factors() = 2
    Number / 2
  Wend
  Max = Number
  While I <= Max And Number > 1
    While Number % I = 0
      AddElement(Factors())
      Factors() = I
      Number / I
    Wend
    I + 2
  Wend
EndProcedure

If OpenConsole()
  NewList n()
  For a=1 To 20
    text$=RSet(Str(a),2)+"= "
    Factorize(a,n())
    If ListSize(n())
      ResetList(n())
      While NextElement(n())
        text$ + Str(n())
        If ListSize(n())-ListIndex(n())>1
          text$ + "*"
        EndIf
      Wend
    Else
      text$+Str(a) ; To handle the '1', which is not really a prime...
    EndIf
    PrintN(text$)
  Next a
EndIf


from functools import lru_cache

primes = [2, 3, 5, 7, 11, 13, 17]    # Will be extended

@lru_cache(maxsize=2000)
def pfactor(n):
    if n == 1:
        return [1]
    n2 = n // 2 + 1
    for p in primes:
        if p <= n2:
            d, m = divmod(n, p)
            if m == 0:
                if d > 1:
                    return [p] + pfactor(d)
                else:
                    return [p]
        else:
            if n > primes[-1]:
                primes.append(n)
            return [n]

if __name__ == '__main__':
    mx = 5000
    for n in range(1, mx + 1):
        factors = pfactor(n)
        if n <= 10 or n >= mx - 20:
            print( '%4i %5s %s' % (n,
                                   '' if factors != [n] or n == 1 else 'prime',
                                   'x'.join(str(i) for i in factors)) )
        if n == 11:
            print('...')

    print('\nNumber of primes gathered up to', n, 'is', len(primes))
    print(pfactor.cache_info())


  [ [] swap
    dup times
    [ [ dup i^ 2 + /mod
        0 = while
        nip dip
          [ i^ 2 + join ]
        again ]
      drop
      dup 1 = if conclude ]
    drop ]                     is primefactors    ( n --> [ )

  [ 1 dup echo cr
    [ 1+ dup primefactors
      witheach
        [ echo
          i if [ say " x " ] ]
      cr again ] ]             is countinfactors (   -->   )

countinfactors


#initially I created a function which returns prime factors then I have created another function counts in the factors and #prints the values.

findfactors <- function(num) {
  x <- c()
  p1<- 2
  p2 <- 3
  everyprime <- num
  while( everyprime != 1 ) {
    while( everyprime%%p1 == 0 ) {
      x <- c(x, p1)
      everyprime <- floor(everyprime/ p1)
    }
    p1 <- p2
    p2 <- p2 + 2
  }
  x
}
count_in_factors=function(x){
  primes=findfactors(x)
  x=c(1)
  for (i in 1:length(primes)) {
    x=paste(primes[i],"x",x)
  }
  return(x)
}
count_in_factors(72)


#lang typed/racket

(require math/number-theory)

(define (factorise-as-primes [n : Natural])
  (if
   (= n 1)
   '(1)
   (let ((F (factorize n)))
     (append*
      (for/list : (Listof (Listof Natural))
        ((f (in-list F)))
        (make-list (second f) (first f)))))))

(define (factor-count [start-inc : Natural] [end-inc : Natural])
  (for ((i : Natural (in-range start-inc (add1 end-inc))))
    (define f (string-join (map number->string (factorise-as-primes i)) " × "))
    (printf "~a:\t~a~%" i f)))

(factor-count 1 22)
(factor-count 2140 2150)
; tb


constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;

multi factors(1) { 1 }
multi factors(Int $remainder is copy) {
  gather for @primes -> $factor {

    # if remainder < factor², we're done
    if $factor * $factor > $remainder {
      take $remainder if $remainder > 1;
      last;
    }

    # How many times can we divide by this prime?
    while $remainder %% $factor {
        take $factor;
        last if ($remainder div= $factor) === 1;
    }
  }
}

say "$_: ", factors($_).join(" × ") for 1..*;


/*REXX program lists the prime factors of a specified integer  (or a range of integers).*/
@.=left('', 8);  @.0="{unity} ";  @.1='[prime] ' /*some tags  and  handy-dandy literals.*/
parse arg LO HI @ .                              /*get optional arguments from the C.L. */
if LO=='' | LO==","  then do; LO=1; HI=40;  end  /*Not specified?  Then use the default.*/
if HI=='' | HI==","  then HI= LO                 /* "      "         "   "   "     "    */
if  @==''            then  @= 'x'                /* "      "         "   "   "     "    */
if length(@)\==1  then @= x2c(@)                 /*Not length 1?  Then use hexadecimal. */
tell= (HI>0)                                     /*if  HIGH  is positive, then show #'s.*/
HI= abs(HI)                                      /*use the absolute value for  HIGH.    */
w= length(HI)                                    /*get maximum width for pretty output. */
numeric digits max(9, w + 1)                     /*maybe bump the precision of numbers. */
#= 0                                             /*the number of primes found (so far). */
     do n=abs(LO)  to HI;          f= factr(n)   /*process a single number  or  a range.*/
     p= words( translate(f, ,@) )  -  (n==1)     /*P:  is the number of prime factors.  */
     if p==1  then #= # + 1                      /*bump the primes counter (exclude N=1)*/
     if tell  then say right(n, w)  '='  @.p  f  /*display if a prime, plus its factors.*/
     end   /*n*/
say
say right(#, w)          ' primes found.'        /*display the number of primes found.  */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure expose @; parse arg z 1 n,$;  if z<2  then return z   /*is Z too small?*/
           do  while z//2==0;   $= $||@||2;   z= z%2;    end  /*maybe add factor of   2 */
           do  while z//3==0;   $= $||@||3;   z= z%3;    end  /*  "    "     "    "   3 */
           do  while z//5==0;   $= $||@||5;   z= z%5;    end  /*  "    "     "    "   5 */
           do  while z//7==0;   $= $||@||7;   z= z%7;    end  /*  "    "     "    "   7 */

         do j=11  by 6  while j<=z               /*insure that  J  isn't divisible by 3.*/
         parse var j  ''  -1  _                  /*get the last decimal digit of  J.    */
         if _\==5  then do while  z//j==0;  $=$||@||j;  z= z%j;  end   /*maybe reduce Z.*/
         if _ ==3  then iterate                  /*Next # ÷ by 5?  Skip.     ___        */
         if j*j>n  then leave                    /*are we higher than the   √ N   ?     */
         y= j + 2                                /*obtain the next odd divisor.         */
                        do while  z//y==0;  $=$||@||y;  z= z%y;   end  /*maybe reduce Z.*/
         end   /*j*/
       if z==1  then return substr($,       1+length(@) )  /*Is residual=1?  Don't add 1*/
                     return substr($||@||z, 1+length(@) )  /*elide superfluous header.  */


for i = 1 to 20
    see "" + i + " = " + factors(i) + nl
next

func factors n
     f = ""
     if n = 1 return "1" ok
     p = 2
     while p <= n
           if (n % p) = 0
              f += string(p) + " x "
              n = n/p
           else p += 1 ok
     end
     return left(f, len(f) - 3)


require 'optparse'
require 'prime'

maximum = 10
OptionParser.new do |o|
  o.banner = "Usage: #{File.basename $0} [-m MAXIMUM]"
  o.on("-m MAXIMUM", Integer,
       "Count up to MAXIMUM [#{maximum}]") { |m| maximum = m }
  o.parse! rescue ($stderr.puts $!, o; exit 1)
  ($stderr.puts o; exit 1) unless ARGV.size == 0
end

# 1 has no prime factors
puts "1 is 1" unless maximum < 1

2.upto(maximum) do |i|
  # i is 504 => i.prime_division is [[2, 3], [3, 2], [7, 1]]
  f = i.prime_division.map! do |factor, exponent|
    # convert [2, 3] to "2 x 2 x 2"
    ([factor] * exponent).join " x "
  end.join " x "
  puts "#{i} is #{f}"
end


for i = 1000 to 1016
  print i;" = "; factorial$(i)
next
wait
function factorial$(num)
 if num = 1 then factorial$ = "1"
 fct = 2
 while fct <= num
 if (num mod fct) = 0 then
   factorial$ = factorial$ ; x$ ; fct
   x$  = " x "
   num = num / fct
  else
   fct = fct + 1
 end if
 wend
end function