Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
For example, if n is 9 the output should be “2, 3, 5, 7″. If n is 18, the output should be “2, 3, 5, 7, 11, 13, 17″.
For example, if n is 9 the output should be “2, 3, 5, 7″. If n is 18, the output should be “2, 3, 5, 7, 11, 13, 17″.
#include<stdio.h>#include<malloc.h>#include<math.h>void unsetBit(char *b,int i){ int blk=(i-1)/8; int shift=((i-1)%8); b[blk] &= ~(1<<shift);}int bitStatus(char *b,int i){ int k,t,blk=(i-1)/8; int shift=((i-1)%8); k=b[blk]&(1<<shift); t=(k!=0)?(blk*8+(int)log2((double)k)+1):0; return t;}int main(){ int n,nb,i,j,k; printf("\n Enter range of numbers = "); scanf("%d",&n); nb=(int)ceil((double)n/8.0); char *b=malloc(nb); printf("# bytes required = %d\n",nb); for(i=0;i<nb;b[i++]=0xFF); for(i=2;i<=sqrt(n);i++){ if(bitStatus(b,i) != 0){ for(j=i*i;j<=n;j+=i){ unsetBit(b,j); } } } printf("\n"); for(i=2;i<=n;i++){ k=bitStatus(b,i); if(k!=0) printf("%5d",k); } printf("\n"); return 0;}//end