Searching for Primes under One Million
JavaFX Script is very fast because it is built on top of the Java platform. The following example searches for all primes below one million and returns the number found. On most modern computers, the search will execute in under half a second. For comparison, you can try the Javascript version on the right.
This code is adapted from the countprimes example at IT Writing.
JavaFX Script |
JavaScript
|
||||||||||
JavaFX Script + Java w/ Threads |
|||||||||||
Figure 1: Counting Primes in JavaFX Script and JavaScript
Understanding the Code
The basic code is simple and naive, but it highlights the speed comparison to JavaScript. Both versions have been implemented the exact same way. For every odd number under the maximum, the code tries every possible factor less than the square root of the target number. For each factor it performs remainder division, looking for factors that do not result in a remainder of zero. When it finds such a number, it increments the numprimes variable and continues.
function findPrimes(n:Integer):Integer {
var j:Integer;
var limit:Number;
var numprimes:Integer = 1; //2 is prime
var i:Integer = 3;
while(i<=n) {
var isPrime = true;
limit = Math.ceil(Math.sqrt(i)) +1;
j = 3;
while(j<limit) {
if(i mod j == 0) {
isPrime = false;
break;
}
j+=2;
}
i+=2;
if(not isPrime) {
continue;
}
if(isPrime) {
numprimes++;
}
}
return numprimes;
}
Figure 2: Finding Factors With No Zero Remainder
Josh Marinacci