ある分数を,分子が 1 の分数の和で表す
1/3 でも,1/4 + 1/12 のようにすること
EgyptianFraction = function(numerator, denominator) {
EF = function(numerator, denominator) {
denominator2 = 1
repeat {
denominator2 = denominator2 + 1
if (denominator < numerator * denominator2)
break
}
answer <<- c(answer, denominator2)
numerator2 = numerator * denominator2 - denominator
denominator2 = denominator * denominator2
gcd = GCD(numerator2, denominator2)
numerator2 = numerator2/gcd
denominator2 = denominator2/gcd
if (numerator2 == 1)
answer <<- c(answer, denominator2)
else if (numerator2 != 0)
Recall(numerator2, denominator2)
}
GCD = function(x, y) {
while (y%%x != 0) {
t = y%%x
y = x
x = t
}
x
}
cat("\n", numerator, "/", denominator, "== ")
answer = NULL
EF(numerator, denominator)
cat(sub("^ \\+ ", "", paste(" + 1 /", answer, collapse = "")), "\n")
check = TRUE
if (check == TRUE) {
library(gmp)
left = as.bigq(numerator)/as.bigq(denominator)
right = sum(as.bigq(1)/answer)
print(left, initLine = FALSE)
print(right, initLine = FALSE)
if (left != right) {
cat("Warning! wrong answer\n")
cat(numerator, denominator, "\n")
}
}
invisible(answer)
}
EgyptianFraction(3, 5)
EgyptianFraction(5, 7)
EgyptianFraction(1, 3)
dat = cbind(numerator = c(66, 80, 2, 235, 40, 168, 72, 146, 5, 112, 148, 95, 106, 210, 92, 31,
137, 177, 30, 22), denominator = c(152, 416, 90, 300, 159, 340, 115, 451, 6, 254, 285, 247,
206, 377, 228, 222, 218, 398, 94, 39))
options(scipen = 10)
for (i in 1:20) {
EgyptianFraction(dat[i, 1], dat[i, 2])
}