I don’t understand why it doesn’t show all the cousins in this range

Asked

Viewed 48 times

0

#include <stdio.h>

int eh_primo(int x){
    int i;
    int cont;
    for (i=1;i<=x;i++){
        if (x % i == 0){
          cont +=1;
        }
    }
    if (cont == 2 || cont == 1){
      return 1;
    }else{
      return 0;
    }
}

void todos_os_primos(int max){
  int j;
  for (j=1;j<=max;j++){
    if(eh_primo(j) == 1){
      printf("%d",j);
    }else{}
  }

}


int main (void){
    int n;
    printf("Digite o numero: \n");
    scanf("%d",&n);
    todos_os_primos(n);
    return 0;
}
  • 2

    How much is it worth cont += 1 if you do not know the value of cont? Remember that number 1 is not prime.

1 answer

1

Missed you to initialize cont=0 in function eh_primo

int eh_primo(int x){
    int i;
    int cont =0 ;
    for (i=1;i<=x;i++){
        if (x % i == 0){
          cont +=1;
        }
    }
    if (cont == 2 || cont == 1){
      return 1;
    }else{
      return 0;
    }
}

But keep in mind that you can make other improvements to your code.

  1. You don’t need to check the division by 1 (every number is divisible by 1, so you don’t need to)
  2. You can compare the rest of the division x % i == 0 && x != i already gives you a number that is not cousin and you can return it.
  • 1

    Optimization by optimization you could iterate for absurdly fewer numbers

  • 1

    Yes. It can be optimized. I just didn’t want to modify his code

Browser other questions tagged

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