primenums_pc.c 2.47 KB
/* -----------------------------------------------------------------------------
 *  Copyright (C) 2019-2021 daiteq s.r.o.                http://www.daiteq.com
 *
 *  This program is distributed WITHOUT ANY WARRANTY; without even
 *  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 *  PURPOSE.
 *
 * -----------------------------------------------------------------------------
 *  Filename    : primenums_pc.c
 *  Authors     : Martin Danek
 *  Description : Sieve of Eratosthenes - reference desktop implementation
 *  Release     :
 *  Version     : 1.0
 *  Date        : 27.4.2021
 * -----------------------------------------------------------------------------
 */


#include <stdio.h>
#include <stdlib.h>


#define PRINT_ITEMS /* */
#define VERBOSE /*
/* #define LONGRUN /* */


#define MAXNUM 1300000
#define SQRTMAXNUM 1141 // ceil(sqrt(1300000))

// #define MAXNUM 8192 // 1300000
// #define SQRTMAXNUM 92 // 1141 // ceil(sqrt(1300000))

void i_print(unsigned i) {
  unsigned char buf[22];
  unsigned idx=20;
  buf[21]='\0';
  //  buf[20]='\n';
  if (i==0) {
    buf[idx--]='0';
  }
  else {
    while ((i>0)&&(idx>0)) {
      buf[idx--]='0'+(i%10);
      i=i/10;
    }
  }
  buf[idx]=' ';
  printf("%s",&buf[idx]);
}

unsigned i_conv(char *s) {
  unsigned val=0;
  unsigned i=0;
  while (*(s+i)!='\0') {
//     printf("%c",*(s+i));
    val*=10;
    val+=*(s+i)-'0';
    i++;
  }
//   printf("\n");
  return val;
}


int main(void) {
int i,j;
unsigned sz;
unsigned *a;
// char *a;
unsigned top;
unsigned acc;

sz = sizeof(unsigned);
// sz = sizeof(char);
top = MAXNUM;


if ((a=malloc(top*sz))==NULL) {
  printf("primenums: malloc failed for size %u\n",top*sz);
  exit(1);
}

printf("primenums: MAXNUM is ");i_print(top);
printf("\n");
// printf("primenums: sizeof(unsigned) is ");i_print(sz);
printf("primenums: sizeof(char) is ");i_print(sz);
printf("\n");

printf("primenums: initializing array\n");
for (i=0;i<top;i++) {
  *(a+i)=1;
//   i_print(i);
}


printf("primenums: eliminating composites\n");
j=2;
while(j<SQRTMAXNUM) {
  while (*(a+j)==0)
    j++;
    for (i=j;i<top;i=i+j)
      if (i>j) {
        *(a+i)=0;
    }
    j++;
}

#ifdef PRINT_ITEMS
#ifdef VERBOSE
printf("primenums: printing primes\n");
#endif
acc=0;
for (i=1;i<top;i++)
#ifdef VERBOSE
  if (*(a+i)==1) {
    printf("%d\n",i);
    acc++;
  }
#else
  if (*(a+i)==1)
    printf("1");
  else
    printf("0");
#endif
printf("\n");
#endif

printf("primenums: primes found: %d\n\n",acc);


printf("\n*** END OF TEST ***\n");

}