Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
C#
int i, j, count =0;

for (i=2; i<=100; i++)
{
    for (j=1; j<=100; j++)

    {
        if (i % j == 0)
        {
            count++;

        }
    }

    if (count == 2)
    {
        Console.WriteLine("This is a prime number" + i);
        count = 0;
    }

}

Console.ReadLine();
Posted
v4

You only reset count if the current count is two, but you should always reset it.

And you only need to check up to the square root of the number you are checking.

And look into http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes[^]
 
Share this answer
 
C#
int i, j, count =0;

 for (i=2; i<=100; i++)
 {
     for (j=1; j<=i; j++)

     {
         if (i % j == 0)
         {
             count++;
         }
     }

     if (count == 2)
     {
         Console.WriteLine("This is a prime number" + i);
     }

     // This should be after the if, as we need to make it 0 every time.
     count = 0;
 }

 Console.ReadLine();

1. You should have the second loop condition like j<=i and not j<=100.
Actually you need to check whether the number is divisible with 1, 2.... upto the number you are comparing with (that is i).

2. Count should be 0 every time, but you are making it 0 when it is prime, inside the if condition.
So, 2, 3 are prime, and when 4 comes it does not make count 0, hence stops.


Thanks...
 
Share this answer
 
v3
Comments
Allwin456 2-Mar-13 23:52pm    
@Tadit Dash .. But still then the out is --> This is a prime number 2
This is a prime number 3

And not showing the output for any other numbar. What might be the reason ??
Allwin456 2-Mar-13 23:58pm    
Its solved now. Thanks
Hey I am sorry...
I could not check it at once...
I have updated the answer, check it out.

You have to make count to 0 every time.
Allwin456 3-Mar-13 20:47pm    
ok. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900