Coding Challenge Practice - Question 68

Published: (December 1, 2025 at 05:14 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem Statement

Implement a function isPrime(num) that returns true if the given number is a prime number and false otherwise.

Approach

Handle edge cases

  • Numbers less than or equal to 1 are not prime.
  • 2 is the only even prime number.
  • Any other even number greater than 2 cannot be prime.

Check odd divisors

For odd numbers greater than 2, test divisibility by odd integers starting from 3 up to the square root of the number.

  • If any divisor divides the number evenly, the number is not prime.
  • If none do, the number is prime.

Code

function isPrime(num) {
  // Edge cases
  if (num <= 1) return false;   // 0, 1, and negatives are not prime
  if (num === 2) return true;   // 2 is the only even prime
  if (num % 2 === 0) return false; // other even numbers are not prime

  // Check odd divisors up to sqrt(num)
  const limit = Math.sqrt(num);
  for (let i = 3; i <= limit; i++) {
    if (num % i === 0) return false;
  }
  return true;
}
Back to Blog

Related posts

Read more »

Coding Challenge Practice - Question 69

Problem Description Create a function that returns the n-th term of the “look‑and‑say” sequence as a string. The sequence starts with '1' for n = 1. Each sub...

Challenge no. 1 - User Avatar

Communities DEV Community !DEV Community Logohttps://media2.dev.to/dynamic/image/width=65,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-...