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

int target;
int num_threads;

void* find_factors(void* arg) {
  int start = *((int* )arg);
  for (int i = start; i <= target; i = i + num_threads) {
    if (target % i == 0) {
      printf("%d is a factor\n", i);
    }
  }
  return NULL;
}

int main(int argc, char** argv){
  if (argc != 2) {
    printf("Usage: %s num\n", argv[0]);
    return -1;
  }
  target = atoi(argv[1]);
  num_threads = atoi(argv[2]);
  pthread_t* threads = malloc(num_threads * sizeof(pthread_t));
  int* starts = malloc(num_threads * sizeof(int));
  for(int i = 0; i < num_threads; i++){
    starts[i] = i + 1;
    pthread_create(&threads[i], NULL, &find_factors, &starts[i]);
  }
  free(starts);
  free(threads);
  for(int i = 0; i < num_threads; i++)
    pthread_join(threads[i], NULL);
  printf("All done!\n");
  return 0;
}