数据结构与算法应用(七):筛选算法

将自定义范围的数存在单链表中,利用爱拉托散(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 );
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值