Skill: comparing-fractions
Fraction Comparator
Enter two fractions and see the verdict three ways: cross-multiplication, common denominator, and benchmark distance.
Fraction comparator
Three ways to compare
Cross-multiplication, a common denominator, or benchmarks (0, 1/2, 1) — all three must agree.
/* == PURE (tested by test_tool.js) == */
function tCmpGcd(a, b){ a = Math.abs(a); b = Math.abs(b); while (b){ var t = a % b; a = b; b = t; } return a; }
function tCompareInfo(n1, d1, n2, d2){
n1 = Math.round(n1); d1 = Math.round(d1); n2 = Math.round(n2); d2 = Math.round(d2);
if (d1 <= 0 || d2 <= 0) return { ok: false, err: 'Denominators must be positive.' };
var L = n1 * d2, R = n2 * d1;
var c = L < R ? '<' : (L > R ? '>' : '=');
var lcm = d1 / tCmpGcd(d1, d2) * d2;
return { ok: true, n1: n1, d1: d1, n2: n2, d2: d2, cmp: c,
cross1: L, cross2: R, lcd: lcm,
r1n: n1 * lcm / d1, r2n: n2 * lcm / d2,
dec1: n1 / d1, dec2: n2 / d2 };
}
/* == /PURE == */
/* == PURE (tested by test_tool.js) == */ function tCmpGcd(a, b){ a = Math.abs(a); b = Math.abs(b); while (b){ var t = a % b; a = b; b = t; } return a; } function tCompareInfo(n1, d1, n2, d2){ n1 = Math.round(n1); d1 = Math.round(d1); n2 = Math.round(n2); d2 = Math.round(d2); if (d1 <= 0 || d2 <= 0) return { ok: false, err: 'Denominators must be positive.' }; var L = n1 * d2, R = n2 * d1; var c = L < R ? '<' : (L > R ? '>' : '='); var lcm = d1 / tCmpGcd(d1, d2) * d2; return { ok: true, n1: n1, d1: d1, n2: n2, d2: d2, cmp: c, cross1: L, cross2: R, lcd: lcm, r1n: n1 * lcm / d1, r2n: n2 * lcm / d2, dec1: n1 / d1, dec2: n2 / d2 }; } /* == /PURE == */
(function(){ 'use strict'; function $(id){ return document.getElementById(id); } function render(){ var n1 = parseInt($('inN1').value, 10), d1 = parseInt($('inD1').value, 10); var n2 = parseInt($('inN2').value, 10), d2 = parseInt($('inD2').value, 10); var out = $('toolOut'); var r = tCompareInfo(n1, d1, n2, d2); if (!r.ok){ out.innerHTML = '
' + r.err + '
'; return; } var h = '
' + r.n1 + '/' + r.d1 + ' ' + r.cmp + ' ' + r.n2 + '/' + r.d2 + '
'; h += '
'; h += '
'; h += '
'; out.innerHTML = h; } $('calcBtn').addEventListener('click', render); render(); })();