C program to print first 10 prime numbers
Output:
The first 10 prime numbers are:
2 3 5 7 11 13 17 19 23 29
Implementation:
Output:
The first 10 prime numbers are:
2 3 5 7 11 13 17 19 23 29
Implementation:
/* This method uses the "sieve of erasthothenes algorithm" An algorithm to print largest prime numbers */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <limits.h> #define MAX 1000000 /* Initially setting values of all the hash indices to zero */ int hash[MAX]={0}; /* setting the multiples of n to 1 inorder to consider those numbers as non-prime numbers */ void sethash(int n) { int i; for(i=1;i*n<MAX;i++) { if(hash[i*n]==0) { hash[i*n]=1; } } } int main(void) { /* set the value of n according to your number of prime numbers to print */ int n=10; int i; int count=0; printf("The first 10 prime numbers are:\n"); for(i=2;i<MAX;i++) { /* if the value's hash index is not set, it is a prime number then, set all the multiples of that number as non-prime number using sethash() function */ if(hash[i]==0) { /* if we already reached n prime numbers, we can stop finding & printing prime numbers */ count++; printf("%d ",i); if(count==n) { break; } sethash(i); } } return 0; }