Program to list prime numbers less than or equal to the input value

Asked

Viewed 76 times

-3

Good morning, I want to print a set to which I must print only the primes smaller or equal to the input value, but I cannot succeed, because it always returns the value n and n-1, with the exception of the number 1 (which is not prime). I wonder what’s left for this code to recognize the while and print only the prime numbers.

#include<stdio.h>
int main(){
    int n,res,i,j;
    printf("insira o seu numero aqui\n") 
    scanf("%d",&n);
    printf("Voce inseriu este numero: %d \n",n);
        for (i=n;i>=0;i--){
        res=1;
        j=2;
                    if (i<=1){
                    res=0;
                    while (res==1 && j<=i/2)
                        if (i&j==0)
                        res=0;
                    j++;
                }
                if(res==1)
                printf("%d ",i);
 }
    return 0;
}
  • I don’t see the point in this test: if (i<=1){. Here: while (res==1 && j<=i/2) if (i&j==0) res=0; can enter infinite loop. The algorithm used does not check whether the number is prime.

  • But he didn’t go in, and he didn’t even show up on the print. When I did this algorithm just getting the value by the user to know if it is prime or not it worked. When I tried to add a for and while getting the n-1 of for it n worked. I’m pretty beginner in C. Soon gets this confused.

  • I was in the logic at: I give the value To each number made the test if it is prime. Who eh cousin he is printed As soon as the test is done he goes down to zero repeats.

  • Here: if (i&j==0) i don’t know what the result expects to get from this Bitwise AND.

1 answer

-1


See if this is what you want:

#include<stdio.h>
int main() {
    int n, res, i, j;
    printf("Insira o seu numero aqui: ");
    scanf("%d", &n);
    printf("Voce inseriu este numero: %d \n",n);
    for (i=n; i>1; i--) {
        int j=2;
        while ((j <= i/2) && (i%j != 0))
            j++;
        if (j>i/2)
            printf("%d ",i);
    }
    return 0;
}
  • Unfortunately not. It doesn’t even list the numbers, just print the n at the beginning of the algorithm. But thanks for the help.

  • Corrected, I was using n in place of i in the verification of primality.

  • Very grateful! Solved my doubt :)

Browser other questions tagged

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