Fractran: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 50: Line 50:
{{trans|D}}
{{trans|D}}


<lang 11l>F fractran(prog, =val, limit)
<syntaxhighlight lang="11l">F fractran(prog, =val, limit)
V fracts = prog.split(‘ ’).map(p -> p.split(‘/’).map(i -> Int(i)))
V fracts = prog.split(‘ ’).map(p -> p.split(‘/’).map(i -> Int(i)))
[Float] r
[Float] r
Line 61: Line 61:
R r
R r


print(fractran(‘17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1’, 2, 15))</lang>
print(fractran(‘17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1’, 2, 15))</syntaxhighlight>


{{out}}
{{out}}
Line 69: Line 69:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* FRACTRAN 17/02/2019
<syntaxhighlight lang="360asm">* FRACTRAN 17/02/2019
FRACTRAN CSECT
FRACTRAN CSECT
USING FRACTRAN,R13 base register
USING FRACTRAN,R13 base register
Line 116: Line 116:
XDEC DS CL12 temp
XDEC DS CL12 temp
REGEQU
REGEQU
END FRACTRAN</lang>
END FRACTRAN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 136: Line 136:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Fractan is
procedure Fractan is
Line 178: Line 178:
2, 15);
2, 15);
-- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116"
-- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116"
end Fractan;</lang>
end Fractan;</syntaxhighlight>


{{out}}
{{out}}
Line 185: Line 185:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># as the numbers required for finding the first 20 primes are quite large, #
<syntaxhighlight lang="algol68"># as the numbers required for finding the first 20 primes are quite large, #
# we use Algol 68G's LONG LONG INT with a precision of 100 digits #
# we use Algol 68G's LONG LONG INT with a precision of 100 digits #
PR precision 100 PR
PR precision 100 PR
Line 258: Line 258:
print( ( whole( pos, -12 ) + " " + whole( power of 2, -6 ) + " (" + whole( n OF pf, 0 ) + ")", newline ) )
print( ( whole( pos, -12 ) + " " + whole( power of 2, -6 ) + " (" + whole( n OF pf, 0 ) + ")", newline ) )
FI
FI
OD</lang>
OD</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 286: Line 286:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>n := 2, steplimit := 15, numerator := [], denominator := []
<syntaxhighlight lang="autohotkey">n := 2, steplimit := 15, numerator := [], denominator := []
s := "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"
s := "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"


Line 309: Line 309:
}
}
break
break
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>0: 2
<pre>0: 2
Line 334: Line 334:
the "factor" command allows one to decrypt the data. For example, the program below computes the product of a and b, entered as 2<sup>a</sup> and 3<sup>b</sup>, the product being 5<sup>a×b</sup>. Two arrays are computed from the fractions, ns for the numerators and ds for the denominators. Then, every time where the multiplication by a fraction yields an integer, the output of the division is stored into a csv file in factored format.
the "factor" command allows one to decrypt the data. For example, the program below computes the product of a and b, entered as 2<sup>a</sup> and 3<sup>b</sup>, the product being 5<sup>a×b</sup>. Two arrays are computed from the fractions, ns for the numerators and ds for the denominators. Then, every time where the multiplication by a fraction yields an integer, the output of the division is stored into a csv file in factored format.


<lang bash>#! /bin/bash
<syntaxhighlight lang="bash">#! /bin/bash
program="1/1 455/33 11/13 1/11 3/7 11/2 1/3"
program="1/1 455/33 11/13 1/11 3/7 11/2 1/3"
echo $program | tr " " "\n" | cut -d"/" -f1 | tr "\n" " " > "data"
echo $program | tr " " "\n" | cut -d"/" -f1 | tr "\n" " " > "data"
Line 353: Line 353:
let "t=$t+1"
let "t=$t+1"
done
done
</syntaxhighlight>
</lang>


If at the beginning n=72=2<sup>3</sup>×3<sup>2</sup> (to compute 3×2), the steps of the computation look like this:
If at the beginning n=72=2<sup>3</sup>×3<sup>2</sup> (to compute 3×2), the steps of the computation look like this:
Line 390: Line 390:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion


Line 445: Line 445:
echo.
echo.
pause
pause
exit /b 1</lang>
exit /b 1</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Input:
<pre>Input:
Line 479: Line 479:
Note that in some interpreters you may need to press <Return> twice after entering the fractions if the ''Starting value'' prompt doesn't at first appear.
Note that in some interpreters you may need to press <Return> twice after entering the fractions if the ''Starting value'' prompt doesn't at first appear.


<lang befunge>p0" :snoitcarF">:#,_>&00g5p~$&00g:v
<syntaxhighlight lang="befunge">p0" :snoitcarF">:#,_>&00g5p~$&00g:v
v"Starting value: "_^#-*84~p6p00+1<
v"Starting value: "_^#-*84~p6p00+1<
>:#,_&0" :snoitaretI">:#,_#@>>$&\:v
>:#,_&0" :snoitaretI">:#,_#@>>$&\:v
:$_\:10g5g*:10g6g%v1:\1$\$<|!:-1\.<
:$_\:10g5g*:10g6g%v1:\1$\$<|!:-1\.<
g0^<!:-1\p01+1g01$_10g6g/\^>\010p00</lang>
g0^<!:-1\p01+1g01$_10g6g/\^>\010p00</syntaxhighlight>


{{out}}
{{out}}
Line 498: Line 498:
<code>Fractran</code> performs a single iteration of fractran on a given input, list of numerators and list of denominators.
<code>Fractran</code> performs a single iteration of fractran on a given input, list of numerators and list of denominators.


<lang bqn># Fractran interpreter
<syntaxhighlight lang="bqn"># Fractran interpreter


# Helpers
# Helpers
Line 531: Line 531:
seq ← 200 RunFractran 2‿"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"
seq ← 200 RunFractran 2‿"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"
•Out "Generated numbers: "∾•Repr seq
•Out "Generated numbers: "∾•Repr seq
•Out "Primes: "∾•Repr 1↓⌊2⋆⁼(⌈=⌊)∘(2⊸(⋆⁼))⊸/ seq</lang>
•Out "Primes: "∾•Repr 1↓⌊2⋆⁼(⌈=⌊)∘(2⊸(⋆⁼))⊸/ seq</syntaxhighlight>
<lang> )ex fractran.bqn
<syntaxhighlight lang="text"> )ex fractran.bqn
Generated numbers: 2‿15‿825‿725‿1925‿2275‿425‿390‿330‿290‿770‿910‿170‿156‿132‿116‿308‿364‿68‿4‿30‿225‿12375‿10875‿28875‿25375‿67375‿79625‿14875‿13650‿2550‿2340‿1980‿1740‿4620‿4060‿10780‿12740‿2380‿2184‿408‿152‿92‿380‿230‿950‿575‿2375‿9625‿11375‿2125‿1950‿1650‿1450‿3850‿4550‿850‿780‿660‿580‿1540‿1820‿340‿312‿264‿232‿616‿728‿136‿8‿60‿450‿3375‿185625‿163125‿433125‿380625‿1010625‿888125‿2358125‿2786875‿520625‿477750‿89250‿81900‿15300‿14040‿11880‿10440‿27720‿24360‿64680‿56840‿150920‿178360‿33320‿30576‿5712‿2128‿1288‿5320‿3220‿13300‿8050‿33250‿20125‿83125‿336875‿398125‿74375‿68250‿12750‿11700‿9900‿8700‿23100‿20300‿53900‿63700‿11900‿10920‿2040‿1872‿1584‿1392‿3696‿3248‿8624‿10192‿1904‿112‿120‿900‿6750‿50625‿2784375‿2446875‿6496875‿5709375‿15159375‿13321875‿35371875‿31084375‿82534375‿97540625‿18221875‿16721250‿3123750‿2866500‿535500‿491400‿91800‿84240‿71280‿62640‿166320‿146160‿388080‿341040‿905520‿795760‿2112880‿2497040‿466480‿428064‿79968‿29792‿18032‿74480‿45080‿186200‿112700‿465500‿281750‿1163750‿704375‿2909375‿11790625‿13934375‿2603125‿2388750‿446250‿409500‿76500‿70200‿59400‿52200‿138600‿121800‿323400‿284200‿754600‿891800‿166600‿152880‿28560‿26208‿4896‿1824‿1104
Generated numbers: 2‿15‿825‿725‿1925‿2275‿425‿390‿330‿290‿770‿910‿170‿156‿132‿116‿308‿364‿68‿4‿30‿225‿12375‿10875‿28875‿25375‿67375‿79625‿14875‿13650‿2550‿2340‿1980‿1740‿4620‿4060‿10780‿12740‿2380‿2184‿408‿152‿92‿380‿230‿950‿575‿2375‿9625‿11375‿2125‿1950‿1650‿1450‿3850‿4550‿850‿780‿660‿580‿1540‿1820‿340‿312‿264‿232‿616‿728‿136‿8‿60‿450‿3375‿185625‿163125‿433125‿380625‿1010625‿888125‿2358125‿2786875‿520625‿477750‿89250‿81900‿15300‿14040‿11880‿10440‿27720‿24360‿64680‿56840‿150920‿178360‿33320‿30576‿5712‿2128‿1288‿5320‿3220‿13300‿8050‿33250‿20125‿83125‿336875‿398125‿74375‿68250‿12750‿11700‿9900‿8700‿23100‿20300‿53900‿63700‿11900‿10920‿2040‿1872‿1584‿1392‿3696‿3248‿8624‿10192‿1904‿112‿120‿900‿6750‿50625‿2784375‿2446875‿6496875‿5709375‿15159375‿13321875‿35371875‿31084375‿82534375‿97540625‿18221875‿16721250‿3123750‿2866500‿535500‿491400‿91800‿84240‿71280‿62640‿166320‿146160‿388080‿341040‿905520‿795760‿2112880‿2497040‿466480‿428064‿79968‿29792‿18032‿74480‿45080‿186200‿112700‿465500‿281750‿1163750‿704375‿2909375‿11790625‿13934375‿2603125‿2388750‿446250‿409500‿76500‿70200‿59400‿52200‿138600‿121800‿323400‿284200‿754600‿891800‿166600‿152880‿28560‿26208‿4896‿1824‿1104
Primes: 2‿3</lang>
Primes: 2‿3</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
This program computes the first twenty primes. It has to do almost 430000 iterations to arrive at the twentieth prime, so instead of immediately writing each number to the terminal, it adds it to a list. After the set number of iterations, the list of numbers is written to a text file numbers.lst (21858548 bytes), so you can inspect it. Because it takes some time to do all iterations, its is advisable to write the source code below in a text file 'fractran' and run it in batch mode in the background, instead of starting Bracmat in interactive mode and typing the program at the prompt. The primes, together with the largest number found, are written to a file FRACTRAN.OUT.
This program computes the first twenty primes. It has to do almost 430000 iterations to arrive at the twentieth prime, so instead of immediately writing each number to the terminal, it adds it to a list. After the set number of iterations, the list of numbers is written to a text file numbers.lst (21858548 bytes), so you can inspect it. Because it takes some time to do all iterations, its is advisable to write the source code below in a text file 'fractran' and run it in batch mode in the background, instead of starting Bracmat in interactive mode and typing the program at the prompt. The primes, together with the largest number found, are written to a file FRACTRAN.OUT.
<lang bracmat>(fractran=
<syntaxhighlight lang="bracmat">(fractran=
np n fs A Z fi P p N L M
np n fs A Z fi P p N L M
. !arg:(?N,?n,?fs) {Number of iterations, start n, fractions}
. !arg:(?N,?n,?fs) {Number of iterations, start n, fractions}
Line 573: Line 573:
str$("\ntime: " flt$(clk$+-1*!t0,4) " sec\n")
str$("\ntime: " flt$(clk$+-1*!t0,4) " sec\n")
, "FRACTRAN.OUT",NEW)
, "FRACTRAN.OUT",NEW)
);</lang>
);</syntaxhighlight>
In Linux, run the program as follows (assuming bracmat and the file 'fractran' are in the CWD):
In Linux, run the program as follows (assuming bracmat and the file 'fractran' are in the CWD):
<pre>./bracmat 'get$fractran' &</pre>
<pre>./bracmat 'get$fractran' &</pre>
Line 609: Line 609:
Using GMP. Powers of two are in brackets.
Using GMP. Powers of two are in brackets.
For extra credit, pipe the output through <code>| less -S</code>.
For extra credit, pipe the output through <code>| less -S</code>.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <gmp.h>
#include <gmp.h>
Line 673: Line 673:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <sstream>
#include <sstream>
Line 742: Line 742:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 764: Line 764:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defun fractran (n frac-list)
<syntaxhighlight lang="lisp">(defun fractran (n frac-list)
(lambda ()
(lambda ()
(prog1
(prog1
Line 784: Line 784:
for next = (funcall fractran-instance)
for next = (funcall fractran-instance)
until (null next)
until (null next)
do (print next))</lang>
do (print next))</syntaxhighlight>


{{out}}
{{out}}
Line 811: Line 811:
===Simple Version===
===Simple Version===
{{trans|Java}}
{{trans|Java}}
<lang d>import std.stdio, std.algorithm, std.conv, std.array;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.conv, std.array;


void fractran(in string prog, int val, in uint limit) {
void fractran(in string prog, int val, in uint limit) {
Line 828: Line 828:
fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23
fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15);
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>0: 2
<pre>0: 2
Line 847: Line 847:


===Lazy Version===
===Lazy Version===
<lang d>import std.stdio, std.algorithm, std.conv, std.array, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.conv, std.array, std.range;


struct Fractran {
struct Fractran {
Line 872: Line 872:
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2)
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2)
.take(15).writeln;
.take(15).writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132]</pre>
<pre>[2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132]</pre>
Line 879: Line 879:
{{libheader| System.RegularExpressions}}
{{libheader| System.RegularExpressions}}
{{Trans|Java}}
{{Trans|Java}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program FractranTest;
program FractranTest;


Line 971: Line 971:
TFractan.Create(DATA, 2).Free;
TFractan.Create(DATA, 2).Free;
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 993: Line 993:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Fractran do
<syntaxhighlight lang="elixir">defmodule Fractran do
use Bitwise
use Bitwise
Line 1,058: Line 1,058:
|> Enum.map(&Fractran.lowbit/1)
|> Enum.map(&Fractran.lowbit/1)
|> tl
|> tl
IO.puts "The first few primes are:\n#{inspect prime}"</lang>
IO.puts "The first few primes are:\n#{inspect prime}"</syntaxhighlight>


{{out}}
{{out}}
Line 1,071: Line 1,071:
=={{header|Erlang}}==
=={{header|Erlang}}==
The exec() function can be passed a predicate which filters steps that satisfy a condition, which for the prime automata is a check to see if the number is a power of 2.
The exec() function can be passed a predicate which filters steps that satisfy a condition, which for the prime automata is a check to see if the number is a power of 2.
<lang erlang>#! /usr/bin/escript
<syntaxhighlight lang="erlang">#! /usr/bin/escript


-mode(native).
-mode(native).
Line 1,130: Line 1,130:
gcd(A, 0) -> A;
gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).
gcd(A, B) -> gcd(B, A rem B).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,146: Line 1,146:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io kernel math math.functions math.parser multiline
<syntaxhighlight lang="factor">USING: io kernel math math.functions math.parser multiline
prettyprint sequences splitting ;
prettyprint sequences splitting ;
IN: rosetta-code.fractran
IN: rosetta-code.fractran
Line 1,180: Line 1,180:
2bi ;
2bi ;
MAIN: main</lang>
MAIN: main</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,191: Line 1,191:


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>Func FT( arr, n, m ) =
<syntaxhighlight lang="fermat">Func FT( arr, n, m ) =
;{executes John H. Conway's FRACTRAN language for a program stored in [arr], an}
;{executes John H. Conway's FRACTRAN language for a program stored in [arr], an}
;{input integer stored in n, for a maximum of m steps}
;{input integer stored in n, for a maximum of m steps}
Line 1,216: Line 1,216:
[arr]:=[( 17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55/1 )];
[arr]:=[( 17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55/1 )];


FT( [arr], 2, 20 );</lang>
FT( [arr], 2, 20 );</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
2
2
Line 1,245: Line 1,245:


===The Code===
===The Code===
The source style is F77 except for the use of the I0 format code, though not all F77 compilers will offer INTEGER*8. By not using the MODULE scheme, array parameters can't be declared via P(:) which implies a secret additional parameter giving the size of the array and which can be accessed via the likes of <code>UBOUND(P, DIM = 1)</code> Instead, the old-style specification involves no additional parameters and can be given as P(*) meaning "no statement" as to the upper bound, or P(M) which ''may'' be interpreted as the upper bound being the value of M in the compilers that allow this. The actual upper bound of the parameter is unknown and unchecked, so the older style of P(12345) or similar might be used. Rather to my surprise, this compiler (Compaq F90/95) complained if parameter M was declared after the arrays P(M),Q(M) as it is my habit to declare parameters in the order of their appearance. <lang Fortran>C:\Nicky\RosettaCode\FRACTRAN\FRACTRAN.for(6) : Warning: This name has not been given an explicit type. [M]
The source style is F77 except for the use of the I0 format code, though not all F77 compilers will offer INTEGER*8. By not using the MODULE scheme, array parameters can't be declared via P(:) which implies a secret additional parameter giving the size of the array and which can be accessed via the likes of <code>UBOUND(P, DIM = 1)</code> Instead, the old-style specification involves no additional parameters and can be given as P(*) meaning "no statement" as to the upper bound, or P(M) which ''may'' be interpreted as the upper bound being the value of M in the compilers that allow this. The actual upper bound of the parameter is unknown and unchecked, so the older style of P(12345) or similar might be used. Rather to my surprise, this compiler (Compaq F90/95) complained if parameter M was declared after the arrays P(M),Q(M) as it is my habit to declare parameters in the order of their appearance. <syntaxhighlight lang="fortran">C:\Nicky\RosettaCode\FRACTRAN\FRACTRAN.for(6) : Warning: This name has not been given an explicit type. [M]
INTEGER P(M),Q(M)!The terms of the fractions.</lang>
INTEGER P(M),Q(M)!The terms of the fractions.</syntaxhighlight>
So much for multi-pass compilers!
So much for multi-pass compilers!


Similarly, without the MODULE protocol, in all calling routines function FRACTRAN would be deemed floating-point so a type declaration is needed in each. <lang Fortran> INTEGER FUNCTION FRACTRAN(N,P,Q,M) !Notion devised by J. H. Conway.
Similarly, without the MODULE protocol, in all calling routines function FRACTRAN would be deemed floating-point so a type declaration is needed in each. <syntaxhighlight lang="fortran"> INTEGER FUNCTION FRACTRAN(N,P,Q,M) !Notion devised by J. H. Conway.
Careful: the rule is N*P/Q being integer. N*6/3 is integer always because this is N*2/1, but 3 may not divide N.
Careful: the rule is N*P/Q being integer. N*6/3 is integer always because this is N*2/1, but 3 may not divide N.
Could check GCD(P,Q), dividing out the common denominator so MOD(N,Q) works.
Could check GCD(P,Q), dividing out the common denominator so MOD(N,Q) works.
Line 1,298: Line 1,298:
END DO !The next step.
END DO !The next step.
END !Whee!
END !Whee!
</syntaxhighlight>
</lang>


===The Results===
===The Results===
Line 1,339: Line 1,339:
28 1: 14875
28 1: 14875
</pre>
</pre>
Later Fortrans might offer the library function <code>POPCNT(n)</code> which returns the number of on-bits in an integer, most convenient for detecting a straight power of two in a binary computer. Adjusting the interpretation loop to be <lang Fortran> DO I = 1,M !Here we go!
Later Fortrans might offer the library function <code>POPCNT(n)</code> which returns the number of on-bits in an integer, most convenient for detecting a straight power of two in a binary computer. Adjusting the interpretation loop to be <syntaxhighlight lang="fortran"> DO I = 1,M !Here we go!
IT = FRACTRAN(N,P,Q,L) !Do it!
IT = FRACTRAN(N,P,Q,L) !Do it!
IF (POPCNT(N).EQ.1) WRITE (6,11) I,IT,N !Show it!
IF (POPCNT(N).EQ.1) WRITE (6,11) I,IT,N !Show it!
Line 1,350: Line 1,350:
END IF !So much for overflow.
END IF !So much for overflow.
END DO !The next step.
END DO !The next step.
</syntaxhighlight>
</lang>
Leads to the following output:
Leads to the following output:
<pre>
<pre>
Line 1,385: Line 1,385:


===Revised Code===
===Revised Code===
Because this scheme requires a supply of prime numbers, it is convenient to employ the routines prepared for the [[Extensible_prime_generator|extensible prime generator]] via module PRIMEBAG. So, this means escalating to the F90 style, and given that, some compound data structures can be used (for better mnemonics) in place of collections of arrays. <lang Fortran> MODULE CONWAYSIDEA !Notion devised by J. H. Conway.
Because this scheme requires a supply of prime numbers, it is convenient to employ the routines prepared for the [[Extensible_prime_generator|extensible prime generator]] via module PRIMEBAG. So, this means escalating to the F90 style, and given that, some compound data structures can be used (for better mnemonics) in place of collections of arrays. <syntaxhighlight lang="fortran"> MODULE CONWAYSIDEA !Notion devised by J. H. Conway.
USE PRIMEBAG !This is a common need.
USE PRIMEBAG !This is a common need.
INTEGER LASTP,ENUFF !Some size allowances.
INTEGER LASTP,ENUFF !Some size allowances.
Line 1,572: Line 1,572:
Complete!
Complete!
END !Whee!
END !Whee!
</syntaxhighlight>
</lang>


===Revised Results===
===Revised Results===
Line 1,687: Line 1,687:
100 7: 3 1 1 1
100 7: 3 1 1 1
</pre>
</pre>
This time, restricting output to only occasions when N is a power of two requires no peculiar bit-counting function. Just change the interpretation loop to <lang Fortran> DO I = 1,MS !Here we go!
This time, restricting output to only occasions when N is a power of two requires no peculiar bit-counting function. Just change the interpretation loop to <syntaxhighlight lang="fortran"> DO I = 1,MS !Here we go!
IT = FRACTRAN(LF) !Do it!
IT = FRACTRAN(LF) !Do it!
IF (ALL(NPPOW(2:LP).EQ.0)) CALL SHOWN(I,IT) !Show it!
IF (ALL(NPPOW(2:LP).EQ.0)) CALL SHOWN(I,IT) !Show it!
IF (IT.LE.0) EXIT !Quit it?
IF (IT.LE.0) EXIT !Quit it?
END DO !The next step.</lang>
END DO !The next step.</syntaxhighlight>


Output:
Output:
Line 1,805: Line 1,805:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Added a compiler condition to make the program work with the old GMP.bi header file
Added a compiler condition to make the program work with the old GMP.bi header file
<lang FreeBasic>' version 06-07-2015
<syntaxhighlight lang="freebasic">' version 06-07-2015
' compile with: fbc -s console
' compile with: fbc -s console
' uses gmp
' uses gmp
Line 1,894: Line 1,894:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132, 116
<pre>2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132, 116
Line 1,933: Line 1,933:
=={{header|Go}}==
=={{header|Go}}==
Basic task: This compiles to produce a program that reads the limit, starting number n, and list of fractions as command line arguments, with the list of fractions as a single argument.
Basic task: This compiles to produce a program that reads the limit, starting number n, and list of fractions as command line arguments, with the list of fractions as a single argument.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,994: Line 1,994:
}
}
exec(p, &n, limit)
exec(p, &n, limit)
}</lang>
}</syntaxhighlight>
{{out|Command line usage, with program compiled as "ft"}}
{{out|Command line usage, with program compiled as "ft"}}
<pre>
<pre>
Line 2,002: Line 2,002:
Extra credit: This invokes above program with appropriate arguments,
Extra credit: This invokes above program with appropriate arguments,
and processes the output to obtain the 20 primes.
and processes the output to obtain the 20 primes.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,036: Line 2,036:
}
}
fmt.Println()
fmt.Println()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,044: Line 2,044:
=={{header|Haskell}}==
=={{header|Haskell}}==
===Running the program===
===Running the program===
<lang haskell>import Data.List (find)
<syntaxhighlight lang="haskell">import Data.List (find)
import Data.Ratio (Ratio, (%), denominator)
import Data.Ratio (Ratio, (%), denominator)


Line 2,051: Line 2,051:
case find (\f -> n `mod` denominator f == 0) fracts of
case find (\f -> n `mod` denominator f == 0) fracts of
Nothing -> []
Nothing -> []
Just f -> fractran fracts $ truncate (fromIntegral n * f)</lang>
Just f -> fractran fracts $ truncate (fromIntegral n * f)</syntaxhighlight>


Example:
Example:
Line 2,061: Line 2,061:
===Reading the program===
===Reading the program===
Additional import
Additional import
<lang Haskell>import Data.List.Split (splitOn)</lang>
<syntaxhighlight lang="haskell">import Data.List.Split (splitOn)</syntaxhighlight>
<lang Haskell>readProgram :: String -> [Ratio Int]
<syntaxhighlight lang="haskell">readProgram :: String -> [Ratio Int]
readProgram = map (toFrac . splitOn "/") . splitOn ","
readProgram = map (toFrac . splitOn "/") . splitOn ","
where toFrac [n,d] = read n % read d</lang>
where toFrac [n,d] = read n % read d</syntaxhighlight>


Example of running the program:
Example of running the program:
Line 2,074: Line 2,074:
===Generation of primes===
===Generation of primes===
Additional import
Additional import
<lang Haskell>import Data.Maybe (mapMaybe)
<syntaxhighlight lang="haskell">import Data.Maybe (mapMaybe)
import Data.List (elemIndex)</lang>
import Data.List (elemIndex)</syntaxhighlight>
<lang Haskell>primes :: [Int]
<syntaxhighlight lang="haskell">primes :: [Int]
primes = mapMaybe log2 $ fractran prog 2
primes = mapMaybe log2 $ fractran prog 2
where
where
Line 2,095: Line 2,095:
, 55 % 1
, 55 % 1
]
]
log2 = fmap succ . elemIndex 2 . takeWhile even . iterate (`div` 2)</lang>
log2 = fmap succ . elemIndex 2 . takeWhile even . iterate (`div` 2)</syntaxhighlight>


<pre>λ> take 20 primes
<pre>λ> take 20 primes
Line 2,103: Line 2,103:
Works in both languages:
Works in both languages:


<lang unicon>record fract(n,d)
<syntaxhighlight lang="unicon">record fract(n,d)


procedure main(A)
procedure main(A)
Line 2,129: Line 2,129:
}
}
write()
write()
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,142: Line 2,142:
===Hybrid version===
===Hybrid version===
'''Solution:'''
'''Solution:'''
<lang j>toFrac=: '/r' 0&".@charsub ] NB. read fractions from string
<syntaxhighlight lang="j">toFrac=: '/r' 0&".@charsub ] NB. read fractions from string
fractran15=: ({~ (= <.) i. 1:)@(toFrac@[ * ]) ^:(<15) NB. return first 15 Fractran results</lang>
fractran15=: ({~ (= <.) i. 1:)@(toFrac@[ * ]) ^:(<15) NB. return first 15 Fractran results</syntaxhighlight>


'''Example:'''
'''Example:'''
<lang j> taskstr=: '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1'
<syntaxhighlight lang="j"> taskstr=: '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1'
taskstr fractran15 2
taskstr fractran15 2
2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132</lang>
2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132</syntaxhighlight>


===Tacit version===
===Tacit version===
Line 2,156: Line 2,156:
This is a variation of the previous solution which it is not entirely tacit due to the use of the explicit standard library verb (function) charsub. The adverb (functional) fractran is defined as a fixed tacit adverb (that is, a stateless point-free functional),
This is a variation of the previous solution which it is not entirely tacit due to the use of the explicit standard library verb (function) charsub. The adverb (functional) fractran is defined as a fixed tacit adverb (that is, a stateless point-free functional),


<lang j>fractran=. (((({~ (1 i.~ (= <.)))@:* ::]^:)(`]))(".@:('1234567890r ' {~ '1234567890/ '&i.)@:[`))(`:6)</lang>
<syntaxhighlight lang="j">fractran=. (((({~ (1 i.~ (= <.)))@:* ::]^:)(`]))(".@:('1234567890r ' {~ '1234567890/ '&i.)@:[`))(`:6)</syntaxhighlight>
The argument of fractran specifies a limit for the number of steps; if the limit is boxed the intermediate results are also included in the result.
The argument of fractran specifies a limit for the number of steps; if the limit is boxed the intermediate results are also included in the result.
Line 2,162: Line 2,162:
'''Example'''
'''Example'''


<lang j> '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1' (<15) fractran 2
<syntaxhighlight lang="j"> '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1' (<15) fractran 2
2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132</lang>
2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132</syntaxhighlight>


Line 2,170: Line 2,170:
The prime numbers are produced via the adverb primes; its argument has the same specifications as the argument for the fractran adverb (which is used in its definition),
The prime numbers are produced via the adverb primes; its argument has the same specifications as the argument for the fractran adverb (which is used in its definition),


<lang j>primes=. ('fractan'f.) ((1 }. 2 ^. (#~ *./@:e.&2 0"1@:q:))@:)
<syntaxhighlight lang="j">primes=. ('fractan'f.) ((1 }. 2 ^. (#~ *./@:e.&2 0"1@:q:))@:)
'17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1' (<555555) primes 2
'17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1' (<555555) primes 2
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71</lang>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71</syntaxhighlight>


primes is also a stateless point-free functional,
primes is also a stateless point-free functional,
<lang j> primes
<syntaxhighlight lang="j"> primes
((((({~ (1 i.~ (= <.)))@:* ::]^:)(`]))(".@:('1234567890r ' {~ '1234567890/ '&i.)@:[`))(`:6))((1 }. 2 ^. (#~ *./@:e.&2 0"1@:q:))@:)</lang>
((((({~ (1 i.~ (= <.)))@:* ::]^:)(`]))(".@:('1234567890r ' {~ '1234567890/ '&i.)@:[`))(`:6))((1 }. 2 ^. (#~ *./@:e.&2 0"1@:q:))@:)</syntaxhighlight>


Line 2,185: Line 2,185:
When _ is the limit argument (i.e., when no limit is imposed) the run will halt according to the FRACTRAN programming language specifications (the run might also be forced to halt if a trivial changeless single cycle, induced by a useless 1/1 fraction, is detected). Thus, the FRACTRAN associated verb (function) is,
When _ is the limit argument (i.e., when no limit is imposed) the run will halt according to the FRACTRAN programming language specifications (the run might also be forced to halt if a trivial changeless single cycle, induced by a useless 1/1 fraction, is detected). Thus, the FRACTRAN associated verb (function) is,
<lang j> _ fractran
<syntaxhighlight lang="j"> _ fractran
".@:('1234567890r ' {~ '1234567890/ '&i.)@:[ ({~ (1 i.~ (= <.)))@:* ::]^:_ ]</lang>
".@:('1234567890r ' {~ '1234567890/ '&i.)@:[ ({~ (1 i.~ (= <.)))@:* ::]^:_ ]</syntaxhighlight>


Actually, most of the code above is there to comply with the task's requirement of a "''natural'' format." When J's format for fractions is used the FRACTRAN verb becomes,
Actually, most of the code above is there to comply with the task's requirement of a "''natural'' format." When J's format for fractions is used the FRACTRAN verb becomes,


<lang j>FRACTRAN=. ({~ (1 i.~ (= <.)))@:* ::]^:_</lang>
<syntaxhighlight lang="j">FRACTRAN=. ({~ (1 i.~ (= <.)))@:* ::]^:_</syntaxhighlight>


which is an indirect concise confirmation that J's fixed tacit dialect is Turing complete.
which is an indirect concise confirmation that J's fixed tacit dialect is Turing complete.
Line 2,196: Line 2,196:
In the following example, FRACTRAN calculates the product 4 * 6, the initial value 11664 = (2^4)*(3^6) holds 4 in the register associated with 2 and holds 6 in the register associated with 3; the result 59604644775390625 = 5^24 holds the product 24 = 4 * 6 in the register associated with 5,
In the following example, FRACTRAN calculates the product 4 * 6, the initial value 11664 = (2^4)*(3^6) holds 4 in the register associated with 2 and holds 6 in the register associated with 3; the result 59604644775390625 = 5^24 holds the product 24 = 4 * 6 in the register associated with 5,


<lang j> 455r33 11r13 1r11 3r7 11r2 1r3 FRACTRAN 11664
<syntaxhighlight lang="j"> 455r33 11r13 1r11 3r7 11r2 1r3 FRACTRAN 11664
59604644775390625</lang>
59604644775390625</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.Vector;
<syntaxhighlight lang="java">import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.Pattern;
Line 2,253: Line 2,253:
System.out.println();
System.out.println();
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===Imperative===
===Imperative===
<lang javascript>// Parses the input string for the numerators and denominators
<syntaxhighlight lang="javascript">// Parses the input string for the numerators and denominators
function compile(prog, numArr, denArr) {
function compile(prog, numArr, denArr) {
let regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
let regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
Line 2,301: Line 2,301:
let [num, den] = compile("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", [], []);
let [num, den] = compile("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", [], []);
body.innerHTML = dump(num, den);
body.innerHTML = dump(num, den);
body.innerHTML += exec(2, 0, 15, num, den);</lang>
body.innerHTML += exec(2, 0, 15, num, den);</syntaxhighlight>


===Functional===
===Functional===
Line 2,307: Line 2,307:


Here is a functionally composed version, which also derives a few primes. I may have missed something, but this first draft suggests that we may need bigInt support (which JS lacks) to get as far as the sixth prime.
Here is a functionally composed version, which also derives a few primes. I may have missed something, but this first draft suggests that we may need bigInt support (which JS lacks) to get as far as the sixth prime.
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 2,548: Line 2,548:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"First fifteen steps:" -> [2,15,825,725,1925,2275,425,390,330,290,770,910,170,156,132]
<pre>"First fifteen steps:" -> [2,15,825,725,1925,2275,425,390,330,290,770,910,170,156,132]
Line 2,555: Line 2,555:
=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
<lang julia>function fractran(n::Integer, ratios::Vector{<:Rational}, steplim::Integer)
<syntaxhighlight lang="julia">function fractran(n::Integer, ratios::Vector{<:Rational}, steplim::Integer)
rst = zeros(BigInt, steplim)
rst = zeros(BigInt, steplim)
for i in 1:steplim
for i in 1:steplim
Line 2,588: Line 2,588:
end
end
n = fractran(n, fracs, 2)[2]
n = fractran(n, fracs, 2)[2]
end</lang>
end</syntaxhighlight>


{{output}}
{{output}}
Line 2,614: Line 2,614:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


import java.math.BigInteger
import java.math.BigInteger
Line 2,658: Line 2,658:
println("\nFirst twenty primes:")
println("\nFirst twenty primes:")
println(fractran(program, 2, 20, true))
println(fractran(program, 2, 20, true))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,672: Line 2,672:
This isn't as efficient as possible for long lists of fractions, since it doesn't stop doing n*listelements once it finds an integer. Instead, it computes "is integer?" for n*{all list elements}. For short lists that's probably not a big deal.
This isn't as efficient as possible for long lists of fractions, since it doesn't stop doing n*listelements once it finds an integer. Instead, it computes "is integer?" for n*{all list elements}. For short lists that's probably not a big deal.


<lang Mathematica>fractionlist = {17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1};
<syntaxhighlight lang="mathematica">fractionlist = {17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1};
n = 2;
n = 2;
steplimit = 20;
steplimit = 20;
Line 2,686: Line 2,686:
n = newlist[[truepositions[[1, 1]]]]; j++;
n = newlist[[truepositions[[1, 1]]]]; j++;
]
]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>0: 2
<pre>0: 2
Line 2,713: Line 2,713:


Here is a different solution using a functional approach:
Here is a different solution using a functional approach:
<syntaxhighlight lang="mathematica">
<lang Mathematica>
fractran[
fractran[
program : {__ ? (Element[#, PositiveRationals] &)}, (* list of positive fractions *)
program : {__ ? (Element[#, PositiveRationals] &)}, (* list of positive fractions *)
Line 2,727: Line 2,727:
$PRIMEGAME = {17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1};
$PRIMEGAME = {17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1};
fractran[$PRIMEGAME, 2, 50]
fractran[$PRIMEGAME, 2, 50]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,735: Line 2,735:


Extract the first 20 prime numbers encoded as powers of 2:
Extract the first 20 prime numbers encoded as powers of 2:
<syntaxhighlight lang="mathematica">
<lang Mathematica>
Select[IntegerQ] @ Log2[fractran[$PRIMEGAME, 2, 500000]]
Select[IntegerQ] @ Log2[fractran[$PRIMEGAME, 2, 500000]]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>{1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67}</pre>
<pre>{1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67}</pre>
Line 2,747: Line 2,747:
We provide a general function to run any Fractran program and a specialized iterator to find prime numbers.
We provide a general function to run any Fractran program and a specialized iterator to find prime numbers.


<syntaxhighlight lang="nim">
<lang Nim>
import strutils
import strutils
import bignum
import bignum
Line 2,802: Line 2,802:
for val in primes(20):
for val in primes(20):
echo val
echo val
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,844: Line 2,844:
With this algorithm, we no longer need big numbers. To avoid overflow, value at each step is displayed using
With this algorithm, we no longer need big numbers. To avoid overflow, value at each step is displayed using
its decomposition in prime factors.
its decomposition in prime factors.
<syntaxhighlight lang="nim">
<lang Nim>
import algorithm
import algorithm
import sequtils
import sequtils
Line 2,981: Line 2,981:
echo "\nFirst twenty prime numbers:"
echo "\nFirst twenty prime numbers:"
findPrimes(20)
findPrimes(20)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,022: Line 3,022:
=={{header|OCaml}}==
=={{header|OCaml}}==
This reads a Fractran program from standard input (keyboard or file) and runs it with the input given by the command line arguments, using arbitrary-precision numbers and fractions.
This reads a Fractran program from standard input (keyboard or file) and runs it with the input given by the command line arguments, using arbitrary-precision numbers and fractions.
<lang ocaml>open Num
<syntaxhighlight lang="ocaml">open Num


let get_input () =
let get_input () =
Line 3,064: Line 3,064:
let num = get_input () in
let num = get_input () in
let prog = read_program () in
let prog = read_program () in
run_program num prog</lang>
run_program num prog</syntaxhighlight>


The program
The program
Line 3,114: Line 3,114:
{{Works with|PARI/GP|2.7.4 and above}}
{{Works with|PARI/GP|2.7.4 and above}}


<lang parigp>
<syntaxhighlight lang="parigp">
\\ FRACTRAN
\\ FRACTRAN
\\ 4/27/16 aev
\\ 4/27/16 aev
Line 3,130: Line 3,130:
print(fractran(2,v,15));
print(fractran(2,v,15));
}
}
</lang>
</syntaxhighlight>


{{Output}}
{{Output}}
Line 3,142: Line 3,142:
This makes the fact that it's a prime-number-generating program much clearer.
This makes the fact that it's a prime-number-generating program much clearer.


<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use Math::BigRat;
use Math::BigRat;
Line 3,173: Line 3,173:


print "\n";
print "\n";
</syntaxhighlight>
</lang>


If you uncomment the <pre>#print $n</pre>, it will print all the steps.
If you uncomment the <pre>#print $n</pre>, it will print all the steps.
Line 3,188: Line 3,188:
Division (to whole integer) is performed simply by subtracting the corresponding powers, as above not possible if any would be negative.
Division (to whole integer) is performed simply by subtracting the corresponding powers, as above not possible if any would be negative.


<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- 8s
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- 8s
--with javascript_semantics -- 52s!! (see note)</span>
--with javascript_semantics -- 52s!! (see note)</span>
Line 3,294: Line 3,294:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"first %d primes: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"first %d primes: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%,d iterations in %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">iteration</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%,d iterations in %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">iteration</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,307: Line 3,307:


=={{header|Prolog}}==
=={{header|Prolog}}==
<lang prolog>
<syntaxhighlight lang="prolog">
load(Program, Fractions) :-
load(Program, Fractions) :-
re_split("[ ]+", Program, Split), odd_items(Split, TextualFractions),
re_split("[ ]+", Program, Split), odd_items(Split, TextualFractions),
Line 3,358: Line 3,358:


?- main.
?- main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,367: Line 3,367:
=={{header|Python}}==
=={{header|Python}}==
===Python: Generate series from a fractran program===
===Python: Generate series from a fractran program===
<lang python>from fractions import Fraction
<syntaxhighlight lang="python">from fractions import Fraction


def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
Line 3,387: Line 3,387:
n, m = 2, 15
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))</lang>
', '.join(str(f) for f,i in zip(fractran(n), range(m))))</syntaxhighlight>


{{out}}
{{out}}
Line 3,396: Line 3,396:
Use fractran above as a module imported into the following program.
Use fractran above as a module imported into the following program.


<lang python>
<syntaxhighlight lang="python">
from fractran import fractran
from fractran import fractran


Line 3,409: Line 3,409:
if __name__ == '__main__':
if __name__ == '__main__':
for (prime, i), j in zip(fractran_primes(), range(15)):
for (prime, i), j in zip(fractran_primes(), range(15)):
print("Generated prime %2i from the %6i'th member of the fractran series" % (prime, i))</lang>
print("Generated prime %2i from the %6i'th member of the fractran series" % (prime, i))</syntaxhighlight>


{{out}}
{{out}}
Line 3,436: Line 3,436:
To execute a Fractran program until the halting condition is satisfied, use <code>[ program share run until ]</code>. The Fractran prime generator will never satisfy the halting condition, so in this task the <code>drop</code> after <code>run</code> discards the boolean.
To execute a Fractran program until the halting condition is satisfied, use <code>[ program share run until ]</code>. The Fractran prime generator will never satisfy the halting condition, so in this task the <code>drop</code> after <code>run</code> discards the boolean.


<lang Quackery> [ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!


[ 1 & not ] is even ( n --> b )
[ 1 & not ] is even ( n --> b )
Line 3,494: Line 3,494:
program release
program release
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,505: Line 3,505:
=={{header|Racket}}==
=={{header|Racket}}==
{{trans|D}} Simple version, without sequences.
{{trans|D}} Simple version, without sequences.
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (displaysp x)
(define (displaysp x)
Line 3,535: Line 3,535:
"13 / 11, 15 / 14, 15 / 2, 55 / 1")))
"13 / 11, 15 / 14, 15 / 2, 55 / 1")))


(show-fractran fractran 2 15)</lang>
(show-fractran fractran 2 15)</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 members of fractran(2):
<pre>First 15 members of fractran(2):
Line 3,544: Line 3,544:
{{works with|rakudo|2015-11-03}}
{{works with|rakudo|2015-11-03}}
A Fractran program potentially returns an infinite list, and infinite lists are a common data structure in Raku. The limit is therefore enforced only by slicing the infinite list.
A Fractran program potentially returns an infinite list, and infinite lists are a common data structure in Raku. The limit is therefore enforced only by slicing the infinite list.
<lang perl6>sub fractran(@program) {
<syntaxhighlight lang="raku" line>sub fractran(@program) {
2, { first Int, map (* * $_).narrow, @program } ... 0
2, { first Int, map (* * $_).narrow, @program } ... 0
}
}
say fractran(<17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11
say fractran(<17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11
15/14 15/2 55/1>)[^100];</lang>
15/14 15/2 55/1>)[^100];</syntaxhighlight>
{{out}}
{{out}}
<pre>(2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4 30 225 12375 10875 28875 25375 67375 79625 14875 13650 2550 2340 1980 1740 4620 4060 10780 12740 2380 2184 408 152 92 380 230 950 575 2375 9625 11375 2125 1950 1650 1450 3850 4550 850 780 660 580 1540 1820 340 312 264 232 616 728 136 8 60 450 3375 185625 163125 433125 380625 1010625 888125 2358125 2786875 520625 477750 89250 81900 15300 14040 11880 10440 27720 24360 64680 56840 150920 178360 33320 30576 5712 2128 1288)</pre>
<pre>(2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4 30 225 12375 10875 28875 25375 67375 79625 14875 13650 2550 2340 1980 1740 4620 4060 10780 12740 2380 2184 408 152 92 380 230 950 575 2375 9625 11375 2125 1950 1650 1450 3850 4550 850 780 660 580 1540 1820 340 312 264 232 616 728 136 8 60 450 3375 185625 163125 433125 380625 1010625 888125 2358125 2786875 520625 477750 89250 81900 15300 14040 11880 10440 27720 24360 64680 56840 150920 178360 33320 30576 5712 2128 1288)</pre>
'''Extra credit:'''
'''Extra credit:'''
We can weed out all the powers of two into another infinite constant list based on the first list. In this case the sequence is limited only by our patience, and a ^C from the terminal. The <tt>.msb</tt> method finds the most significant bit of an integer, which conveniently is the base-2 log of the power-of-two in question.
We can weed out all the powers of two into another infinite constant list based on the first list. In this case the sequence is limited only by our patience, and a ^C from the terminal. The <tt>.msb</tt> method finds the most significant bit of an integer, which conveniently is the base-2 log of the power-of-two in question.
<lang perl6>sub fractran(@program) {
<syntaxhighlight lang="raku" line>sub fractran(@program) {
2, { first Int, map (* * $_).narrow, @program } ... 0
2, { first Int, map (* * $_).narrow, @program } ... 0
}
}
Line 3,559: Line 3,559:
15/14 15/2 55/1> {
15/14 15/2 55/1> {
say $++, "\t", .msb, "\t", $_ if 1 +< .msb == $_;
say $++, "\t", .msb, "\t", $_ if 1 +< .msb == $_;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,575: Line 3,575:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red ["Fractran"]
<syntaxhighlight lang="red">Red ["Fractran"]


inp: ask "please enter list of fractions, or input file name: "
inp: ask "please enter list of fractions, or input file name: "
Line 3,598: Line 3,598:
if l = index? code [halt]
if l = index? code [halt]
]
]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>please enter list of fractions, or input file name: 17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1
<pre>please enter list of fractions, or input file name: 17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1
Line 3,622: Line 3,622:
Programming note: &nbsp; extra blanks can be inserted in the fractions before and/or after the solidus &nbsp; ['''<big>/</big>'''].
Programming note: &nbsp; extra blanks can be inserted in the fractions before and/or after the solidus &nbsp; ['''<big>/</big>'''].
===showing all terms===
===showing all terms===
<lang rexx>/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */
<syntaxhighlight lang="rexx">/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */
numeric digits 2000 /*be able to handle larger numbers. */
numeric digits 2000 /*be able to handle larger numbers. */
parse arg N terms fracs /*obtain optional arguments from the CL*/
parse arg N terms fracs /*obtain optional arguments from the CL*/
Line 3,649: Line 3,649:
exit 0 /*stick a fork in it, we're all done. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</lang>
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre style="height:63ex">
<pre style="height:63ex">
Line 3,759: Line 3,759:
===showing prime numbers===
===showing prime numbers===
Programming note: &nbsp; if the number of terms specified (the 2<sup>nd</sup> argument) is negative, then only powers of two are displayed.
Programming note: &nbsp; if the number of terms specified (the 2<sup>nd</sup> argument) is negative, then only powers of two are displayed.
<lang rexx>/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */
<syntaxhighlight lang="rexx">/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */
numeric digits 999; d= digits(); w= length(d) /*be able to handle gihugeic numbers. */
numeric digits 999; d= digits(); w= length(d) /*be able to handle gihugeic numbers. */
parse arg N terms fracs /*obtain optional arguments from the CL*/
parse arg N terms fracs /*obtain optional arguments from the CL*/
Line 3,797: Line 3,797:
exit 0 /*stick a fork in it, we're all done. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</lang>
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</syntaxhighlight>
{{out|output|text=&nbsp; when using the input (negative fifty million) of: &nbsp; &nbsp; <tt> , &nbsp; -50000000 </tt>}}
{{out|output|text=&nbsp; when using the input (negative fifty million) of: &nbsp; &nbsp; <tt> , &nbsp; -50000000 </tt>}}
<pre>
<pre>
Line 3,879: Line 3,879:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>ar = %w[17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1]
<syntaxhighlight lang="ruby">ar = %w[17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1]
FractalProgram = ar.map(&:to_r) #=> array of rationals
FractalProgram = ar.map(&:to_r) #=> array of rationals


Line 3,896: Line 3,896:
# demo
# demo
p Runner.take(20).map(&:numerator)
p Runner.take(20).map(&:numerator)
p prime_generator.take(20)</lang>
p prime_generator.take(20)</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,905: Line 3,905:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>class TestFractran extends FunSuite {
<syntaxhighlight lang="scala">class TestFractran extends FunSuite {
val program = Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1")
val program = Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1")
val expect = List(2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132)
val expect = List(2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132)
Line 3,928: Line 3,928:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 3,935: Line 3,935:
{{libheader|Scheme/SRFIs}}
{{libheader|Scheme/SRFIs}}
Similar to Python implementation of generating primes, the power of 2 is detected by first converting the number to binary representation, and check if it has only 1 "1" bit.
Similar to Python implementation of generating primes, the power of 2 is detected by first converting the number to binary representation, and check if it has only 1 "1" bit.
<lang scheme>(import (scheme base)
<syntaxhighlight lang="scheme">(import (scheme base)
(scheme inexact)
(scheme inexact)
(scheme read)
(scheme read)
Line 4,008: Line 4,008:


(display "Primes:\n")
(display "Primes:\n")
(generate-primes 20 2) ; create first 20 primes</lang>
(generate-primes 20 2) ; create first 20 primes</syntaxhighlight>
{{out}}
{{out}}
<pre>Task: 2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4
<pre>Task: 2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4
Line 4,016: Line 4,016:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "rational.s7i";
include "rational.s7i";


Line 4,051: Line 4,051:
end for;
end for;
writeln;
writeln;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,059: Line 4,059:


Program to compute prime numbers with fractran (The program has no limit, use CTRL-C to terminate it):
Program to compute prime numbers with fractran (The program has no limit, use CTRL-C to terminate it):
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigrat.s7i";
include "bigrat.s7i";


Line 4,087: Line 4,087:
begin
begin
fractran(2_, program);
fractran(2_, program);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,121: Line 4,121:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>var str ="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1"
<syntaxhighlight lang="ruby">var str ="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1"
const FractalProgram = str.split(',').map{.num} #=> array of rationals
const FractalProgram = str.split(',').map{.num} #=> array of rationals


Line 4,148: Line 4,148:


prime_generator(20, {|n| print (n, ' ') })
prime_generator(20, {|n| print (n, ' ') })
print "\n"</lang>
print "\n"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,157: Line 4,157:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6


oo::class create Fractran {
oo::class create Fractran {
Line 4,205: Line 4,205:
77/19 1/17 11/13 13/11 15/14 15/2 55/1
77/19 1/17 11/13 13/11 15/14 15/2 55/1
}]
}]
puts [$ft execute 2]</lang>
puts [$ft execute 2]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,211: Line 4,211:
</pre>
</pre>
You can just collect powers of 2 by monkey-patching in something like this:
You can just collect powers of 2 by monkey-patching in something like this:
<lang tcl>oo::objdefine $ft method pow2 {n} {
<syntaxhighlight lang="tcl">oo::objdefine $ft method pow2 {n} {
set co [coroutine [incr nco] my Generate 2]
set co [coroutine [incr nco] my Generate 2]
set pows {}
set pows {}
Line 4,222: Line 4,222:
return $pows
return $pows
}
}
puts [$ft pow2 10]</lang>
puts [$ft pow2 10]</syntaxhighlight>
Which will then produce this additional output:
Which will then produce this additional output:
<pre>
<pre>
Line 4,230: Line 4,230:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
<lang ti83b>100->T
<syntaxhighlight lang="ti83b">100->T
2->N
2->N
{17,78,19,23,29,77,95,77, 1,11,13,15,15,55}->LA
{17,78,19,23,29,77,95,77, 1,11,13,15,15,55}->LA
Line 4,248: Line 4,248:
J+1->J
J+1->J
End
End
End</lang>
End</syntaxhighlight>
Note:
Note:
-> stands for Store symbol
-> stands for Store symbol
Line 4,271: Line 4,271:
=={{header|VBA}}==
=={{header|VBA}}==
This implementations follows the Wikipedia description of [[wp:FRACTRAN|FRACTRAN]]. There are test, decrement and increment instructions on an array of variables which are the exponents of the prime factors of the argument, which are the only instructions used to run the program with the function run, or go through it step by step with the function steps. An auxiliary factor function is used to compile the FRACTRAN program.
This implementations follows the Wikipedia description of [[wp:FRACTRAN|FRACTRAN]]. There are test, decrement and increment instructions on an array of variables which are the exponents of the prime factors of the argument, which are the only instructions used to run the program with the function run, or go through it step by step with the function steps. An auxiliary factor function is used to compile the FRACTRAN program.
<lang vb>Option Base 1
<syntaxhighlight lang="vb">Option Base 1
Public prime As Variant
Public prime As Variant
Public nf As New Collection
Public nf As New Collection
Line 4,386: Line 4,386:
Debug.Print "First 30 primes:"
Debug.Print "First 30 primes:"
Debug.Print "after"; filter_primes(2, 30); "iterations."
Debug.Print "after"; filter_primes(2, 30); "iterations."
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>First 20 results:
<pre>First 20 results:
15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4 30
15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4 30
Line 4,397: Line 4,397:
{{libheader|Wren-big}}
{{libheader|Wren-big}}
Extra credit is glacially slow. We just find the first 10 primes which takes about 85 seconds.
Extra credit is glacially slow. We just find the first 10 primes which takes about 85 seconds.
<lang ecmascript>import "/big" for BigInt, BigRat
<syntaxhighlight lang="ecmascript">import "/big" for BigInt, BigRat


var isPowerOfTwo = Fn.new { |bi| bi & (bi - BigInt.one) == BigInt.zero }
var isPowerOfTwo = Fn.new { |bi| bi & (bi - BigInt.one) == BigInt.zero }
Line 4,427: Line 4,427:
System.print(fractran.call(program, 2, 20, false))
System.print(fractran.call(program, 2, 20, false))
System.print("\nFirst ten primes:")
System.print("\nFirst ten primes:")
System.print(fractran.call(program, 2, 10, true))</lang>
System.print(fractran.call(program, 2, 10, true))</syntaxhighlight>


{{out}}
{{out}}
Line 4,439: Line 4,439:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>var fracs="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17,"
<syntaxhighlight lang="zkl">var fracs="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17,"
"11/13, 13/11, 15/14, 15/2, 55/1";
"11/13, 13/11, 15/14, 15/2, 55/1";
fcn fractranW(n,fracsAsOneBigString){ //-->Walker (iterator)
fcn fractranW(n,fracsAsOneBigString){ //-->Walker (iterator)
Line 4,453: Line 4,453:
}
}
}.fp(Ref(n),fracs))
}.fp(Ref(n),fracs))
}</lang>
}</syntaxhighlight>
<lang zkl>fractranW(2,fracs).walk(20).println();</lang>
<syntaxhighlight lang="zkl">fractranW(2,fracs).walk(20).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,460: Line 4,460:
</pre>
</pre>
{{trans|Python}}
{{trans|Python}}
<lang zkl>var [const] BN=Import("zklBigNum"); // libGMP
<syntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"); // libGMP
fcn fractranPrimes{
fcn fractranPrimes{
foreach n,fr in ([1..].zip(fractranW(BN(2),fracs))){
foreach n,fr in ([1..].zip(fractranW(BN(2),fracs))){
Line 4,470: Line 4,470:
}
}
}
}
fractranPrimes();</lang>
fractranPrimes();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>