Created
October 16, 2013 06:22
-
-
Save AndreasHassing/7003375 to your computer and use it in GitHub Desktop.
\n between each prime in numbers.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
#include <stdlib.h> | |
int is_prime(unsigned long long p){ | |
unsigned long long i; //For the loop | |
for (i = 2; i <= p-1; i++){ //Counts to the number before p | |
if (p % i == 0) { //If no remainder it divides and therefore a composite number | |
//printf("0\n"); | |
return 0; | |
} | |
} | |
//printf("1\n"); // If not composite, prime | |
return 1; | |
} | |
void *print_prime_factors(void *arg){ | |
unsigned long long i; //For the loop | |
unsigned long long *n = (unsigned long long *)&arg; | |
printf("%llu: ", *n); | |
for (i = 2; i <= *n-1; i++){ //Counts to the number before n | |
if (*n % i == 0) { //Factor | |
if (is_prime(i) == 1) { // If prime | |
printf("%llu ", i); | |
} | |
} | |
} | |
printf("\n"); | |
return 0; | |
} | |
int main(){ | |
FILE *text; //Format needed to open a file | |
unsigned long long m; | |
pthread_t thread0; //Reference to the second thread | |
text = fopen("numbers.txt", "r"); | |
int r = fscanf(text, "%llu", &m); | |
while(r != EOF){ //EOF is the end of the scan by default | |
if (r==1) { | |
if (is_prime(m) == 1){ //If the number is a prime itself | |
printf("%llu: is prime \n", m); | |
} | |
else { | |
print_prime_factors((unsigned long long *)m); | |
} | |
} | |
r = fscanf(text, "%llu", &m); | |
} | |
fclose(text);//Closes the file after using it | |
if(pthread_create(&thread0, NULL, &print_prime_factors, &m)) { //Creating thread | |
fprintf(stderr, "Error creating thread\n"); | |
return 1; | |
} | |
if(pthread_join(thread0, NULL)) { //Waiting for the thread to finish | |
fprintf(stderr, "Error joining thread\n"); | |
return 2; | |
} | |
pthread_exit(NULL); // Exiting the thread | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment