Is it possible to convert fraction to decimal using only addition and subtraction?

109 Views Asked by At

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?

3

There are 3 best solutions below

0
On

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$.

0
On

Presumably multiplying and dividing by a power of ten is allowed (i.e. just adding or removing trailing zeros or moving the decimal point). If so, then simply multiply your number $x$ by 1000, and then do your division routine, and then divide your answer by 1000 afterward.

0
On

Hint: This example using arbitrary numbers suggests a solution without spelling it out explicitly. (I am assuming that your inputs are integers, and you would like to return a decimal approximation of the quotient.)

$$ \frac{168}{23} \approx 7.3043 \quad \text{and} \quad \frac{168 \cdot 10^4}{23} = \frac{1\,680\,000}{23} \approx 73043 $$

Questions that you should ask yourself (or me if you're stuck):

  • Does this always work?
  • Why does this work? (Answering this will give an answer to the first question.)
  • Why the exponent $4$ in $10^4$?