Code Logo

Prime Number Check

Published at25 Jul 2026
Number Theory Easy 0 views
Like0

Check if a given 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.

Check divisibility from 2 up to the square root of n. If n is divisible by any number in that range, it's not prime. Numbers less than 2 are not prime.

Example Input & Output

Example 1
Input
7
Output
true
Explanation

7 is prime

Example 2
Input
1
Output
false
Explanation

1 is not prime

Example 3
Input
17
Output
true
Explanation

17 is prime

Example 4
Input
4
Output
false
Explanation

4 = 2x2, not prime

Example 5
Input
2
Output
true
Explanation

2 is prime

Algorithm Flow

Recommendation Algorithm Flow for Prime Number Check
Recommendation Algorithm Flow for Prime Number Check

Solution Approach

function solution(n) {
  if (n < 2) return false;
  for (var i = 2; i * i <= n; i++) { if (n % i === 0) return false; }
  return true;
}

Best Answers

java
class Solution {
    public boolean solution(int n) {
        if(n<2)return false;
        for(int i=2;i*i<=n;i++){if(n%i==0)return false;}
        return true;
    }
}