Easy CHALLENGE
Prime Number
Given an integer n, determine if it is a prime number. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.Logical Approach_
1
Handle edge cases: numbers < 2 are not prime.2
Loop from 2 up to the square root of n.3
Check if n is divisible by any number in the loop.4
If divisible, it is not prime. If the loop completes, it is prime.Variations Hub_
Print all prime numbers up to N (Sieve of Eratosthenes).
Find the Kth prime number.
Find prime factors of a given number.
Implementation Protocol (JS)
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}Line-by-Line Breakdown_
Point 1
Line 2-3: Handle 0, 1, 2, and 3 specifically as they are basic cases.
Point 2
Line 5: Optimization: All primes except 2 and 3 are of the form 6k ± 1.
Point 3
Line 7: Loop up to sqrt(n) for efficiency (O(sqrt(n))).
Point 4
Line 8: Check divisibility for both 6k-1 and 6k+1 cases.