From: Sean Proctor Newsgroups: comp.os.msdos.djgpp Subject: Re: prime numbers Message-ID: <5hv9lss7coonkir69gckd85dirsk2d44ep@4ax.com> References: <8j2kh1$v5e$1 AT nnrp1 DOT deja DOT com> <0br9ls8epo0j6qabj75jfg7f829p43ip1i AT 4ax DOT com> X-Newsreader: Forte Agent 1.8/32.548 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Lines: 98 Date: Sat, 24 Jun 2000 18:29:52 GMT NNTP-Posting-Host: 207.16.154.84 X-Complaints-To: Abuse Role , We Care X-Trace: monger.newsread.com 961871392 207.16.154.84 (Sat, 24 Jun 2000 14:29:52 EDT) NNTP-Posting-Date: Sat, 24 Jun 2000 14:29:52 EDT Organization: ENTER.net (enter.net) To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com okay, so I forgot a function... here: #include #include typedef prime_list struct PRIME_LIST /*I always forget the order here, that might be wrong*/ struct PRIME_LIST { prime_list *next int num; }; int get_number(int argc, char *argv[]); int div_by_list(int num, prime_list *list); void add_num(int num, prime_list *list_end); void print_list(prime_list *list); int main(int argc, char *argv[]) { int num; struct prime_list *list, *end; num = get_number(argc, argv); /*read number from arg list, if it's not there, take input for it*/ /*add 2 to the beginning of the list*/ list = (prime_list *)malloc(sizeof(prime_list)); list->num = 2; list->next = null; end = list; /*okay, now start stepping through all numbers*/ for(i = 3; i <= num; i++) if(!div_by_list(i, list)) /*div i by each number in list, return whether it was divisible by any*/ add_num(i, end); /*if it wasn't add it to the list*/ print_list(list); /*self explanatory*/ return 0; } int get_number(int argc, char *argv[]) { int num; char str[256]; if(argc) { num = atoi(argv[0]); if(argc > 1) { printf("Invalid input string.\n"); if(num){ printf("Using the first number.\n"): return num; } } if(num) return num; } gets(str); /* I forget if this takes an argument or if it returns a pointer, you'll have to figure that out */ num = atoi(str); return num; } int div_by_list(int num, prime_list *list) { prime_list *temp; temp = list; while(temp) { /* if there's no remainder, return true.*/ if(num % temp->num == 0) return 1; temp = temp->next; } /*if it got to the end of the list, return false*/ return 0; } void add_num(int num, prime_list *list_end) { /*start at the end because lower numbers are more common and so we don't have to step through the list*/ list_end->next = (prime_list *)malloc(sizeof(prime_list)); list_end = list_end->next; list_end->num = num; list_end->next = null; } void print_list(prime_list *list) { prime_list *temp; temp = list; while(temp) { printf("%d ", temp->num); /*you can change the format here, I don't know how you want it.*/ temp = temp->next; }; printf("\n"); }