Re: Prime Numbers




rhle.freak wrote:
Here is my code to generate prime numbers.It works absolutely fine when
the range is
*not very large*. However on initializing i with a large integer it
produces erroneous results
(some numbers ending in 5 ..which obviously cannot be prime numbers)
can anyone please help me out with the reason??


/*Generate Prime Numbers*/
#include<stdio.h>
#include<stdlib.h>

struct node{
int data;
struct node *next;
};

typedef is needed in C not in C++

node* create_node(void)
{
struct node *z;
z=(node*)malloc(sizeof(node));
if(z==NULL)
{
printf("Error");
exit(0);
}
return z;
}

node* node_insert(struct node *start,int prime_num)
{
struct node *z;
z=create_node();
z->data=prime_num;
z->next=start;
start=z;

return start;

}

int main(void)
{
int flag;
unsigned /*long long*/ int i;
struct node *start=NULL,*j;

for(i=2;i<20000;i++) /*Range to check*/
{
flag=0;
for(j=start;j!=NULL;j=j->next) /*Call the prime numbers from
the stack*/
{
if(i%j->data==0 || i%2==0)
flag=1;
}
if(flag==0)
{
start=node_insert(start,i); /*Push the generated prime numbers into
the stack*/
printf("%d\n",i);
}
}
return 0;
}
I ran it and found primes until 20000 fine. Well can you tell me for
which testcase it fails which value of i it fails. One reason could be
overflow .Otherwise it looks fine

Moreover do a for(i=3;i< MAX ;i+=2)

.



Relevant Pages

  • Re: what is wrong?
    ... The only reason you "should" get no output is if the int 21h/47h fails. ... After the "xlatb", ...
    (alt.lang.asm)
  • Re: Value type intialization...
    ... which fails for the same reason; you /must/ give it a starting value, ... Marc ...
    (microsoft.public.dotnet.languages.csharp)
  • radix sort
    ... struct node *next; ... void freelist; ... int large_dig; ... kth digit of all no:s */ ...
    (comp.programming)
  • LinkedList Pointer (REPOST - diff version)
    ... struct node * next; ... No problem until you are dealing with a pointer variable. ... void Push(struct node** headRef, int newData); ... Given an int and a reference to the head pointer (i.e. a struct ...
    (comp.lang.c)
  • LinkedList Pointer (REPOST - diff version)
    ... struct node * next; ... No problem until you are dealing with a pointer variable. ... void Push(struct node** headRef, int newData); ... Given an int and a reference to the head pointer (i.e. a struct ...
    (comp.lang.c)