This is a C Program to find prime number between a given range using Wheel Seive method. Wheel factorization is a graphical method for manually performing a preliminary to the Sieve of Eratosthenes that separates prime numbers from composites.
The algorithm goes this way, Start by writing the natural numbers around circles as shown below. Prime numbers in the innermost circle have their multiples in similar positions as themselves in the other circles, forming spokes of primes and their multiples. Multiples of the prime numbers in the innermost circle form spokes of composite numbers in the outer circles.
Here is source code of the C Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <malloc.h>
#define MAX_NUM 50
// array will be initialized to 0 being global
int primes[MAX_NUM];
void gen_sieve_primes(void) {
int p;
// mark all multiples of prime selected above as non primes
int c = 2;
int mul = p * c;
for (p = 2; p < MAX_NUM; p++) // for all elements in array
{
if (primes[p] == 0) // it is not multiple of any other prime
primes[p] = 1; // mark it as prime
for (; mul < MAX_NUM;) {
primes[mul] = -1;
c++;
mul = p * c;
}
}
}
void print_all_primes() {
int c = 0, i;
for (i = 0; i < MAX_NUM; i++) {
if (primes[i] == 1) {
c++;
if (c < 4) {
switch (c) {
case 1:
printf("%d st prime is: %d\n", c, i);
break;
case 2:
printf("%d nd prime is: %d\n", c, i);
break;
case 3:
printf("%d rd prime is: %d\n", c, i);
break;
default:
break;
}
}
else
printf("%d th prime is: %d\n", c, i);
}
}
}
int main() {
gen_sieve_primes();
print_all_primes();
return 0;
}
Output:
$ gcc WheelSeive.c $ ./a.out 1 st prime is: 2 2 nd prime is: 3 3 rd prime is: 5 4 th prime is: 7 5 th prime is: 11 6 th prime is: 13 7 th prime is: 17 8 th prime is: 19 9 th prime is: 23 10 th prime is: 29 11 th prime is: 31 12 th prime is: 37 13 th prime is: 41 14 th prime is: 43 15 th prime is: 47
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Apply for C Internship
- Apply for Computer Science Internship
- Practice BCA MCQs
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos