-5

i try to find prime number by use that code:

        public static void TongSoNguyenTo()
        {
        var tongchiahet = 0;
        for (var so=2;so<20;so++)
        {
            for (var chia=1;chia<=so;chia++)
            {
                if (so % chia == 0)
                {
                    tongchiahet++;
                    if (tongchiahet == 2)
                    {
                        Console.WriteLine(so);
                    }
                }
            }
        }
        Console.ReadKey();
    }

but instead of list of number, it can write one number. what can i do next

Vô Tâm
  • 17
  • 5

1 Answers1

0

You have issues in your second loop, I don't get the why you used the variable tongchiahet, The main thing that you have to use is a break statement, which helps you to stop iteration of second loop if so % chia == 0 in between iterations: Here is a working Example for you, And try the following code:

int limit = 20;
for (var so = 1; so < limit; so++)
{
    bool isPrime = false;
    for (var chia = 2; chia < so; chia++)
    {
        if (so % chia == 0)
        {
            isPrime = true;
            break;
        }
    }
    if (!isPrime)
        Console.WriteLine(so);

}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88