The problem stated that we need to find the Egyptian fraction sequence given the numerator and denomintor. So I started out with a simple python psuedo code implementation:
ef = []
while nr != 0:
x = ceil(dr/nr)
ef += [x]
# Update remainder values of numerator and denominator
nr *= x
nr -= dr
dr *= x
Wrote the entire program in python, with type annotations for added ease of conversion to rust.
import math
from typing import List
def egyptianize(nr: int, dr: int) -> List[int]:
ef = []
while nr != 0:
x = math.ceil(dr/nr)
ef.append(x)
nr = x * nr - dr
dr *= x
return ef
def main():
facts = egyptianize(4, 13)
for i in range(len(facts)):
x = "\n" if i == len(facts)-1 else "+ "
print(f'1/{facts[i]} {x}', end="")
if __name__=="__main__":
main()
And finally, with ease translated the logic into rust-lang.
fn egyptianize(mut nr: i32, mut dr: i32) -> Vec<i32> {
let mut ef = Vec::<i32>::new();
while nr != 0 {
let x = ((dr as f64)/(nr as f64)).ceil() as i32;
ef.push(x);
nr = x * nr - dr;
dr *= x;
}
ef
}
fn main() {
let facts = egyptianize(4, 13);
for i in 0..facts.len() {
print!("1/{} {}", facts[i], if i == facts.len()-1 {"\n"} else {"+ "});
}
}
Hope you find this simple explanation beneficial. You can find the code ready to execute and play with here.