Solve logic error

Asked

Viewed 269 times

4

I’m doing some college exercises, but I’m having a logic error in this exercise:

#include <stdio.h>
#include <stdlib.h>

/*usuario entra com um numero, o programa devera imprimir o maior numero primo entre 1 e o numero digitado*/

int main()
{
    int aux, num, i, j, cont=0, rest=0;

    printf("digite um nume:\n");
    scanf("%i", &num);

    for(i=1;i<=num;i++)
    {
        for(j=1; j<=i; j++)
        {
          rest=i%j;

          if(rest==0)
                cont++;

          if(cont==2)
            aux=i;
        }
    }

    printf("O maior numero primo entre 0 e %d sera %d", num, aux);

    return 0;
}

How to solve the problem?

3 answers

7


I found 2 errors in your code:

1- The meter cont has to be reset every iteration of the first for:

for(i=1;i<=num;i++)
{
    cont = 0;
    for (j=1; j<=i; j++)

2- In the second for, you check whether cont is equal to 2 and assumes that number is prime. But if he finds another perfect division then, cont will turn into 3, 4, 5... and that number won’t be prime. So, you have to check if cont is equal to 2 at the end of for, after passing all the numbers:

if(cont==2 && j == i)
    aux=j;
  • Thank you Lucas, it worked, corrected, I understood my mistake and the solution.

5

You can do it more efficiently:

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

int main() {
    int num, aux, cont;
    aux = 0;
    printf("digite um nume:\n");
    scanf("%i", &num);
    for (int i = num; i >= 2; --i) {
        cont = 0;
        for (int j = 2; j < sqrt(i) + 1; ++j) {
            if (i % j == 0) {
                cont++;
                break;
            }
        }
        if (cont == 0) {
            aux = i;
            break;
        }
    }
    printf("O maior numero primo entre 0 e %d sera %d", num, aux);
}

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

It’s best to start from a higher number, so find a cousin faster. Starting at 1 you have to go through all the cousins until you figure out which one is the biggest. This way the first cousin you find is already the expected result.

  • bigown thanks for showing in this way, I tested and liked it quite tested and I will present to my teacher to take a look.

  • Wouldn’t it be more efficient to do j*j <= i than to calculate the square root?

  • @Jeffersonquesado is likely.

0

I did it in a simpler way:

Isuário enters with a number, the program must print the largest prime number between 1 and the number typed

int main() {  
int i, num;

    printf("digite um nume:\n");  
    scanf("%i", &num);  

//já que é o primeiro primo maior entre 0 e num, é mais lógico começar de num;  

    for(i=num;i>2;i--) {  

if ((i%2!=0) & (i%3!=0) && (i%5!=0)) {

   printf("O maior numero primo entre 0 e %d sera %d", num, i);
}
}

    return 0;
}

Browser other questions tagged

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