エジプトの分数
Unknown programmer's programming note.
1. プログラムの概要
egypfrac - 分数を分子が1の分数の和で表す
2. C
/* * 出典元「C言語による最新アルゴリズム事典」奥村晴彦著 - P14 * インデントは変更してあります。 * 他にも、メッセージや変数名や処理を変更している場合があります。 */ #include <stdio.h> int main() { int m, n, q; printf("numerator m=? "); scanf("%d", &m); printf("denominator n=? "); scanf("%d", &n); printf("%d/%d = ", m, n); while (n % m != 0) { q = n / m + 1; printf("1/%d + ", q); m = m * q - n; n = n * q; } printf("1/%d\n", n / m); }
3. Emacs Lisp
(let ((m (read-number "numerator m=? ")) (n (read-number "denominator n=? ")) q) (message (with-output-to-string (princ (format "%d/%d = " m n)) (while (not (zerop (% n m))) (setq q (+ (/ n m) 1)) (princ (format "1/%d + " q)) (setq m (- (* m q) n)) (setq n (* n q))) (princ (format "1/%d" (/ n m))))))
4. Bash
#!/bin/bash read -p "numerator m=? " m read -p "denominator n=? " n printf "%d/%d = " $m $n while [ $(( $n % $m )) -ne 0 ] do q=$(( $n / $m + 1)) printf "1/%d + " $q m=$(( $m * $q - $n)) n=$(( $n * $q )) done printf "1/%d\n" $(($n / $m ))
5. Fish
#!/usr/bin/fish read -P "numerator m=? " m read -P "denominator n=? " n printf "%d/%d = " $m $n while test (math $n % $m ) -ne 0 set q (math -s0 $n / $m + 1) printf "1/%d + " $q set m (math "$m * $q - $n") set n (math "$n * $q") end printf "1/%d\n" (math -s0 $n / $m)