Continued fraction/Arithmetic/Construct from rational number: Difference between revisions

Add Factor example
(Add Factor example)
Line 570:
else let q = n / d in (decimal)q :: (rI2cf d (n - q * d))
</lang>
 
=={{header|Factor}}==
Note that the input values are stored as strings and converted to numbers before being fed to <code>r2cf</code>. This is because ratios automatically reduce themselves to the lowest-terms mixed number, which would make for confusing output in this instance.
<lang factor>USING: formatting kernel lists lists.lazy math math.parser qw
sequences ;
IN: rosetta-code.cf-arithmetic
 
: r2cf ( x -- lazy )
[ >fraction [ /mod ] keep swap [ ] [ / ] if-zero nip ]
lfrom-by [ integer? ] luntil [ >fraction /i ] lmap-lazy ;
 
: main ( -- )
qw{
1/2
3
23/8
13/11
22/7
-151/77
14142/10000
141421/100000
1414214/1000000
14142136/10000000
31/10
314/100
3142/1000
31428/10000
314285/100000
3142857/1000000
31428571/10000000
314285714/100000000
}
[ dup string>number r2cf list>array "%19s -> %u\n" printf ]
each ;
MAIN: main</lang>
{{out}}
<pre>
1/2 -> { 0 2 }
3 -> { 3 }
23/8 -> { 2 1 7 }
13/11 -> { 1 5 2 }
22/7 -> { 3 7 }
-151/77 -> { -1 -1 -24 -1 -2 }
14142/10000 -> { 1 2 2 2 2 2 1 1 29 }
141421/100000 -> { 1 2 2 2 2 2 2 3 1 1 3 1 7 2 }
1414214/1000000 -> { 1 2 2 2 2 2 2 2 3 6 1 2 1 12 }
14142136/10000000 -> { 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 }
31/10 -> { 3 10 }
314/100 -> { 3 7 7 }
3142/1000 -> { 3 7 23 1 2 }
31428/10000 -> { 3 7 357 }
314285/100000 -> { 3 7 2857 }
3142857/1000000 -> { 3 7 142857 }
31428571/10000000 -> { 3 7 476190 3 }
314285714/100000000 -> { 3 7 7142857 }
</pre>
 
=={{header|Go}}==
1,827

edits