Hone logo
Hone
Problems

Prime Number Checker in JavaScript

Determining whether a number is prime is a fundamental problem in number theory and computer science. This challenge asks you to write a JavaScript function that efficiently checks if a given integer is a prime number. Prime numbers are essential in cryptography and have various applications in algorithm design.

Problem Description

You need to create a JavaScript function called isPrime that takes a single integer as input and returns true if the number is prime, and false otherwise. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Key Requirements:

  • The function must correctly identify prime numbers.
  • The function should handle edge cases appropriately (e.g., numbers less than or equal to 1).
  • Efficiency is important; avoid unnecessary computations.

Expected Behavior:

The function should return a boolean value (true or false).

Edge Cases to Consider:

  • Numbers less than or equal to 1 are not prime.
  • 2 is the only even prime number.
  • Large numbers may require optimization to avoid timeouts.

Examples

Example 1:

Input: 7
Output: true
Explanation: 7 is only divisible by 1 and 7.

Example 2:

Input: 10
Output: false
Explanation: 10 is divisible by 1, 2, 5, and 10.

Example 3:

Input: 1
Output: false
Explanation: 1 is not a prime number by definition.

Example 4:

Input: 2
Output: true
Explanation: 2 is the smallest prime number.

Constraints

  • The input n will be an integer.
  • 1 <= n <= 1000000 (One million)
  • The function should execute in a reasonable time (e.g., less than 1 second for the given input range). While not strictly enforced, aim for an efficient solution.

Notes

  • A common optimization is to only check divisibility up to the square root of the input number. If a number has a divisor greater than its square root, it must also have a divisor smaller than its square root.
  • Consider the special case of 2 separately for efficiency.
  • Think about how to handle negative numbers (the problem statement specifies integers, but it's good to consider). For this challenge, you can assume the input will be a non-negative integer.
Loading editor...
javascript