今天心血来朝,想写一个古老的算法程序,就是求素数,看是很简单,但实际实现也还是要一点时间:呵呵。。。都是我C学得不咱的。
源程序:
#include
#include
#include
typedef struct node{
int data;
struct node *link;
}table;
table *creat_table()
{
table *head=NULL;
if((head=(table *)malloc(sizeof(table)))==NULL)
{
printf("create head print error!\n");
exit(-1);
}
head->data=2;
head->link=NULL;
return head;
}
table *full_table(table *head,int data)
{
table *p=NULL,*s=head;
if((p=(table *)malloc(sizeof(table)))==NULL)
{
printf("create node error !\n");
free_table(head);
exit(-1);
}
p->data=data;
while(head->link)
{
head=head->link;
}
p->link=NULL;
head->link=p;
printf("%d\t",p->data);
return s;
}
table *free_table(table *head)
{
table *p=NULL;
while(head->link)
{
p=head->link;
free(head);
head=p;
}
free(head);
}
int get_prime_number(table *head,int A)
{
int i=0,j=0;
table *p=head;
for(i=3;i<=A;i++)
{
while(p)
{
j=p->data;
if((i%j)==0)
{
goto NEXT;
}
else
{
p=p->link;
}
}
p=full_table(head,i);
NEXT:
p=head;
}
free_table(head);
return 0;
}
int main()
{
int A=0;
table *head=NULL;
printf("Please Input Number:\n");
scanf("%d",&A);
if(A>2)
{
printf("Prime Number from 1 to %d is:\n",A);
printf("%d\t",2);
head=creat_table();
get_prime_number(head,A);
}
else
if(A==2)
{
printf("Prime Number from 1 to %d is:\n",A);
printf("%d",A);
}
else
{
printf("Please Input >2 number!\n");
}
printf("\n");
return 0;
}
运行结果:
Please Input Number:102
Prime Number from 1 to 102 is:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101
阅读(737) | 评论(0) | 转发(0) |