Medium ยท trial division
Prime Check
Is n divisible by anything besides 1 and itself? Only test divisors up to โn โ and stop the moment you find one. The โn bound is what makes it fast.
Problem
Input: one integer n (0 โค n โค 10โถ).
Output: Yes if n is prime, No otherwise (0 and 1 are not prime).
Sample:
| Input | Output |
|---|---|
7 | Yes |
25 | No |
Your solution
Custom input for "Run my input"
Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.
Stuck? Hints
Hint 1 โ why โn is enough
If n = a ร b with a โค b, then a โค โn. A factor bigger than โn always pairs with one smaller โ so testing up to i * i <= n covers everything.
Hint 2 โ the edge cases
n < 2 โ not prime (handle before the loop). Perfect squares like 25 need <= in i * i <= n, not < โ otherwise 5ร5 slips through. And break on the first divisor found.
Solution (try first!)
int n = int.Parse(Console.ReadLine());
if (n < 2) { Console.WriteLine("No"); return; }
bool prime = true;
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0) { prime = false; break; }
}
Console.WriteLine(prime ? "Yes" : "No");
return at top-level exits early โ no else-branch needed for the n < 2 case. Scaling this to "count all primes below N" is a sieve โ a good next challenge. Next: Fibonacci.