Mail Archives: djgpp/2000/06/24/14:30:34
On Sat, 24 Jun 2000 15:36:01 GMT, kknd_bl AT hotmail DOT com wrote:
>how can I write a program that displays all the prime numbers (numbers
>that can only be divided by themselves and one) from 1 to N ??
>
>
>Sent via Deja.com http://www.deja.com/
>Before you buy.
I don't think here's where you ask people to write your programs for
you, but I'll do this one cause I'm bored.
first off, one isn't a prime number, so you don't need to include
that, and you know two is... you'll want something like this.
#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);
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;
}
if there's any problems, email me at sproctor AT ccs DOT neu DOT edu I haven't
tested it at all so it's likely there will be. as far as I know that
should work though.
Sean
- Raw text -