Certainly! Here's a Python function and a JavaScript function to select the prime numbers from a given list or array:
Python:
python
def select_primes(numbers):
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
return [num for num in numbers if is_prime(num)]
JavaScript:
javascript
function selectPrimes(numbers) {
function isPrime(num) {
if (num < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
return numbers.filter(isPrime);
}
Both functions work as follows:
They define an inner function (is_prime in Python and isPrime in JavaScript) that takes a single number as input and checks whether it is prime or not.
The inner function first checks if the number is less than 2. If it is, it returns False (in Python) or false (in JavaScript) since numbers less than 2 are not considered prime.
If the number is greater than or equal to 2, the inner function enters a loop that starts from 2 and goes up to the square root of the number (inclusive). It checks if the number is divisible by any value in this range. If it finds a divisor, it returns False (in Python) or false (in JavaScript) since the number is not prime.
If the loop completes without finding any divisors, the inner function returns True (in Python) or true (in JavaScript), indicating that the number is prime.
The main function (select_primes in Python and selectPrimes in JavaScript) takes a list or array of numbers as input.
In Python, the main function uses a list comprehension to iterate over each number in the input list and includes only the numbers for which the is_prime function returns True.
In JavaScript, the main function uses the filter method to iterate over each number in the input array and includes only the numbers for which the isPrime function returns true.
Finally, the main function returns the list or array of prime numbers.
You can call these functions with a list or array of numbers, and they will return a new list or array containing only the prime numbers from the input.