Medium csharp

Prime number check

Problem

Check if 29 is prime and print Prime or Not Prime.

Hints
  • Divide n by all integers from 2 up to sqrt(n).

Your practice code

Ready — edit the code above and click Run.

Solution

using System;

class Program
{
    static void Main()
    {
        int n = 29;
        bool isPrime = n > 1;
        for (int i = 2; i * i <= n && isPrime; i++)
            if (n % i == 0) isPrime = false;
        Console.WriteLine(isPrime ? "Prime" : "Not Prime");
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Loop only to sqrt(n) (here i*i <= n)—efficient prime test for interviews.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details