Code of the Day: Javascript, Prime Factors of a Number


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.

  1. Faster performance by eliminating recursion and caching Math.sqrt.
  2. Whole numbers bigger than 1 return an empty array, since they’re not prime numbers.
  3. 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;
}

Example:
getPrimeFactors(15120) // returns [2, 2, 2, 3, 3, 3, 7]

Demo:

Larry Battle

Larry Battle

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.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Qunit Template


Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

QUnit JSFiddle.net Template
http://jsfiddle.net/tWyHg/1/

Larry Battle

Larry Battle

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.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

A quick comparison between == vs equals in Java


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

/**
@author Larry Battle <bateru.com/news>
@date April 19, 2012
@purpose To show a simple comparison between == and equals().
*/
 
public class SameObjectTest {
	public static boolean areAssertsEnabled(){
		boolean isEnabled = false;
		try{
			assert false: "Yes asserts are enabled.";
		}catch( AssertionError e ){
			isEnabled = true;
		}
		return isEnabled;
	}
	public static void main(String[] args ){
		// All asserts should be without an error.
		String message = "Test Completed with no errors.";
		int[] ints = new int[]{ 10, 10, 20 };
		String[] strings = new String[]{ new String( "Duck" ), new String( "Duck" ), new String( "Goose!" ) };
		Worker[] workers = new Worker[]{ new Worker( "Working" ), new Worker( "Working" ), new Worker( "Sleeping" ) };
 
		assert ints[0] == ints[1] : "10 is 10";
		assert ints[1] != ints[2] : "10 is not 20";
		// Primative data types can't use ints[i].equals( ints[j] ) because they don't have methods.
 
		// Strings are a little bit more tricky. Go here for more inforamtion. http://www.janeg.ca/scjp/lang/strLiteral.html
		assert strings[0] == strings[0]: "An equality check, ==, on objects compares the references, not the values.";
		assert strings[0] != strings[1]: "strings[0] and strings[1] do not have the same reference point. In otherwords, that don't have the same Class and hashCodes.";
		assert strings[0].equals( strings[1] ): "String equals methods is predefined to compare the value of the string objects.";
		assert !strings[0].equals( strings[2] ): "the string duck should not equal the string goose!";
 
		// You have to override the equals methods for user-defined objects.
		assert workers[0] != workers[1]: "workers[0] and workers[1] have two different hash values.";
		assert workers[0].equals( workers[1] ): "However workers[0] and workers[1] are equivalent to eachother, according to the equals method.";
		assert !workers[1].equals( workers[2] ): "But this is not the case for workers[1] and workers[2].";
 
		message = ( areAssertsEnabled() ) ? message : "Asserts are disabled! Please enable with the switch -ea, ex. java -ea ";
		System.out.println( message );
	}
}
class Worker{
	public String status;
	public Worker( String status ){
		this.status = ( status != null ) ? status : "Unknown";
	}
	public boolean equals( Object obj ){
		boolean areSame = false;
		Worker x;
		if( obj != null  ){
			if( obj == this ){
				areSame = true;
			}
			if( this.getClass() == obj.getClass() ){
				x = (Worker) obj;
				if( x != null && x.status.equals( this.status ) ){
					areSame = true;
				}
			}
		}
		return areSame;
	}
}

Larry Battle

Larry Battle

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.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Reimplementation of Number.prototype.toFixed


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

Number.prototype.toFixed was giving me too many problems, so I just rewrote it.
There’s the source.

/**
@author Larry Battle <a alt="contact me" href="bateru.com/news/contact">Contact Me</a>
@date	Mar 30, 2012
@purpose Provide the fix for Number.prototype.toFixed() function.
@info source at http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed
 */
Number.prototype.toFixed_fix = function (precision) {
	var num = this.toString(), zeros = '00000000000000000000', newNum, decLength, factor;
	if (0 > precision || precision > 20) {
		throw new RangeError("toFixed() digits argument must be between 0 and 20");
	}
	if (Math.abs(num) === Infinity || Math.abs(num) >= 1e21) {
		return num;
	}
	precision = parseInt(precision, 10) || 0;
	newNum = num = isNaN(parseInt(num, 10)) ? '0' : num;
	if (/\./.test(num)) {
		decLength = num.split('.')[1].length;
		if (decLength < precision) {
			newNum += zeros.substring(0, precision - decLength);
		} else {
			factor = Math.pow(10, precision);
			newNum = Math.round(num * factor) / factor;
		}
	} else {
		if (precision) {
			newNum += '.' + zeros.substring(0, precision);
		}
	}
	return newNum;
};

Test cases here

Want to learn more about Javascript?
Checkout this ‘Professional JavaScript for Web Developers’.

Larry Battle

Larry Battle

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.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube