Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wintran67 opened this issue Dec 9, 2023 · 1 comment
Open

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

wintran67 opened this issue Dec 9, 2023 · 1 comment

Comments

@wintran67
Copy link

Notes

Please delete this section after reading it

If you have a problem with an error message:

  • node version: <run "node -v" in you terminal and replace this>
  • npm version: <run "npm -v" in you terminal and replace this>
  • os: windows 7/windows 10/mac/linux

Error output

 // copy your error output here

My Code

 // copy your code here
@mahdi-eth
Copy link

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants