-2

I have seen this question but it doesn't work for negative numbers or numbers with (+) prefixes.

Here's what I want.

-20/8 = -5/2  
+28/-6 = -14/3  
-30/-4 = 15/2  
34/12 = 17/6
+40/6 = 20/3
32/+64 = 1/2
DavidNyan10
  • 163
  • 13
  • 2
    step one, calculate and save the sign you expect. step two, use the absolute value of the numbers in the code you've found, step three, apply the sign you saved to the result – Bravo Feb 21 '22 at 07:50
  • @Bravo Thank you! I'll try that in a min and see if that works. – DavidNyan10 Feb 21 '22 at 07:54

2 Answers2

0

Thanks to @Bravo I got this piece of code that works!

function reduce(num, den) {
    if (num.startsWith("+")) {
        num = num.substring(1);
    }
    if (den.startsWith("+")) {
        den = den.substring(1);
    }
    const neg = num < 0 != den < 0;
    num = Math.abs(num);
    den = Math.abs(den);
    var gcd = function gcd(a, b) {
        return !b ? a : gcd(b, a % b);
    };
    var g = gcd(num, den);
    return [neg ? "-" + num / g : num / g, den / g];
}

It works very well as expected.

DavidNyan10
  • 163
  • 13
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 21 '22 at 10:14
0

Try with that code :

function reduce(numerator,denominator,toString=false){
    var gcd = function gcd(a,b){
      return b ? gcd(b, a%b) : a;
    };
    gcd = gcd(numerator,denominator);
    var temp_num = numerator / gcd;
    var temp_deno= denominator / gcd;

    if(temp_deno < 0 ){
        temp_deno *= -1;
        temp_num *= -1;
    }

    var result = [temp_num, temp_deno];
    if(toString){
        return result.toString().replace(',','/');
    }
    return result;
  }

// Test : true for returning string
console.log(reduce(-20,8,true));    //-5/2  
console.log(reduce(+28,-6,true));   //-14/3 
console.log(reduce(-30,-4,true));   //15/2
console.log(reduce(34,12,true));    //17/6
console.log(reduce(+40,6,true));    //20/3
console.log(reduce(32,+64,true));   //1/2

Nay Lin Aung
  • 164
  • 9