Day 25: Running Time and Complexity

  • + 0 comments
    C# Csharp
    
        static void Main(String[] args) 
        {
            int row = int.TryParse(Console.ReadLine(), out int inputRow) ? inputRow : 0;
    
            while (row > 0)
            {
                int.TryParse(Console.ReadLine(), out int rec);
    
                if (rec > 1)
                {
                    bool isPrime = true;
    
                    // Optimized primality test: check divisors only up to the square root
                    for (int i = 2; i * i <= rec; i++)
                    {
                        if (rec % i == 0)
                        {
                            isPrime = false;
                            break;
                        }
                    }
    
                    string result = isPrime ? "Prime" : "Not prime";
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine("Not prime");
                }
    
                row--;
            }
        }