I want a function called findFirst that takes parameters n and q and returns the smallest prime number dividing n that is greater than or equal to q. So first I wrote a function that would say if a number is prime or not.
var isPrime = function(n){
if(n === 1){
return false;
}
else if (n === 2 || n === 3){
return true;
}
else {
for(i=2; i < n; i++){
if(i * i >= n){
for(j=2; j<=i; j++){
if(n % j === 0){
return false;
}
}
return true;
}
}
}
};
There could be other ways to make this more efficient, but I am pretty sure this function is not the problem.
So with this function I made my first attempt to write findFirst:
var findFirst = function(n,q){
var p = q;
while(n % p !== 0 || isPrime(p) === false){
p++;
}
return p;
};
This function works, but with large numbers it crashes, for example it crashes on input (6310545154, 3). By the way the prime power decomposition of 6310545154 is 2 * 3155272577
So I wrote another function that would first just list the prime factors of a number:
var getFactors = function(n){
var factors = [];
var k = n;
var p = 2;
while(isPrime(k) === false && k !== 1){
while(k % p !== 0 || isPrime(p) === false){
p = p+1;
}
while(k % p === 0){
k = k/p;
}
factors.push(p);
}
if(isPrime(k) === true){
factors.push(k);
return factors;
}
if(k === 1){
return factors;
}
};
And now my second attempt at findFirst is:
var findFirst = function(n,q){
var array = getFactors(n);
var p = 0;
for(i = 0; i < array.length; i++){
if(array[i] >= q && p === 0){
p = array[i];
}
}
return p;
};
This one works great. It doesn’t crash on that large number above and computes the result instantly. Can anyone see why this would happen? It seems like the ‘while’ loop in my original attempt is pretty similar to one of the ‘while’ loops in the getFactors function. And the second attempt looks a lot more complicated.
The second program returns very quickly because your number only has one large prime factor; once it’s found (all) the small prime factor(s) it quickly exits its loop. The first program has to count all the way from 3 up to 3155272577 before it discovers that it’s a factor. After 2147483647 it has to switch from integer to floating-point arithmetic, which makes it even slower.
Note that
is an unusual way of creating a function; normally you would write