4umi.com/web/javascript/factor

Factor-that-number

Math Javascript

The magic of mathematics brings you a Javascript that returns a number's factors or dividers, and other neat stuff.

The action

Enter a number for your example, and press ‘Start’ to run the test.

Input
Result
...

The script

Pretty straight-forward.

// original: Jeff LeMieux, © 2001
// http://webdeveloper.earthweb.com/repository/javascripts/2002/01/72541/prfact.htm
function factor( a ) {
 var b = a, c, i = 1, j = Math.floor( a / 2 ), output = 'Factors of ' + a + ': ', pf = '';
 for( ; i<=a; i++ ) {
  c = a / i;
  if( c===Math.floor( c ) ) {
   output += i + ', ';
  }
 }
 output = output.substr( 0, output.length - 2 ) + '\r\nPrime factors:  ';
 for( i = 2; i<=j; i++ ) {
  c = b / i;
  if( c===Math.floor( c ) ) {
   pf = pf + i + ' x ';
   b = c;i--;
  }
 }
 if( !pf ) { pf = b + ' is a prime number!    '; } 
 return output + pf.substr( 0, pf.length - 3 );
}

gid( 'r' ).firstChild.nodeValue = factor( +document.forms.f.elements.n.value );