This code is supposed to simplify fractions and convert decimals to fractions but when I put in fractions with larger dividens (numbers more than 7 or 8 digits) it lags a great amount.
http://jsfiddle.net/SuperBoi45/vQjgx/
var fraction = {};
fraction.simplify = function( frac ) {
if ( frac.indexOf('/') < 0 ) return frac;
var numbers = frac.split('/'),
factor = null,
parsed = null;
return (function run( nums ) {
factor = fraction.factor( nums[0], nums[1] );
if ( factor === 1 ) {
parsed = [ Math.abs(nums[0]), Math.abs(nums[1]) ];
if ( nums[1] === 1 ) return nums[0];
else if ( nums[1] === -1 ) return -nums[0];
else if ( nums[0] < 0 && nums[1] < 1 ) return parsed[0] + '/' + parsed[1];
else if ( nums[0] < 0 || nums[1] < 0 ) return '-' + parsed[0] + '/' + parsed[1];
else return nums[0] + '/' + nums[1];
}
return run( [ nums[0] / factor, nums[1] / factor ] );
})( numbers );
};
fraction.convert = function( decimal ) {
var j = decimal.length - 1,
b = "1";
if ( decimal.indexOf(".") >= 0 && decimal.length > 1 ) {
while ( decimal.charAt( j ) != "." ) {
b += "0";
j--;
}
decimal *= b;
decimal += "/" + b;
}
return decimal;
};
fraction.factor = (function() {
var greater = function( a, b ) {
return a > b ? a : b;
};
return function( x, y ) {
x = Math.abs( x );
y = Math.abs( y );
var a = greater( x, y ),
i = a,
b = ( i === x ) ? y : x;
for ( ; i >= 1; i-- ) {
if ( a % i === 0 && b % i === 0 ) return i;
}
return 1;
};
})();
I’m trying to make it work like Wolfram Alpha because you can put in fractions with large dividens and it doesn’t freeze one bit when showing you its quick-rendered result.
Can anyone fix this code to work with larger numbers. I’d figure you’d have to use a different algorithm than mine. On the other hand, does anyone know WA’s algorithm or can direct me to a site where I can find out?
Replace
fraction.factor()with this:That’s Euclid’s algorithm, which can serve as a great introduction to Number Theory. It’ll run way faster than your iterative approach.