0

Help sieving an array for prime numbers?

I am learning Javascript at the moment and following the Project Euler challenges to help me learn it properly. Currently I'm trying write a code for the third challenge (find the largest prime factor of 600851475143). I have managed to create an array of all the factors of the given integer (works for this or any number) by calling a function. What method should I use to loop the factors array and sieve the numbers for primes? I've tried filter(), and map(), but can't seem to get them to return anything useful.

29th Nov 2018, 9:36 PM
George S
1 Resposta
+ 1
If you have a way to generate factors already, I think the easiest way is to check the factors of each factor. Sort all the factors of your large number biggest to smallest, and the first factor that has no factors (other than itself and 1) is the largest prime factor. .filter can definitely do it but even easier might be .find()! Something like this: function get_factors(n){ // you did that already } let factors = get_factors(600851475143); let sorted = factors.sort((a,b) => b-a); let largest_prime_factor = sorted.find(x => get_factors(x) <= 2);
29th Nov 2018, 11:31 PM
Schindlabua
Schindlabua - avatar