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

Content added Content deleted
m (→‎{{header|C}}: Remove vanity tags)
Line 1,333: Line 1,333:
As a silly one-liner:
As a silly one-liner:
<lang perl6>sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }</lang>
<lang perl6>sub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }</lang>

=={{header|Phix}}==
{{trans|C}}
<lang Phix>function r2cf(sequence fraction)
integer {numerator, denominator} = fraction
integer quotient = 0
if denominator!=0 then
quotient = floor(numerator/denominator)
{numerator,denominator} = {denominator,mod(numerator,denominator)}
end if
return {quotient,{numerator,denominator}}
end function

constant DENOMINATOR = 2
procedure test(string txt, sequence tests)
sequence fraction
integer quotient
printf(1,"Running %s :",{txt})
for i=1 to length(tests) do
fraction = tests[i]
printf(1,"\nFor N = %d, D = %d :",fraction)
while fraction[DENOMINATOR]!=0 do
{quotient,fraction} = r2cf(fraction)
printf(1," %d ",quotient)
end while
end for
printf(1,"\n\n")
end procedure

constant examples = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}},
sqrt2 = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}},
pi = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}}
test("the examples",examples)
test("for sqrt(2)",sqrt2)
test("for pi",pi)</lang>
{{out}}
<pre>
Running the examples :
For N = 1, D = 2 : 0 2
For N = 3, D = 1 : 3
For N = 23, D = 8 : 2 1 7
For N = 13, D = 11 : 1 5 2
For N = 22, D = 7 : 3 7
For N = -151, D = 77 : -2 25 1 2

Running for sqrt(2) :
For N = 14142, D = 10000 : 1 2 2 2 2 2 1 1 29
For N = 141421, D = 100000 : 1 2 2 2 2 2 2 3 1 1 3 1 7 2
For N = 1414214, D = 1000000 : 1 2 2 2 2 2 2 2 3 6 1 2 1 12
For N = 14142136, D = 10000000 : 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2

Running for pi :
For N = 31, D = 10 : 3 10
For N = 314, D = 100 : 3 7 7
For N = 3142, D = 1000 : 3 7 23 1 2
For N = 31428, D = 10000 : 3 7 357
For N = 314285, D = 100000 : 3 7 2857
For N = 3142857, D = 1000000 : 3 7 142857
For N = 31428571, D = 10000000 : 3 7 476190 3
For N = 314285714, D = 100000000 : 3 7 7142857
</pre>


=={{header|Python}}==
=={{header|Python}}==