
Problem
Solution
Submissions
Check Prime Number
Certification: Basic Level
Accuracy: 31.71%
Submissions: 41
Points: 5
Write a C# program to determine whether a given number N is a prime number. A prime number is a natural number greater than 1 that has exactly two distinct divisors: 1 and itself.
Your implementation should support the following functionality:
- IsPrime(N): Given an integer N, return true if it is prime, otherwise return false.
Example 1
- Input: N = 7
- Output: True
- Explanation:
- Step 1: Check if N is less than 2. If so, return false (not a prime).
- Step 2: Check if N is divisible by any number from 2 up to sqrt(N).
- Step 3: For N = 7, we check divisibility by 2 (7 % 2 = 1).
- Step 4: We check divisibility by 3 (7 % 3 = 1).
- Step 5: No need to check more as sqrt(7) is approximately 2.65.
- Step 6: Return true as 7 is only divisible by 1 and itself.
Example 2
- Input: N = 10
- Output: False
- Explanation:
- Step 1: Check if N is less than 2. 10 is greater than 2, so continue.
- Step 2: Check if N is divisible by any number from 2 up to sqrt(N).
- Step 3: For N = 10, we check divisibility by 2 (10 % 2 = 0).
- Step 4: Since 10 is divisible by 2, return false.
- Step 5: 10 is divisible by 1, 2, 5, and 10, so it is not a prime number.
Constraints
- 1 ≤ N ≤ 10^9
- Time Complexity: O(√N) using an optimized approach (checking divisibility up to sqrt(N)).
- Space Complexity: O(1)
Editorial
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. |
Solution Hints
- Basic Check: If N ≤ 1, it's not prime. If 𝑁=2 or N=3, it's prime.
- Even Number Check: If N is even and greater than 2, it's not prime.
- Trial Division: Check divisibility from 3 to N, skipping even numbers.
- Optimization: Only check divisibility by numbers of the form 6k ± 1 (except 2 and 3).