prime numbers program

I am having trouble making a prime numbers program so I wondered if anyone here could help...

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
int entered, i, n; //All variables declared at the top, makes it easier
bool isprime;
cout << "Enter number to calculate primes: ";
cin >> entered;
cout << "2 ";
for(i = 3; i <= entered; i++)
isprime = true;
{
if(entered % i == 0)
{
isprime = true;
}
if(isprime = false);
}
cout << i;
cout << endl;
system("pause");
}
Where exactly is the problem?
1. I think you should start with i = 2, because for a prime number, number % 2 should equal 0 too.
2. I'm not sure what you're trying to do, but from I read this from the code:
- Set the variable isprime to true for x times, where x is the number you entered (entered) minus 3 (because you're starting at 3).
- If entered modulo i equals zero then:
- Set isprime to true
- If isprime equals to false
- Do nothing

BTW, entered modulo I is always entered, so it would ever equal to zero. Why? Because once your for loop finishes because it is not lower than entered or equal to entered anymore, i will be one higher than entered.
If you explain what you are trying to do, I could help you.
im trying to list all primes between 2 and the entered number
including 2 and the entered number?
if the entered number is prime then yes
anyway, assuming so, you can use a loop from 2 to the entered number:
1
2
3
4
5
6
7
for (int i = 2; i <= entered; i++)
{
    //Let's say we have a function ( bool isPrime(int) ) that detects if it is a prime number:

    if ( isPrime(i) )
        cout << i << " is a prime number.\n";
}
if you would like to know how to implement such a function, I can give an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool isPrime(int number)
{
    //Loop through all numbers from 2 to number and check if number is divisable by it:
    for (int i = 2; i < number; i++)
    {
        //If it is devisable, then remember and stop looking for divisors
        if (number % i == 0)
        {
            //It is devisable, so stop looking and say it is not a prime:
            return false;
        }
    }

    //If you get here, no divisors where found because the function would have been stopped by then and returned false. That;s why you can return true now, it is a prime:
    return true;
}
ok il try that later i dont have time at the moment
Topic archived. No new replies allowed.