Header Ads Widget

Responsive Advertisement

04: Find prime number in array | javascript Dsa

 Q:) Find a prime number from an array?


prime number find in array


var arr = [2, 3,4,6, 5, 7, 9, 81, 343, 77, 34234]
var isPrime = []
arr.forEach((num) => {
    if (num <= 1) {
        return false
    };
    for (let i = 2; i < num; i++) {
        if (num % i == 0) {
            return false
        };
    };
    isPrime.push(num)

});
console.log(isPrime,"isPrime")

Today's Dsa question is the prime number find in the array. so above code, we do our best to find out prime and we explain what we do and achieve the result step by step in the below section:

1: Array Initialization:

var arr = [2, 3, 4, 6, 5, 7, 9, 81, 343, 77, 34234]:
This line initializes an array named arr with some numbers.

2:Empty Array for Prime number:

var isPrime = []:
This line initializes an empty array isPrime. This array will store prime numbers found in the arr.

3:Loop through Array with forEach:

arr.forEach((num) => { ... });
This line starts a loop that iterates through each element of the array arr. The loop is implemented using the forEach method, which takes a callback function as an argument.

4: Check for Numbers Less than or Equal to 1:

if (num <= 1) { return false; }:
Inside the loop, each number num is checked. If the number is less than or equal to 1, it's not a prime number, so the function returns false.

5: Check for Prime Numbers:

for (let i = 2; i < num; i++) { ... }:
 If the number is greater than 1, the function enters a loop to check for prime numbers. It iterates from 2 to one less than the number itself.

if (num % i == 0) { return false; }:
Within the loop, each number is divided by i. If the remainder is 0, it means the number is divisible by i, which implies it's not a prime number. In such cases, the function returns false.

6: Push Prime Numbers to Array:

isPrime.push(num):
If a number passes both checks and is not divisible by any number other than 1 and itself, it's a prime number. Such prime numbers are pushed into the isPrime array.

7: Logging Prime Numbers:

console.log(isPrime, "isPrime"):
After the loop completes, the isPrime array contains all the prime numbers found in arr. This array is logged to the console.

Summary,

The code iterates through each number in the arr, checks if it's less than or equal to 1, and then checks if it's a prime number. Prime numbers are collected in the isPrime array, which is then logged into the console. This process effectively filters out prime numbers from the given array.


Feel free to reach out and drop your query.
if you have a better idea to solve this question then let us know in the comment section

Post a Comment

0 Comments