Fractran: Difference between revisions

Content added Content deleted
m (Added reference to library "bignum".)
Line 2,615: Line 2,615:
19: 4
19: 4
20: 30</pre>
20: 30</pre>

Here is a different approach using NestWhileList:
<lang Mathematica>
fractran[
program : {__ ? (Element[#, PositiveRationals] &)}, (* list of positive fractions *)
n0_Integer, (* initial state *)
maxSteps : _Integer : Infinity] := (* max number of steps *)
NestWhileList[ (* Return a list representing the evolution of the state n *)
Function[n, SelectFirst[IntegerQ][program * n]], (* Select first integer in n*program, if none return Missing *)
n0,
Not @* MissingQ, (* continue while the state is not Missing *)
1,
maxSteps]

$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]
</lang>

{{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}</pre>

Extract the prime numbers encoded as powers of 2 in the previous list:
<lang Mathematica>
Select[IntegerQ] @ Log2[fractran[$PRIMEGAME, 2, 10000]]
</lang>
{{out}}
<pre>{1, 2, 3, 5, 7, 11, 13, 17}</pre>

=={{header|Nim}}==
=={{header|Nim}}==
=== Using fractions===
=== Using fractions===