#include <assert.h> #include <math.h> #include <stdio.h> #include <string.h> /* Included for strcmp. */ unsigned int check_prime(unsigned int number) { unsigned int divisor; unsigned int boolprime; boolprime = 1; /* Initialize boolean 'prime' as being true */ for (divisor = number - 1; divisor > 1; divisor--) { if (number % divisor == 0) { boolprime = 0; divisor = 1; /* to exit loop when not prime */ } } return (boolprime); } unsigned int count_factors(unsigned int n) { unsigned int factor; unsigned int result; unsigned int count; result = n; assert(n > 1); for (factor = 2; result > 1; factor++) { while (result % factor == 0 && check_prime(factor)) { result = result / factor; count++; } } printf return (count); } unsigned int count_distinct_factors(unsigned int n) { unsigned int factor; unsigned int result; unsigned int count; result = n; assert(n > 1); for (factor = 2; result > 1; factor++) { while (result % factor == 0 && check_prime(factor)) { result = result / factor; } count++; } return (count); } void test_factors(void) { unsigned int n = 12; printf("\n%u has ", n); printf("%u factors, ", count_factors(n)); printf("%u of them distinct.\n",count_distinct_factors(n)); } /* * Requires: * Nothing. * * Effects: * If the "-t" option is specified on the command line, then test code is * executed. Otherwise, requests a number from standard input and prints * the number of prime factors that number has and the number of those * factors that are distinct. Upon completion, the program always returns * 0. * * If the number that is input is not between 2 and the largest unsigned * integer, the output of the program is undefined, but it will not crash. */ int main(int argc, char **argv) { unsigned int n; /* If "-t" is specified, run test procedure and exit program. */ if (argc > 1 && strcmp(argv[1], "-t") == 0) { test_factors(); return (0); } /* Get input. */ printf("Enter number:\n"); scanf("%u", &n); /* Print results. */ printf("%u has %u prime factors, %u of them distinct.\n", n, count_factors(n), count_distinct_factors(n)); /* No errors. */ return (0); }

When I comment out all but one of the lines in the "test_factors" function, the output is correct. However, when I try to print all of them (see: 'main' function), the output is way off. For example, an input of 12 for the 'main' function would output the following:

" 12 has 11084 prime factors, 11081 of them distinct."

I'm assuming this has something to do with the fact that I am working exclusively with unsigned integers and that there is some sort of overflow/offset that I am unaware of. Any suggestions would be greatly appreciated.

-- Sarah --