Testing primes in C

Asked

Viewed 1,118 times

7

I am trying to develop in C a program in which the user puts a sequence of numbers and the same should determine whether the numbers are primes or not.

Just follow my code:

#include <stdio.h>

int main() {


    int num1, num2, i;
    char op;

    do {

      printf("\nInforme um numero: ");
      scanf("%i", &num1);

      printf("\nInforme um numero: ");
      scanf("%i", &num2);

        for (i=num1; i<=num2; i++) {

            if (i % 1 == 0 && i % i == 0) {

                printf("\n%i - Primos!", i);

            } else {

                printf("\n%i - Nao primos!", i);

            }
        }

     printf("\nDeseja calcular outra sequencia de numeros? ");
     scanf("%s", &op);

    } while (op == 's' || op == 'S');

    return(0);
}

Where am I wrong? I put a sequence of 1 through 10 and the result are all primes.

  • Could you explain your question better Marcielli? I don’t understand the part you say you have to read a sequence of numbers!!

  • 3

    I’m sorry, but if this is your course material, you shouldn’t come and get someone on the site to sort it out for you. Surely the answer is in the book used in the course or even with some colleague you can study with. The mistake is very clear to those who have been through it but insisting until finding the mistake is part of learning.

  • Yes. It is so... I have to ask for 2 numbers for the user. Between the first and the second I must take the test. Example: He can ask from 5 to 30, so from 5 to 30 I have to test and tell those who are cousins and those who are not.

  • 2

    Oh yes, it is my first time on this site... I do not look for ready answers no, just tips of what might be wrong. Maybe I expressed myself wrong in the question. I’m here to learn, but I really don’t understand why it’s not working. But ok, if this kind of question cannot be asked here I understand! Thank you anyway. ;)

  • Better analyze the conditions of your repeat cycle for! Think mathematically and sketch a paper into a mathematical sketch!! From what I understand you must indicate which are the prime numbers between the first number read and the second right?

  • Ah, ok. I’ll do it here... Maybe if I do it on paper I’ll get a better view of the problem right? Yes, that’s right! Thank you -

Show 1 more comment

2 answers

6


The problem is that this code is not testing whether the numbers are primes. The expression i % i == 0 gives a good indication that there is something missing there. This expression will always be true, after all the rest of a number divided by it is always zero. And the expression i % 1 == 0 is always true. Every number divided by 1 has 0 rest. So it is unnecessary.

The main change I made was to create an internal loop that tries to make all possible divisions between 2 and the number before what is being tested. If a single division has zero rest, it does not need to keep comparing. If it stops at the same number being tested means that no division gave 0 rest, then it is prime.

#include <stdio.h>

int main() {
    int num1, num2, i, j;
    char op;
    do {
        printf("\nInforme um numero: ");
        scanf("%i", &num1);
        printf("\nInforme um numero: ");
        scanf("%i", &num2);
        for (i = num1; i <= num2; i++) {
            for (j = 2; j < i; j++) if (i % j == 0) break;
            if (i == j) printf("\n%i - Primos!", i);
            else printf("\n%i - Nao primos!", i);
        }
        printf("\nDeseja calcular outra sequencia de numeros? ");
        scanf("%s", &op);
    } while (op == 's' || op == 'S');
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You can optimize this, but as you are learning so it is good, better not complicate.

  • Oh yes, one is inside another... I’ll take line by line and understand now how it does. Thank you very much! ;)

2

Recently I had done an exercise of this (except that in addition to talking about whether you are cousin or not I had to display the sum of pairs, odd and cousins) , I also do ADS rs, well, I edited mine to serve you, I think it became simpler to understand and was like this:

#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
main(void) // void, para não precisar do return 0;
{
    setlocale(LC_ALL,""); // permite colocar acentos
    int num1, num2, num, cont, isPrimo;
    char op;
    do
    {
        isPrimo = 0; // é um bool binário, onde 0 não é primo e um é primo
        printf("Número Inicial: ");
        scanf("%i", &num1);
        printf("Número Final: ");
        scanf("%i", &num2);

        for(num = num1; num < num2; num ++)
        { //vai do num1 ao num2 e armazena o valor atual da sequência em num
            for(cont = 1; cont < num; cont ++)
                if(num % cont == 0) /*compara se num é divisivel pela sequencia de 1 até ele mesmo
                                      e atribui isso ao bool, para verificarmos depois*/
                    isPrimo += 1; /* aumenta o valor, se ele for primo será 1, pois número primo é 
                                    divísel por um e por ele mesmo, porém comecei o cont com 1, então se o 
                                    número for primo ele entrará no if apenas uma vez, deixando isPrimo = 1, formando um bool*/
            if(isPrimo == 1) // comparo se o bool é verdadeiro (1) e imprimo que é primo
                printf("%3i é primo.\n", num);
            else // se nao ele não é primo
                printf("%3i não é primo.\n", num);
            isPrimo = 0; //redefino o bool
        }
        printf("\nDeseja calcular outra sequencia de numeros? ");
        scanf("%s", &op);
        system("cls");
    }while(op == 's' || op == 'S');
    system("pause");

}

I hope it has become simpler to understand rsr, nor was going to answer the question because it has been here for a long time and already has answer, but they are different logics and maybe you understand this better.

  • 1

    Ah, that’s nice. Thank you. I’ll take a look at the way you did too. ;)

Browser other questions tagged

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