Resolve logic error

3

I am doing some college exercises, however I am 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?

    
asked by anonymous 12.02.2015 / 16:44

3 answers

7

I found 2 errors in your code:

1- The cont counter must be reset at 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 that cont equals 2 and assumes that number is prime. But if he finds another perfect split later, cont will become 3, 4, 5 ... and that number will not 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;
    
12.02.2015 / 17:09
4

You can do more efficiently:

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

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

int main() {
    int num, i, j, aux, cont;
    aux = 0;
    printf("digite um nume:\n");
    scanf("%i", &num);

    for (i = num; i >= 2; --i) {
        cont = 0;
        for (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);
    return 0;
}

See running on ideone .

It's best to start from a higher number, so find a cousin more quickly. 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.

    
12.02.2015 / 17:10
0

I did it in a simpler way:

/ user enters a number, the program should print the largest number between 1 and the number entered /

int main () {
int i, num;

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

// Since it is the first largest cousin between 0 and num, it is more logical to start from num;

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

printf ("The largest prime number between 0 and% d will be% d", num, i); } }

return 0;

}

    
03.03.2016 / 15:32