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:

InputOutput
7Yes
25No

Your solution

Program.cs โ€” 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.