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

Line 2,453:
 
<pre>$ m4 continued-fraction-from-rational.m4
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|Make}}==
===GNU Make and POSIX shell===
<syntaxhighlight lang="make">
.SILENT:
.DEFAULT_GOAL := start-here
 
define r2cf =
M=`expr $(1)`; \
N=`expr $(2)`; \
printf '%d/%d => ' $$M $$N; \
SEP='['; \
while test $$N -ne 0; do \
printf "%s%d" "$$SEP" `expr $$M '/' $$N`; \
if test "$$SEP" = '['; then SEP='; '; else SEP=', '; fi; \
R=`expr $$M '%' $$N`; \
M=$$N; \
N=$$R; \
done
printf ']\n'
endef
 
start-here:
$(call r2cf, 1, 2)
$(call r2cf, 3, 1)
$(call r2cf, 23, 8)
$(call r2cf, 13, 11)
$(call r2cf, 22, 7)
$(call r2cf, -151, 77)
 
$(call r2cf, 14142, 10000)
$(call r2cf, 141421, 100000)
$(call r2cf, 1414214, 1000000)
$(call r2cf, 14142136, 10000000)
 
$(call r2cf, 31, 10)
$(call r2cf, 314, 100)
$(call r2cf, 3142, 1000)
$(call r2cf, 31428, 10000)
$(call r2cf, 314285, 100000)
$(call r2cf, 3142857, 1000000)
$(call r2cf, 31428571, 10000000)
$(call r2cf, 314285714, 100000000)
</syntaxhighlight>
 
{{out}}
 
<pre>$ make -f continued-fraction-from-rational.mk
1/2 => [0; 2]
3/1 => [3]
1,448

edits