将自定义范围的数存在单链表中,利用爱拉托散(Eratosthenes)法进行判断,若满足倍数条件将其释放掉。
/*
求任意给定范围之间的素数。
*/
//用自定义结构体typedef struct设计该软件的数据结构;
typedef struct num{
long int data;
struct num *next;
}Num;
long int n1,n2,n;
//初始化链表
Num *InitList(Num *head)
{
head=(Num*)malloc(sizeof(Num));
head->next=NULL;
return head;
}
//输入并筛选掉偶数
Num *inputdata(Num *head)
{
int i;
Num *s,*s1;
s1=InitList(s1);
s1=head;
printf("请输入要查找素数的范围:");
scanf("%d%d",&n1,&n2);
n=n2-n1+1;
if (n1<3)
{
i=3;
}
else
{
if (n1%2==0)
{
i=n1+1;
}
else
{
i=n1;
}
}
while(1)
{
s=(Num *)malloc(sizeof(Num));
s->data=i;
s->next=NULL;
s1->next=s;
s1=s1->next;
i=i+2;
if (i>n2+2)
{
break;
}
}
return head;
}
//输出剩下的数
Num *output(Num *head)
{
Num *s;
s=InitList(s);
s=head->next;
while (s->next!=NULL)
{
printf("%d\t",s->data);
s=s->next;
}
}
//单链表筛选法筛选
Num* delete(Num* head)
{
Num *p,*q,*m;
p=InitList(p);
q=InitList(q);
m=InitList(m);
p=m=head->next;
while (m!=NULL)
{
while(p->next != NULL)
{
if((p->next->data) % (m->data) == 0)
{
if(p->next->next==NULL) break;
q=p->next;
p->next=p->next->next;
free(q);
n--;
}
p=p->next;
}
p=m->next;
m=m->next;
}
return head;
}
//进行函数的调用并计时
void main()
{
Num *head,*p;
double duration;
clock_t begin,end;
p=InitList(p);
head=InitList(head);
head=inputdata(head);
printf("筛选前:\n");
output(head);
begin=clock();
p=delete(head);
end=clock();
duration=(double)(end-begin)/CLOCKS_PER_SEC;
printf("\n筛选后:\n");
output(p);
printf("\n");
printf("素数的个数n=%ld\n",n);
printf( "所用时间为:%f seconds\n", duration );
}