Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

My function converts an improper fraction to a mixed number (it does not AND should not simplify the fraction).

// Improper fraction to mixed number
// n = numerator
// d = denominator
// i = number
function improperFractionToMixedNumber(n, d) {
    i = (n / d) >> 0;

    n -= i * d;

    return [i, n, d];   
}

// Convert 14/4 to mixed number
improperFractionToMixedNumber(14, 4); // 3, 2, 4

Can this be improved or simplified?

I don't care for this part:

i = (n / d) >> 0;

But it's the only way I could figure out how to see how many times a number equally divides into another number.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

What you're doing with i = (n / d) >> 0 is a sign-propagating right shift. The interesting this is, you're doing a right shift by 0 (I'd imagine because you'd otherwise get NaN. Your method of doing so is a cheap version (read: performance hack?) of doing i = parseInt(n / d). Here's your function with the SPRS removed and replaced with parseInt() instead. I've also implemented simplification.

function improperFractionToMixedNumber(n, d) {
    i = parseInt(n / d);
    n -= i * d;
    return [i, n, d];   
}

Here is the same function, but also implementing simplification via a helper function reduce:

// Improper fraction to mixed number
// n = numerator
// d = denominator
// i = number
function improperFractionToMixedNumber(n, d) {
    i = parseInt(n / d);
    n -= i * d;
    return [i, reduce(n,d)];   
}


function reduce(numerator,denominator){
    if (isNaN(numerator) || isNaN(denominator))
      return NaN;
    var gcd = function gcd(a, b){ return b ? gcd(b, a%b) : a; };
    gcd = gcd(numerator, denominator);
    return [numerator/gcd, denominator/gcd];
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.