Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Example Programs
  5. Find Prime Numbers

Find Prime Numbers

Example 32

Write a for loop to find prime numbers between 1 to 50

function isPrime(num) {
  if (num <= 1) {
    return false;
  }
  for (var i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  return true;
}

for (var i = 1; i <= 50; i++) {
  if (isPrime(i)) {
    console.log(i);
  }
}

Output

Loading

Views: 67

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments