creating a fraction or decimal using only addition or subtraction

108 Views Asked by At

how do i create a decimal or a fraction by only using addition or subtract? I have the numbers 1 and 2, and I want to end up with .5 -- have been stuck on this for quite a bit! I cannot just do 1/2, I have to somehow use only addition or subtraction.

var divide = function(x, y) {
    //the number of times you need to subtract y from x.

  if (y === 0) {
    return 0
  } 
  // if 
  if (x - y === 0) {
    return 1;
  } 
  if (x < y) {
    return 0; <--- this is where the problem is 
  } else {
    return (1 + divide(x - y, y)); // need to get this toFixed somehow.  
  }

};
2

There are 2 best solutions below

3
On BEST ANSWER

If you're restricted to integers, then you can't.

The integers are closed under addition. (In other words, adding two integers gives you another integer.) Same for subtraction.

0
On

First you need to decide whether you want your answer as a fraction with denominator as a power of 2 or as a decimal (a fraction with denominator as a power of 10).

Let's suppose you are going to go for the fraction with denominator as a power of 2 and that you have decided that you are happy to work to the nearest $\frac 1 {16}$.

To demonstrate, I will give the example of 5 divided by 7: a half is too easy!

Start by adding 5 to 5 - gives you 10.

Then add 10 to 10 - gives you 20.

Then add 20 to 20 - gives you 40.

Then add 40 to 40 - gives you 80.

We do this adding four times because $16=2^4$. For greater accuracy we would add more times.

Now subtract 7 repeatedly and increment your counter as you go.

You can subtract 11 times until you reach a value less than 7.

Stop.

Your answer is $\frac 57 \approx \frac {11}{16}$