code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
Terms of Agreement:
By using this code, you agree to the following terms...
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for langauges that allow it) freely and with no charge.
2) You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
//
/* gprime.c -
A simple yet very fast C-program (if not the fastest) I wrote to generate
prime numbers and store them into 'primes.dat'.
It calculates all prime numbers starting from 1 to 1000000.
Note that the program has to start with an odd number (1, 3, 5, 7, ...) in
order to work properly. When 2 becomes calculated, there's a fault because
it's not recognized as a prime number however it is one, so you'll have to
manually add it to the file.
Also, you can restart the program at a later time with let's say 1000001
(odd) 'till 10000000 and the prime numbers will automatically be added to
the file. */
#include
#include
#include
#include
void main() {
FILE *fp;
unsigned long i, j, okay=0, root;
if ((fp=fopen("primes.dat", "a"))==NULL) {
fprintf(stderr, "Error: primes.dat could not be created.");
exit(1);
}
for (i=1; i<1000000; i+=2) {
root=(unsigned long) ceill(sqrt(i))+1;
for (j=1; j if (!(i%j)) okay++; if (okay==1) { printf("%ld\n", i); fprintf(fp, "%ld\n", i); } okay=0; } fclose(fp); }