#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <dispatch/dispatch.h>

#define INTERVALO 300
#define BEGINIG 5000

int main(int argc, char *argv[])
{
  uint32_t quantidade, k;
  if (argc==2) quantidade = atoi(argv[1]);
  else quantidade = 20;
  
  dispatch_queue_t globalFila = dispatch_get_global_queue(0, 0);
  dispatch_group_t grp = dispatch_group_create();
  
  for (k = 0; k < quantidade; k++) {
    dispatch_group_async(grp, globalFila, ^{
		uint32_t inicio, fim, j, primo, i, total;
		total = 0;
		inicio = k * INTERVALO + BEGINIG;
		fim = inicio + INTERVALO;
	    for ( i = inicio; i < fim; i++){
			primo=0;
			for ( j = 2; j <= i; j++){
        	  if ( i%j == 0 ){
        		primo++;
        		if ( primo > 1 ){
        		  j=i;
        		}
        		else{
        		  if ( primo == 1 && j == i ){
        			//printf("Primo %d\n", i);
        			total++;
        		  }
        		}
        	  }
			}
		}
		//printf("Task %d -> total: %d\n", k, total);
    });
  }
  dispatch_group_wait(grp, DISPATCH_TIME_FOREVER);
  
  //printf("\n\nMatriz calculada\n"); 
  
  return 0;
}