primes/primes.alt3.c

50 lines
947 B
C
Raw Normal View History

2011-03-08 07:01:27 +00:00
// C version of a Prime Number Finder
// Alternate Algorithm: Instead of using sqrt function,
// track it with two variables
// haplo@mindstab.net
#include <stdio.h>
#include <stdlib.h>
int check(int i, int cnt, int m)
{
if(i > m) return 1;
else {
if( (cnt%i)==0) return 0;
return check(i+2,cnt, m);
}
}
int primes(int c, int m, int sq, int sqm)
{
if(c > m) return 1; else
{
if(check(3,c,sq))
printf("%d\n", c);
if(c>=sqm) {
sq++;
sqm = sq*sq;
}
return primes(c+2, m, sq, sqm);
}
}
int main(int argc, char **argv)
{
unsigned int i, x, max=2, isP, sqr=4;
unsigned int MAX_NUM;
if(argc < 2) {
printf("primesaltc <MAX NUM>\n");
return -1;
} else {
MAX_NUM = atoi(argv[1]);
}
if(MAX_NUM < 1)
{
printf("Invalid MAX_NUM specified\n");
return -1;
}
primes(3, MAX_NUM, 2,4);
}