int main(int argc, char *argv[]) { int d, f, n, p, q, r; r = 1; if (argc < 2) { printf("Enter the number you'd like to factor.\n"); for (scanf("%d", &n); n <= 0; scanf("%d",&n)) { while (fgetc(stdin) != '\n'); printf("Invalid input. Enter an integer to factor: "); } } else { if (strcmp(argv[1], "-l") == 0 || strcmp(argv[1], "--list") == 0) { list_primes(atoi(argv[2])); if (list_primes <= 0) { printf("Invalid argument.\n"); return 1; } return 0; } else { n = atoi(argv[1]); if (n <= 0) { printf("Invalid argument.\n"); return 0; } } } p = n; for (int c = 2; c < n && r < n; c += 2) { if (n % c == 0 && !isprime(c)) { if (f == 0) printf("\nFactors:\n"); d++; if (f > 0) printf(", "); while (p % c == 0 && p != 1) { f++; q++; p /= c; r *= c; } printf("%d", c); if (q > 1) printf("^%d", q); q = 0; } if (c == 2) c--; } if (f > 0) printf("\n"); printf("\nResults:\n"); if (f > 0) { printf("%d is a composite number with %d factors, %d of which are" " distinct.\n", n, f, d); } else { printf("%d is prime.\n", n); } return 0; }
/*----------------------------------------------------------------------------- * FUNCTION: create_processes * * DATE: January 25, 2010 * * REVISIONS: * * DESIGNER: Steffen L. Norgren <*****@*****.**> * * PROGRAMMER: Steffen L. Norgren <*****@*****.**> * * INTERFACE: void create_threads(PRIME_OPTIONS *opts) * opts - structure that sores options * * RETURNS: void * * NOTES: Creates a specified number of processes, which is defined by the * opts->processes variable. * *----------------------------------------------------------------------------*/ void create_processes(PRIME_OPTIONS *opts) { unsigned long prime_start, prime_stop; pid_t pid = -2; /* force the switch into default */ pid_t *child; int i; child = malloc(opts->processes * sizeof(pid_t)); /* The first process's processing block. */ prime_start = opts->start; prime_stop = opts->start + opts->block; for (i = 0; i <= opts->processes; i++) { switch (pid) { case -1: /* fork error */ perror("Error occoured with fork()\n"); exit(_FORK_ERROR); case 0: /* child process */ printf("Child pid %d starting on range %ld - %ld\n", getpid(), prime_start, prime_stop); list_primes(prime_start,prime_stop); printf("Child pid %d finished range %ld - %ld\n", getpid(), prime_start, prime_stop); exit(_CHILD_EXIT); default: /* parent process*/ if (i != opts->processes) { pid = fork(); child[i] = pid; /* Subsequent process's processing blocks */ if (pid != 0) { prime_start = prime_stop; prime_stop = prime_stop + opts->block; } } } } }