Tutorialspoint
Problem
Solution
Submissions

Check if Number is Prime

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to determine if a given positive integer is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, etc.

Example 1
  • Input: num = 17
  • Output: true
  • Explanation:
    • Check if 17 is greater than 1 (it is).
    • Check if 17 is divisible by any number from 2 to √17 (approximately 4.12).
    • Test divisibility: 17 % 2 = 1, 17 % 3 = 2, 17 % 4 = 1.
    • None of these divisions result in 0, so 17 has no divisors other than 1 and itself.
    • Therefore, 17 is a prime number.
Example 2
  • Input: num = 15
  • Output: false
  • Explanation:
    • Check if 15 is greater than 1 (it is).
    • Check if 15 is divisible by any number from 2 to √15 (approximately 3.87).
    • Test divisibility: 15 % 2 = 1, 15 % 3 = 0.
    • Since 15 % 3 = 0, we found that 15 is divisible by 3.
    • Therefore, 15 is not a prime number.
Constraints
  • 1 ≤ num ≤ 10^6
  • The input will always be a positive integer
  • Numbers less than or equal to 1 should return false
  • Time Complexity: O(√n) where n is the input number
  • Space Complexity: O(1)
NumberControl StructuresKPMGSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Handle edge cases first: numbers less than or equal to 1 are not prime
  • Check if the number is 2, which is the only even prime number
  • If the number is even and greater than 2, it's not prime
  • For odd numbers, check divisibility from 3 up to the square root of the number
  • Only check odd divisors to optimize the algorithm
  • If any divisor is found, the number is not prime
  • If no divisors are found, the number is prime

Steps to solve by this approach:

 Step 1: Handle edge cases by checking if the number is less than or equal to 1, return false
 Step 2: Check if the number is exactly 2, which is the only even prime number, return true
 Step 3: Check if the number is even and greater than 2, return false since even numbers > 2 are not prime
 Step 4: Calculate the square root of the number to determine the upper limit for checking divisors
 Step 5: Use a loop starting from 3 and increment by 2 to check only odd potential divisors
 Step 6: For each odd number in the range, check if it divides the input number evenly
 Step 7: If any divisor is found, return false; if no divisors are found after the loop, return true

Submitted Code :