nodeschool / discussions

:school::speech_balloon: need help with nodeschool? or just wanna ask a question? open an issue on this repo!
489 stars 107 forks source link

how to find a prime number in a array in java script #2941

Open wintran67 opened 11 months ago

wintran67 commented 11 months ago

Notes

Please delete this section after reading it

If you have a problem with an error message:

Error output

 // copy your error output here

My Code

 // copy your code here
mahdi-eth commented 11 months ago

To find prime numbers within an array in JavaScript, you can create a function that checks each number in the array for primality. Here's an example: function isPrime(num) { if (num <= 1) return false; // Numbers less than or equal to 1 are not prime

// Check for factors from 2 to the square root of the number for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) return false; // If the number is divisible by any other number, it's not prime } return true; // If no factors other than 1 and itself, it's prime }

// Filter out the numbers which are not prime function findPrimesInArray(arr) { return arr.filter((num) => isPrime(num)); }

// Example usage: const numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]; const primeNumbers = findPrimesInArray(numbers); console.log("Prime numbers in the array:", primeNumbers);