How to find prime numbers in a given range?

Asked

Viewed 2,532 times

-1

I need some help on that show, on the outside. Next, I need to print the prime numbers within that user-determined range A and B, the problem is that the program only prints a number within that range. And tbm show whether or not you have prime number within the range. I thank you if anyone can help.

#include<stdlib.h>
#include<stdio.h>
main(){
int a, b, div=0;
printf("Digite o numero a:\n");
scanf("%d",&a);
if (a>=0 && a<=100){
    printf("Numero a esta entre 0 e 100\n",a);
}else{
    printf("Nao esta entre 0 e 100, digite novamente:\n", a);
    while(a>100){
        printf("Numero ivalido, digite novamente: \n");
        scanf("%d", &a);

    }
}
printf("Digite o numero b:\n");
scanf("%d",&b);
if (b>=0 && b<=100){
    printf("Numero b esta entre 0 e 100\n",b);

}else{
    printf("Nao estao entre 0 e 100, digite novamente:\n",b);
    while(b>100){
        printf("Numero invalido, digite novamente: \n");
        scanf("%d",&b);

    }

}
for(int i=a+1;i<b;i++){
    if(div%i==0){
        div++;
        printf("%d\n",i);

    }

}
if(div==2){
    printf("Sem numeros primos no intervalo");
}

}

  • The finding of the cousins part is almost all to do, ending up having enough code but almost none focusing on the problem. And so it’s hard to help without doing all the code..

  • Well, I wanted to know how to do this part of the range, pro program print the primes in this range typed by the user.

1 answer

1


I made a small functional example for you to analyze, remembering that prime numbers can only be divided by themselves and by one, so it is necessary more than one repeating structure in the code, any doubt contact me :)

int primo=0;
int a = 0;
int b = 1;
int tem_primo = 0;

printf("Numeros primos::.\n");

for(int i = a; i<=b; i++){

  //Inicia o verificador sempre como zero
  primo=0;

  for (int x = 1; x <=i; x++) {

    if(i % x == 0){
      primo++;
    }

  }
  if(primo==2){

    //Mostra na tela os numeros primos um a um
    printf("%d; ", i);
    tem_primo = 1;
  }
}

//Verifica se há primos no intervalo
if(tem_primo == 0){
  printf("\nNao possui primos no intervalo");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.