Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ Prime Number Algorithm

Name: Anonymous 2008-12-08 21:47

/prog/ I'm very deeply stressed at the moment. I have an assignment due tomorrow morning, a prime number algorithm. I know I screwed it up badly, and I'm not even sure if I am on the right track. If there are any capable c++ programmers on /prog/ right now, think you could lend a gal a hand?

Here is a copy of my current code:

#include <iostream>
using namespace std;

int main()
{
    int s;
    int p;
    long PrimeStatus[100001];
    PrimeStatus[s] = 1;
    long MAX_PRIME_CHECK = 100000;

    for(int s = 1; s < MAX_PRIME_CHECK; s++)
    {
        if(p > 2)
        {
            PrimeStatus[p] = 1;
            return 0;
        }
       
        else if(p <= 2)
        {
            if(PrimeStatus[p] = 1)
            {
                PrimeStatus[p] = 1;
                return 0;
            }
           
            else if(PrimeStatus[p] = 0)
            {
                if(p%(p-1) == 0)
                {
                    PrimeStatus[p] = 0;
                    return 0;
                }
               
                else while(p%(p-1) != 0)
                {
                    p = p-1;
                }
               
                if(p%(p-1) == 0)
                {
                    PrimeStatus[p] = 0;
                    return 0;
                }
            }
        }
    for(p = 1; s = 0; p++)
    {
        cout << PrimeStatus[p] << endl;
    }
    return 0;
    }
}

Name: Anonymous 2008-12-11 13:05

Let a prime number be a number that has no factors aside from one and itself.

A number only has factors that complement eachother, meaning they come in pairs. Thus, you only need to look for factors prior to n / 2.

I'm not exactly sure what you mean by a "prime number algorithm," if you mean it determines a number that's prime or if it generates prime numbers, either of these can be achieved through the use of a prime number function.

bool isPrime(int n) {
    bool is = true;
    for (int c = 2; c <= (n / 2); c++) { // lul sepples
        if ((n % c) == 0) { // c is a factor
            is = false;
            break;
        }
    }
    return is;
}

If you need to generate primes, simply iterate through your range of numbers until a sufficient number of primes is generated. You could alternatively change this to return a vector and push the factors in if you wanted to for some other assignment.

Happy Sepples.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List