-2

Can you advise me on how to display the Prime number or not? I also want to input 0 or 1 and get some answer. I should do it only with for/while loop, and I am stuck here...

Console.WriteLine("Enter a number: ");
int x = Convert.ToInt32(Console.ReadLine());

for (int k = 2; k <= x; k++)
{
    if (x % k == 0)
    {
        
        Console.WriteLine($"number {x} Not prime");
    }
    else
    {
        Console.WriteLine($"number {x} is prime");
    }
}
Ivan
  • 1
  • 1
  • There are a number of optimization opportunities, but the main logic thing you need to change is to break out of the loop when the number is found to not be prime and then only print the `is prime` when that didn't happen, so you need a flag of some sort. – 500 - Internal Server Error Aug 05 '23 at 19:30
  • Now it works, but when i try to input 0 or 1, the program crashes for (int k = 2; k <= x; k++) { if (x % k != 0) { Console.WriteLine($"number {x} is prime"); break; } else { Console.WriteLine($"number {x} Not prime"); break; } } – Ivan Aug 05 '23 at 19:50
  • That doesn't seem to make sense. The `k <= x` expression should never become true for those two values of `x`, so the loop should not be entered. – 500 - Internal Server Error Aug 05 '23 at 20:00

0 Answers0