Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Finding all prime numbers equal to or less than user inputted number?

$
0
0
Hi, everyone, this is probably pretty easy but I'm having trouble. I'm new to C language, and programming in general. I'm having issues with this problem. My problem is to do as follows:

Write a program which reads an integer from standard input.
It should then output all the prime numbers less than or equal to that number.

So, to determine if x is prime, try finding x % y for every number between 1 and y.
If they are all nonzero, then x is prime.
If at least one is zero, then x is not prime.

You can use two nested loops - the outer loops over all numbers we are testing for primality,
the inner loops over the numbers which may potentially be a factor of the number we are testing.

Here is my code:

#include<stdio.h>

main()
{
    int n;
    int x = n-1;

    printf("Enter a positive whole number to see all numbers equal or less than that number which are prime.\n");
    scanf ("%d",&n);

    for (n >2; n--)
    {
            for (x > 2; x-- )
            {
                if (n%x==0)
                {
                    break;}
                }


    }
        if (n%x != 0)
            {printf ("%d", n);}


}



I'm doing this in the IDE Code Blocks. This is probably my 10th different draft and this one just crashes the program once I enter a number (others had numbers repeated over and over, or other problems).

I'm trying to think about it logically and entering numbers into my code and I can see my code is wrong. For example, if n = 20, then the first number that it is divided by will be x, which is n-1, or 19. 20/19 gives a remainder of 1. Since that does not equal zero, it will go to the loop that says to print it as a prime number, which is wrong because it needs to go from 19 down to 10 for the remainder to be zero, and thus prime. I want it to go down from 19 and do nothing until it hits 10 and then prints out the number, then start over with the n-- to make the loops test 18, but I don't know how to structure it to do that. Any advice would be much appreciated.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>