tags:

views:

1422

answers:

7

Where can I find a prime number generator in C?

+8  A: 

Especially for large primes (to used for encryption, etc), I used: the GNU MP Bignum Library.

EDIT: I assumed to question to be about find a random number generator:

Check the methods for Integer Random Numbers to generate random numbers and Number Theoretic Functions to validate their primes:

mpz_t random_prime(mpz_t max) {
    gmp_randstate_t state;
    mpz_t result;

    gmp_randinit_defult(state);
    mpz_init(result);

    while (mpz_probab_prim_p(result, 4) == 0) {
        mpz_urandomm(result, state, max);
    }

    return result;
}

[Haven't run the code myself]

notnoop
@notnoop, I can't immediately see the connection between random numbers and prime numbers ??
paxdiablo
@paxdiablo, I assumed the question is about random prime number generators.
notnoop
Huh? Where did my comment go? I am positive *I* did not delete it!
Bart Kiers
+4  A: 

here is one. http://snippets.dzone.com/posts/show/4247

Scott Frye
+33  A: 

The most "classic" implementation of a prime number generator is the Sieve of Eratosthenes. There are numerous improvements on this algorithm, but it should give you a good start.

Here's a bit of source code (below) from a public domain implementation. [Original link]:

/* This code is in public domain. Use for whatever purpose at your own risk. */
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#define MAXN  100000000  /* maximum value of N */
#define P1    1562501    /* = ceil(MAXN/64) */
#define P2    50000000   /* = ceil(MAXN/2) */
#define P3    5000       /* = ceil(ceil(sqrt(MAXN))/2) */

uint32_t sieve[P1];

#define GET(b) ((sieve[(b)>>5]>>((b)&31))&1)

void make()
{
    uint32_t i, j, k;
    memset(sieve, 0, sizeof(sieve));
    for (k = 1; k <= P3; k++)
        if (GET(k)==0) for(j=2*k+1,i=2*k*(k+1);i<P2;i+=j) sieve[i>>5]|=1<<(i&31);
}

int isprime(int p) { return p==2 || (p>2 && (p&1)==1 && (GET((p-1)>>1)==0)); }

int main()
{
    int i, n;
    make();
    for (n = 0, i = 0; i <= MAXN; i++)
        if (isprime(i)) n++;
    printf("The number of primes below 10^8 is %d.\n", n);
    return 0;
}
Robert Cartaino
+1 for actually answering the question without the snarky "why not try google" comments.
Graeme Perrow
+1 for simply answering the question.
Frerich Raabe
Actually, I'm tempted to -1 for the same reason. You should at least hand him an implementation in some bizzare language like Mumps, so he'll have to do *some* thinking.
T.E.D.
I'm with T.E.D. here. It is so obvious that this is homework (if it was for something cryptography related, the OP surely would have stated this) and now a complete copy-paste solution is provided. Yes, yes, I hear some people say *"well, it's his/her own responsibility"* or *"s/he will get caught if s/he commits plagiarisms"*. A far better way would be to nudge the student in the towards a solution instead of these type of answers. Mind you, I'm not saying to tell him/her to try Google! Learning him/her how to fish instead of handing him/her one, and all that. Just my 2 cents.
Bart Kiers
In the old comp.lang.c days, we liked to answer homework problems with programs using techniques a new student would be unlikely to know. I'd think that any TA reading this would immediately realize it's not Chris' work.
David Thornley
It doesn't really matter if the code is too advanced for a (beginning) student: **IMO** it is just less helpful to post full-blown solutions instead of pointers that will let the OP create it him/herself. No matter what you say, you cannot change my mind on this, nor do I expect you to see things through my eyes all of a sudden.
Bart Kiers
+21  A: 
int get_prime(void) {
  return 3; /* Prime for all values of 3, including large ones */
}

Oh, you mean want random primes of an arbitrary size?

Mikeage
Funny, yes. Great, not so much. It would have been better in a comment.
paxdiablo
-1: Should've been a comment.
Frerich Raabe
This isn't an answer to earn your **reputation** with.
Moayad Mardini
+1 Brilliant! I especially like the comment.
qrdl
My reputation is something I really couldn't care less about. Look at my history [and the type of questions I've posted]; I come here once in a while, and ask questions that are mostly irrelevant to 90% of readers. Besides, you can't put nice looking source code in a comment ;)
Mikeage
You can make it a CW, then.
Moayad Mardini
It's a nice, compact, commented piece of code that answers the original question almost correctly (the correct answer is "in this answer"), and uses my favorite brace style. I have to upvote.
David Thornley
@David -- what do you mean almost correctly? Not only does it meet the stated requirements just as well as the top answer [which I concede does deserve to be higher than mine...], but it's a whole lot easier to prove as mathematically correct [I should probably add a note that if the result is cast to a floating point type, there are not guarantees that it can be re-cast back into an integer prime]. But thanks for the vote of confidence on the parentheses :)
Mikeage
A: 

Using simple loops with division and checking the remainder with a little multi-threading meant I could find the first 1,000,000 primes in 10 seconds on a Q6600 quad-core 2.4GHz processor.

ck
-1: Answers a different question than the one asked here.
Frerich Raabe
If it's a C program, it would answer the question if it said where to find the program.
David Thornley
I was saying that its such a simple concept, writing one using basic math and loops doesn't take long.
ck
+1  A: 

This is a good one: SIMD-oriented Fast Mersenne Twister (SFMT). But overall it depends what you're looking for, as somebody else pointed out. Is it for a homework assignment? Hiding pr0n from your little sister? Looking for the first X-digit prime number in the first million decimal expansion of e for google interviewing..?

lorenzog
A: 

void main(void) {

int num,i,len=541;


printf("Prime numbers are: ");
for(num=2;num<=len;num++){
    for(i=2;i<=len;i++){
        if ( num%i == 0){
            if ( num==i )
                printf("%d ",num);
            else             
                break;

        }
    }
}

}

Akram Abbas