Mail Archives: djgpp/2000/06/24/14:45:15
okay, so I forgot a function... here:
#include <stdio.h>
#include <stdlib.h>
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");
}
- Raw text -