turboc中使用链表和递归的素数

turboc中使用链表和递归的素数,c,recursion,linked-list,turbo-c,C,Recursion,Linked List,Turbo C,我试图将一些链表添加到我的递归素数代码中,我能够使用链表存储值,然后当我要检索两个输入数之间的素数时,我得到了这个结果 对于输入1和5:1,21,301,5 输出应为: 2,3,5 代码是: #include<stdio.h> #include<math.h> #include<stdlib.h> struct node { //struct node *prev; int num; struct node *nxt; }*head;

我试图将一些链表添加到我的递归素数代码中,我能够使用链表存储值,然后当我要检索两个输入数之间的素数时,我得到了这个结果

对于输入1和5:
1,21,301,5

输出应为:

2,3,5

代码是:

#include<stdio.h>
#include<math.h>
#include<stdlib.h>

struct node
{
    //struct node *prev;
    int num;
    struct node *nxt;
}*head;

void store(int value){
    struct node *var, *temp;
    var = (struct node *)malloc(sizeof(struct node));
    var->num = value;
    if(head==NULL){
        head = var;
        head->nxt = NULL;
    }else{
        temp = var;
        temp->nxt = head;
        head=temp;
    }
}

void accept(int value, int i){
    if(i<2){
        printf("Enter value: ");
        scanf("%d", &value);
        store(value);
        i++;
        accept(value,i);
    }
}

void prime(){
    int num,x,y;
    struct node *temp,*temp2,*var;
    temp = head;
    temp2 = temp->nxt;
    y = temp->num;
    x = temp2->num;
    primeloop(x,y);
}

int primeloop(int x,int y){
    int num;
    if ( x == 1 ) x++;
    if(x <= y){
        num = isPrime(x,2); // second input parameter added
        printf("%d",num);
        if(num == 0){
             printf("");
         }else{
             printf("%5d",x);
         }
        primeloop(x+1,y);
    }
}

int isPrime(int n, int i){
    if(n%i==0 && n!=2 && n!=i){
      return(0);
    } else {
       if (i < sqrt(n)) {
        return( isPrime(n,i+1) );
    } else
     return(1);
    }
}

void main(){
    int i,value;
    clrscr();
    i = 0;
    accept(value,i);
    prime();
    getch();
}
#包括
#包括
#包括
结构节点
{
//结构节点*prev;
int-num;
结构节点*nxt;
}*头部;
无效存储(int值){
结构节点*var,*temp;
var=(结构节点*)malloc(sizeof(结构节点));
var->num=值;
if(head==NULL){
水头=var;
head->nxt=NULL;
}否则{
温度=var;
温度->nxt=水头;
压头=温度;
}
}
无效接受(int值,int i){
如果(inxt;
y=温度->数值;
x=temp2->num;
素数环(x,y);
}
整数素数循环(整数x,整数y){
int-num;
如果(x==1)x++;

如果(x我发现了你的问题,我想。你的算法是正确的,但是你有两个冗余的
printf
s

您的
primeloop
应该是这样的

int primeloop(int x,int y){
    int num;
    if ( x == 1 ) x++;
    if(x <= y){
        num = isPrime(x,2); // second input parameter added
        if(num != 0){
            printf("%5d ",x);
        }
        primeloop(x+1,y);
    }
}
intprimeloop(intx,inty){
int-num;
如果(x==1)x++;

如果(x侧注:
head
没有很好地初始化。最好是
…head=NULL
。注意;NULL并不总是0。@chux会记住这一点,谢谢哦,谢谢,不敢相信我错过了,我只是把它放在第一位,如果要检查num,无论如何,谢谢你指出我明显的错误。