Вопрос

Good Day,

I'm trying to make a code that would determine the prime numbers between two numbers. This should be done recursively and without any loop. So far I have this code:

#include<stdio.h>
#include<conio.h>
void prime(int x, int y){
    int waa;
    if(x <= y){
        waa = isPrime(x);
        if(waa==1 || waa == 0){
             printf("");
         }else{
             printf("%5d",waa);
         }
        prime(x+1,y);
    }
}

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

void main(){
    int num[2];
    clrscr();

    printf("Input 2 numbers: \n");
    scanf("%d %d", &num[0], &num[1]);
    prime(num[0], num[1]);
    getch();
}

the output between 1 and 10 is: 2,2,3,5,7,9. expected output: prime numbers 2,3,5,7

Would anyone be able to help me with this.

much appreciated

Thank you

Это было полезно?

Решение

It will be simpler if function isPrime just checks whether the given integer is prime or not and outputs a Boolean value.

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

void prime(int x, int y){
    int waa;
    if ( x == 1 ) x++;
    if(x <= y){
        waa = isPrime(x,2); // second input parameter added
        if(waa != 0){
            printf("%5d",x);
         }
        prime(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;
    }
}

int main(){
    int num[2];

    printf("Input 2 numbers: \n");
    scanf("%d %d", &num[0], &num[1]);
    prime(num[0], num[1]);
    return 0;
}

Input:

1
10

Output:

2 3 5 7

http://ideone.com/gyW7ED

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top