Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
Javascript: Prime Factorization
Today’s code is a enhancement of Code Renaissance‘s version of “Finding Prime Numbers in Javascript”.
Main difference are the following.
Faster performance by eliminating recursion and caching Math.sqrt.
Whole numbers bigger than 1 return an empty array, since they’re not prime numbers.
Decimal values are converted to whole numbers.
/**
* @author Larry Battle - http://bateru.com/news/contact-me
* @date May 11, 2012
* @license MIT and GPL v3
* @purpose Return the prime factors of a number.
* @info - http://bateru.com/news/?s=prime+factors
*/var getPrimeFactors =function(num){
num =Math.floor(num);var root, factors =[], x, sqrt =Math.sqrt, doLoop =1< num;
while( doLoop ){
root = sqrt(num);
x =2;if(num % x){
x =3;
while ((num % x)&&((x +=2)< root));}
x =(x > root)? num : x;
factors.push(x);
doLoop =( x != num );
num /= x;}return factors;}
/**
* @author Larry Battle - http://bateru.com/news/contact-me
* @date May 11, 2012
* @license MIT and GPL v3
* @purpose Return the prime factors of a number.
* @info - http://bateru.com/news/?s=prime+factors
*/
var getPrimeFactors = function(num) {
num = Math.floor(num);
var root, factors = [], x, sqrt = Math.sqrt, doLoop = 1 < num;
while( doLoop ){
root = sqrt(num);
x = 2;
if (num % x) {
x = 3;
while ((num % x) && ((x += 2) < root));
}
x = (x > root) ? num : x;
factors.push(x);
doLoop = ( x != num );
num /= x;
}
return factors;
}
I love to program, and discover new tech.
Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
In javascript, Number.prototype.toFixed has problems rounding.
Here’s the fix and some test cases.
Number.prototype.toFixed=(function(){var oldToFixed =Number.prototype.toFixed;returnfunction(precision){var value =this.toString(), power =Math.pow(10, precision ||0);return oldToFixed.call((Math.round(value * power)/ power), precision);};}());
Number.prototype.toFixed = (function () {
var oldToFixed = Number.prototype.toFixed;
return function (precision) {
var value = this.toString(), power = Math.pow(10, precision || 0);
return oldToFixed.call((Math.round(value * power) / power), precision);
};
}());
Here’s a simple test.
// Programmer: Larry Battle// Link: http://bateru.com/news/2012/03/code-of-the-day-fix-for-number-prototype-tofixed(function(root){"use strict";var log =function( str ){
root.document.body.innerHTML+="log: "+ str +"<br/>";},
assert =function(a, b ){var message = a +' !== '+ b;
message +=( a === b )?"=> true":"=> false";
log( message );};
assert((0.595).toFixed(2),"0.59");
assert((0.9).toFixed(0),"1");Number.prototype.toFixed=(function(){var oldToFixed =Number.prototype.toFixed;returnfunction(precision){var value =this.toString(), power =Math.pow(10, precision ||0);return oldToFixed.call((Math.round(value * power)/ power), precision);};}());
log("Applying the toFixed fix.");
assert((0.595).toFixed(2),"0.60");
assert((0.9).toFixed(0),"1");}(this));
// Programmer: Larry Battle
// Link: http://bateru.com/news/2012/03/code-of-the-day-fix-for-number-prototype-tofixed
(function (root) {
"use strict";
var log = function( str ){
root.document.body.innerHTML += "log: " + str + "<br/>";
},
assert = function (a, b ) {
var message = a + ' !== ' + b;
message += ( a === b ) ? "=> true" : "=> false";
log( message );
};
assert((0.595).toFixed(2), "0.59");
assert((0.9).toFixed(0), "1");
Number.prototype.toFixed = (function () {
var oldToFixed = Number.prototype.toFixed;
return function (precision) {
var value = this.toString(), power = Math.pow(10, precision || 0);
return oldToFixed.call((Math.round(value * power) / power), precision);
};
}
());
log("Applying the toFixed fix.");
assert((0.595).toFixed(2), "0.60");
assert((0.9).toFixed(0), "1");
}(this));
I love to program, and discover new tech.
Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
A few days ago I noticed that my “code of the day” article was wrong. So I spent some time fixing it and provided test cases to check my work.
The main difference about this script is that it allows you to support both the SI and IEC standard and fixes a few rounding errors.
// function: getBytesWithUnit// input: bytes (number)// input: useSI (boolean), if true then uses SI standard (1KB = 1000bytes), otherwise uses IEC (1KiB = 1024 bytes)// input: precision (number), sets the maximum length of decimal places.// input: useSISuffix (boolean), if true forces the suffix to be in SI standard. Useful if you want 1KB = 1024 bytes// returns (string), represents bytes is the most simplified form.var getBytesWithUnit =function(bytes, useSI, precision, useSISuffix){"use strict";if(!(!isNaN(bytes)&&+bytes >-1&& isFinite(bytes))){returnfalse;}var units, obj, amountOfUnits, unitSelected, suffix;
units =['bytes','KB','MB','GB','TB','PB','EB','ZB','YB'];
obj ={
base : useSI ?10:2,
unitDegreeDiff : useSI ?3:10};
amountOfUnits =Math.max(0,Math.floor(Math.round(Math.log(+bytes)/Math.log(obj.base)* 1e6)/ 1e6));
unitSelected =Math.floor(amountOfUnits / obj.unitDegreeDiff);
unitSelected = units.length> unitSelected ? unitSelected : units.length-1;
suffix =(useSI || useSISuffix)? units[unitSelected]: units[unitSelected].replace('B','iB');
bytes =+bytes /Math.pow(obj.base, obj.unitDegreeDiff* unitSelected);
precision = precision ||3;if(bytes.toString().length> bytes.toFixed(precision).toString().length){
bytes = bytes.toFixed(precision);}return bytes +" "+ suffix;};
// function: getBytesWithUnit
// input: bytes (number)
// input: useSI (boolean), if true then uses SI standard (1KB = 1000bytes), otherwise uses IEC (1KiB = 1024 bytes)
// input: precision (number), sets the maximum length of decimal places.
// input: useSISuffix (boolean), if true forces the suffix to be in SI standard. Useful if you want 1KB = 1024 bytes
// returns (string), represents bytes is the most simplified form.
var getBytesWithUnit = function (bytes, useSI, precision, useSISuffix) {
"use strict";
if (!(!isNaN(bytes) && +bytes > -1 && isFinite(bytes))) {
return false;
}
var units, obj, amountOfUnits, unitSelected, suffix;
units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
obj = {
base : useSI ? 10 : 2,
unitDegreeDiff : useSI ? 3 : 10
};
amountOfUnits = Math.max(0, Math.floor(Math.round(Math.log(+bytes) / Math.log(obj.base) * 1e6) / 1e6));
unitSelected = Math.floor(amountOfUnits / obj.unitDegreeDiff);
unitSelected = units.length > unitSelected ? unitSelected : units.length - 1;
suffix = (useSI || useSISuffix) ? units[unitSelected] : units[unitSelected].replace('B', 'iB');
bytes = +bytes / Math.pow(obj.base, obj.unitDegreeDiff * unitSelected);
precision = precision || 3;
if (bytes.toString().length > bytes.toFixed(precision).toString().length) {
bytes = bytes.toFixed(precision);
}
return bytes + " " + suffix;
};
Demo: Test Script here
Want to learn more about Javascript?
Check out this “Professional JavaScript for Web Developers”.
I love to program, and discover new tech.
Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
/**
@function dec2frac
@returns string
@purpose Convert a decimal to a fraction
*/function dec2frac(d){var df =1, top =1, bot =1;var limit = 1e5;//Increase the limit to get more precision.
while (df != d && limit-->0){if(df < d){
top +=1;}else{
bot +=1;
top = parseInt(d * bot,10);}
df = top / bot;}return top +'/'+ bot;}
/**
@function dec2frac
@returns string
@purpose Convert a decimal to a fraction
*/
function dec2frac(d) {
var df = 1, top = 1, bot = 1;
var limit = 1e5; //Increase the limit to get more precision.
while (df != d && limit-- > 0) {
if (df < d) {
top += 1;
}
else {
bot += 1;
top = parseInt(d * bot, 10);
}
df = top / bot;
}
return top + '/' + bot;
}
I love to program, and discover new tech.
Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.