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

(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
Line 433:
(R2CF 3141592653589793 1000000000000000) ; (3 7 15 1 292 1 1 1 2 1 3 1 14 4 2 3 1 12 5 1 5 20 1 11 1 1 1 2)
</pre>
 
=={{header|D}}==
{{trans|Kotlin}}
<lang D>import std.concurrency;
import std.stdio;
 
struct Pair {
int first, second;
}
 
auto r2cf(Pair frac) {
return new Generator!int({
auto num = frac.first;
auto den = frac.second;
while (den != 0) {
auto div = num / den;
auto rem = num % den;
num = den;
den = rem;
div.yield();
}
});
}
 
void iterate(Generator!int seq) {
foreach(i; seq) {
write(i, " ");
}
writeln();
}
 
void main() {
auto fracs = [
Pair( 1, 2),
Pair( 3, 1),
Pair( 23, 8),
Pair( 13, 11),
Pair( 22, 7),
Pair(-151, 77),
];
foreach(frac; fracs) {
writef("%4d / %-2d = ", frac.first, frac.second);
frac.r2cf.iterate;
}
writeln;
 
auto root2 = [
Pair( 14_142, 10_000),
Pair( 141_421, 100_000),
Pair( 1_414_214, 1_000_000),
Pair(14_142_136, 10_000_000),
];
writeln("Sqrt(2) ->");
foreach(frac; root2) {
writef("%8d / %-8d = ", frac.first, frac.second);
frac.r2cf.iterate;
}
writeln;
 
auto pi = [
Pair( 31, 10),
Pair( 314, 100),
Pair( 3_142, 1_000),
Pair( 31_428, 10_000),
Pair( 314_285, 100_000),
Pair( 3_142_857, 1_000_000),
Pair( 31_428_571, 10_000_000),
Pair(314_285_714, 100_000_000),
];
writeln("Pi ->");
foreach(frac; pi) {
writef("%9d / %-9d = ", frac.first, frac.second);
frac.r2cf.iterate;
}
}</lang>
 
{{out}}
<pre> 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
 
Sqrt(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
 
Pi ->
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|F_Sharp|F#}}==
1,452

edits