| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Prime numbers |
JB> to avoid the sqrt() you could if you're working
JB> sequentially you can store square of the prime above
JB> thats too big to be used yet and when you reach that
JB> number go the the next prime in your list etc...
I did one using an integer based square root function which
only checks one less than or one greater than multiples of
six, which all primes seem to be for some reason. :)
This finds all primes < 32766 in 2.6 seconds on my 486sx25.
On my Pentium, it takes less than 0.3 seconds. The resulting
array of primes is sufficient for checking further primes up
to squared(32749). This is using only integers, using only
DOS and 640K, and using only standard malloc(). It should be
rather simple to go much farther with a big number library
and a huge allocation utility.
/*_|_| PRIMES.C
_|_|_| A program to find all the primes < 32,766.
_|_|_| No warrantee or guarantee is given or implied.
_|_|_| Released PUBLIC DOMAIN by Kurt Kuzba. (10/2/96)*/
#include
#include
#include
int rootsqr(int val)
{
unsigned long ndx, cmp, dif;
ndx = cmp = dif = (unsigned long)val;
while((ndx * ndx) > cmp) ndx -= (dif >>= (dif > 1));
while((ndx * ndx) <= cmp) ndx++;
return (int)--ndx;
}
int main(int c, char **v)
{
int ndx = 2, check, prime, current, limit, *primes, show = 0;
float runtime = (float)clock();
primes = malloc(3600 * sizeof(int));
if(primes == NULL)
return puts("Malloc failure");
primes[0] = 1, primes[1] = 2, primes[2] = 3;
if(c > 1 && (v[1][0] == 's' || v[1][0] == 'S')) show++;
for(current = 6; current < 32766; current += 6)
{
check = prime = 1;
limit = rootsqr(current - 1);
while(prime && primes[++check] <= limit)
prime = (int)((current - 1) % primes[check]);
if(prime)
if(show)
printf("%8d", primes[++ndx] = current - 1);
else
primes[++ndx] = current - 1;
check = prime = 1;
limit = rootsqr(current + 1);
while(prime && primes[++check] <= limit)
prime = (int)((current + 1) % primes[check]);
if(prime)
if(show)
printf("%8d", primes[++ndx] = current + 1);
else
primes[++ndx] = current + 1;
}
runtime = ((float)clock() - runtime) / CLK_TCK;
printf("\n%d Primes found in %.2f seconds", ndx + 1, runtime);
return 0;
}
/*_|_| end PRIMES.C */
> ] * Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)SEEN-BY: 396/1 622/419 632/371 633/260 267 270 371 634/397 635/506 728 SEEN-BY: 639/252 670/213 218 @PATH: 154/750 222 396/1 633/260 635/506 728 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.