Thread: Finding Prime Numbers

  1. #1
    Registered User alireza beygi's Avatar
    Join Date
    Dec 2011
    Location
    USA
    Posts
    17

    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;
    }

  2. #2
    Registered User
    Join Date
    Jun 2009
    Posts
    120
    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++;
            }
        }
    }

  3. #3
    Registered User alireza beygi's Avatar
    Join Date
    Dec 2011
    Location
    USA
    Posts
    17
    THANKS a lot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. non prime numbers or composite numbers program.help plz!
    By danishzaidi in forum C Programming
    Replies: 10
    Last Post: 11-15-2011, 11:10 AM
  2. Replies: 2
    Last Post: 12-24-2009, 02:41 AM
  3. Finding Prime Numbers
    By dan724 in forum C Programming
    Replies: 11
    Last Post: 12-14-2008, 12:12 PM
  4. Finding and Printing prime numbers using arrays
    By Sektor in forum C++ Programming
    Replies: 5
    Last Post: 12-11-2003, 08:29 PM
  5. Finding prime factors
    By ripper079 in forum C Programming
    Replies: 3
    Last Post: 05-17-2002, 09:23 PM