// you’re reading...
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 5.00 out of 5)
Loading...

Project Euler Tools

Prime Factor Calculator

Fast Prime Factor Calculator

Prime Factor Calculator

This short program is written in JavaScript and uses the techniques discussed in Project Euler Problem 3 for determining the prime factors of a composite number. Clearly, prime numbers have only themselves as a prime factor (1 is never considered prime) and are identified as such.

The input is limited to an integer less than 2^53 == 9 007 199 254 740 992


Number to factor
Prime factors

Here’s the source code, complete with the HTML, that you can paste into a file and see how it works in your favorite browser:

<script language="JavaScript">
//Prime Factor Calculator
function handle_enter() {
  document.form.factors.value=factorsx(document.form.nx.value); 
}
function factorsx(n) {
    if (n < 2) { return "Neither Prime nor Composite" }
    if (n > 9007199254740991) { return "Number must be less than\n  2^53 == 9 007 199 254 740 992" }
    var response = n + ' = ';
    message = "This Number is Prime"
    var p = 2;
    var np = n
    while (p*p <= np) {      
        if (np % p == 0) { 
            response += p + ' x ';     
            np /= p;
        } else  p+= p>2? 2 : 1; 
    }
    return np==n? message : response + np;
}
</script>
<center>
<table bgcolor="#dddddd">
<tr><td>

<form name="form" method="post" onSubmit="if (this.submitted){return true;} else 
  { handle_enter(); return false; }">

<table>
<tr>
<td>Number to factor</td><td><input type="text" size=14 name="nx">
<input type="button" value="Click here for factors"
   onClick="form.factors.value=factorsx(form.nx.value)"></tr>
<tr>
<td style="vertical-align: top">Prime factors</td>
<td><textarea name="factors" rows=2 cols=40></textarea></td><td> </td></tr>
</table>
</form>

</td></tr></table>
</center>

prime factor calculator v 1.1

Discussion

Trackbacks/Pingbacks

  1. […] factor, which is nice, because it is, in fact, itself the largest prime factor. Here’s a Javascript prime factor calculator to find all the prime factors of a […]

Post a comment