HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Convert Improper Fraction to Mixed Number with JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberconvertwithjavascriptimproperfractionmixed

Problem

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.

Solution

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];
}

Code Snippets

function improperFractionToMixedNumber(n, d) {
    i = parseInt(n / d);
    n -= i * d;
    return [i, n, d];   
}
// 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];
}

Context

StackExchange Code Review Q#20854, answer score: 3

Revisions (0)

No revisions yet.