How to judge all typed numbers? Only the latter is being judged and displayed

Asked

Viewed 76 times

1

@Edit people cannot use vectors only for, while and while :x

I made this code but at the end when and to display the numbers I typed it’s only appearing the last number typed instead of all, what I should arrange ?

Question: A number is, by definition, prime if it has no divisors, except 1 and itself. Prepare a C program to read multiple numbers and determine if each of his is cousin or not.

#include <stdio.h>
#include <locale.h>

int main (){
int a, b, num, q, quantidade, primo;

setlocale(LC_ALL, "Portuguese");

printf ("Quantos número deseja ser informado: ");
scanf ("%d", &quantidade);

for (q=1; q<=quantidade; q++){
    printf ("Digite um número: ");
    scanf ("%d",&num);
}

for (a=1; a<=quantidade; a++){
    primo=0;
    for(b=1; b<=quantidade; b++)
        if((a % b) == 0)
            primo++;
    if (primo == 2) printf ("%d É PRIMO.\n", num);
    else printf ("%d NÃO É PRIMO.\n", num);
}
}
  • 1

    How they answered the ideal is to put the typed values in a list and then go through it. I made an example that you can check here https://repl.it/Mdxj/2

  • I forgot to mention but can’t use vector, just for, while and while :x

  • May I suggest a title edit? "How to judge all typed numbers? Only the latter is being tried and displayed"

  • 1

    @Jeffersonquesado ready :D

3 answers

1

The variable "num" must be a vector, try changing after the first SCANF to:

     int num[quantidade];

And restructure the code to do so.

1


If you can’t use vectors, which would be the best solution to the problem, you can pass the prime verification logic into the while who reads the numbers.

You can also make some adjustments to the cousin check loop itself, which make it simpler and more efficient:

printf ("Quantos número deseja ser informado: ");
scanf ("%d", &quantidade);

for (q=1; q<=quantidade; q++)
{
    printf ("Digite um número: ");
    scanf ("%d",&num);

    //a lógica de verificação do primo vem agora aqui, à medida que lê cada numero
    primo=0;

    //agora começa em 2 e termina em num-1, verificando menos 2 elementos sempre
    for (a=2; a<num; a++) 
    {
        if(num % a == 0){
            primo++; 
            break; //se deu para dividir por um já não precisa de ver mais
        }
    }

    //agora testa com 0 e não 2 devido ao ajuste do for
    if (primo == 0) printf ("%d É PRIMO.\n", num);
    else printf ("%d NÃO É PRIMO.\n", num);
}

See the example in Ideone

Function organisation

Even better would be to organize the logic of checking the cousin in a separate function:

int ePrimo(int n){
    int a;
    for (a=2; a<n; a++)
    {
        if(n % a == 0){
            return 0; //agora fica mais simples pois basta retornar
        }
    }

    return 1; //se chegou ao fim é primo
}

int main ()
{
    int num, q, quantidade;

    setlocale(LC_ALL, "Portuguese");

    printf ("Quantos número deseja ser informado: ");
    scanf ("%d", &quantidade);

    for (q=1; q<=quantidade; q++)
    {
        printf ("Digite um número: ");
        scanf ("%d",&num);

        //aqui agora apenas mostra o resultado da função ePrimo
        printf("%d %s.\n",num, ePrimo(num)? "É PRIMO": "NÃO É PRIMO");
    }

    return 0;
}

See this example also in Ideone

Efficiency improvements in Primo verification

As @Jeffersonquesado indicated in the comments, there is still room to improve the part of the cousin search with some specific changes:

  • Search only while the current number is less or equal than the square root of the limit, because from there we have assurance that there will be no divisible.
  • If the number is not even and therefore not divisible by 2, it is also not divisible by any other pair.

Considering these improvements the verification function would look like this:

int ePrimo(int n)
{
    if (n % 2 == 0) return 0; //se for pair sai logo como não primo

    int a, limite = sqrt(n); //calcula o limite com a raiz quadrada do numero

    for (a=3; a<=limite; a+=2) //agora anda de 2 em 2 excluindo todos os pares
    {
        if(n % a == 0)
        {
            return 0; //agora fica mais simples pois basta retornar
        }
    }

    return 1; //se chegou ao fim é primo
}
  • It was very good explained, Rigadão clarified a lot :D

  • You could let the search for the fastest cousin get by for (a = 2; a*a <= n; a++) in place of the current iteration. It is also possible to halve the search space if you take into account that if it is even, it is divisible by 2, not needing to check any other even number

  • 1

    @Jeffersonquesado Correct! Thanks for the comment. I will add these tips to make the answer more complete

0

Direct answer: You have to check if the number is prime before updating the variable num. ... When your first for is executed, it keeps reading numbers and saving in the variable num. However, when reading the value, nothing happens. When your for comes at the end, your variable num gets the last entered value.

Browser other questions tagged

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