I am working on a programming challenge that requires me to implement addition, division, and modulo using only addition and subtraction. Cool, simple enough:
function multiply(x, y) {
var result = 0;
for (var i = 0; i < x;i++) {
result = result + y
}
return result;
};
function divide(x, y) {
var count = 0;
while (x > y) {
if (x >= y)
count = count + 1;
x = x - y;
}
return count;
};
My divide function only works with whole numbers though. I need it to be accurate to 3 decimal places. There are plenty of solutions of how to do this online, but none of them take into account the constraints I have. How can I convert fraction to decimal using only addition and subtraction?
Suppose that you want $m\div n$, accurate to three decimal places. Use subtraction to calculate $10000m\div n$ as quotient and remainder. Say that the quotient is $d_k\ldots d_1$ as a string of digits. Drop $d_1$, and if $d_1\ge 5$, add $1$ to $d_k\ldots d_2$. Then insert a decimal point in front of $d_4$.