# Finding Prime Numbers

• 01-13-2012
alireza beygi
Finding Prime Numbers
Hello.
The code that I wrote, should take n as an integer and find all prime numbers before n.
with this definition:
A numbers is prime that not be dividable to all last prime numbers.
what's the problem with my code?
thanks.
Code:

```#include <stdio.h> #include <conio.h> int main () {     int n;     int count = 1;     int p [1000];     printf ("Enter a positive integer Num:\n");     scanf ("%d", &n);     if (n <= 1)     printf ("Fail!");     else if (n == 2)     printf ("You entered %d and is prime (only)", n);     else if (n > 2){     p [0] = 2;     for (int i = 3; i <= n; i++){     for (int j = 0; j < count; j++ )     if (i % p [j] == 0)     break;     else     p [j+1] = i;     count ++; } }     for (int k = 0; k < count; k++)     printf ("\n%d\n", p [k]);     getch ();     return 0; }```
• 01-13-2012
DRK
This is a perfect example how bad code style can misguide program functionality. Use indents for every for, while, if, else etc. even if only one instruction will be executed, this way you will get clear picture of your code.

There's also bug in your algorithm, this will fix it:

Code:

```for (int i = 3; i <= n; i++) {     for (int j = 0; j < count; j++)     {         if (i % p[j] == 0)         {             break;         }         else if (j + 1 == count)         {             p[j + 1] = i;             count++;         }     } }```
• 01-13-2012
alireza beygi
THANKS a lot!