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

Line 2,716:
As a silly one-liner:
<syntaxhighlight lang="raku" line>sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }</syntaxhighlight>
 
=={{header|RATFOR}}==
{{works with|ratfor77|[https://sourceforge.net/p/chemoelectric/ratfor77/ public domain 1.0]}}
{{works with|gfortran|12.2.1}}
 
To get nice output with f2c would have been more tedious than I felt like doing, and so the I/O facilities employed here are more advanced than often was the case with an historical FORTRAN77 compiler.
 
<syntaxhighlight lang="ratfor">
# This implementation assumes the I/O facilities of gfortran, and so
# is not suited to f2c as the FORTRAN77 compiler.
 
function r2cf (N1, N2)
implicit none
 
integer N1, N2
integer r2cf
 
integer r
 
# We will use division with rounding towards zero, which is the
# native integer division method of FORTRAN77.
r2cf = N1 / N2
r = mod (N1, N2)
 
N1 = N2
N2 = r
end
 
subroutine wrr2cf (N1, N2) # Write r2cf results.
implicit none
 
integer N1, N2
integer r2cf
integer digit, M1, M2
integer sep
 
write (*, '(I0, "/", I0, " => ")', advance = "no") N1, N2
 
M1 = N1
M2 = N2
sep = 0
while (M2 != 0)
{
digit = r2cf (M1, M2)
if (sep == 0)
{
write (*, '("[", I0)', advance = "no") digit
sep = 1
}
else if (sep == 1)
{
write (*, '("; ", I0)', advance = "no") digit
sep = 2
}
else
{
write (*, '(", ", I0)', advance = "no") digit
}
}
write (*, '("]")', advance = "yes")
end
 
program demo
implicit none
 
call wrr2cf (1, 2)
call wrr2cf (3, 1)
call wrr2cf (23, 8)
call wrr2cf (13, 11)
call wrr2cf (22, 7)
call wrr2cf (-151, 77)
 
call wrr2cf (14142, 10000)
call wrr2cf (141421, 100000)
call wrr2cf (1414214, 1000000)
call wrr2cf (14142136, 10000000)
 
call wrr2cf (31, 10)
call wrr2cf (314, 100)
call wrr2cf (3142, 1000)
call wrr2cf (31428, 10000)
call wrr2cf (314285, 100000)
call wrr2cf (3142857, 1000000)
call wrr2cf (31428571, 10000000)
call wrr2cf (314285714, 100000000)
end
</syntaxhighlight>
 
{{out}}
 
<pre>$ (ratfor77 continued-fraction-from-rational.r | gfortran -x f77 -) && ./a.out
1/2 => [0; 2]
3/1 => [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|REXX}}==
1,448

edits