Prime Number Algorithm

I have been given a task to create a program that asks a user to enter a prime number.

First the number itself is check to see if it is prime or not.
-The way I wanted to do this is divide the number by itself, then decrement it by 1 in a loop, dividing it by that number. Set the remainder equal to some variable, and if the remainder is equal to zero, increment a counter. If the counter is equal to 2 at the end, then that number is infact a prime number.

Second every other number below it has to be check if it is prime or not.
-The way I wanted to do this is just have a for loop decrementing the number that was input and have that first "for" loop inside it.

I am using Linux thru a vmware machine. using emacs c++
this is my code so far, can anyone assist me?

Thanks

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
int number = 0;
int remainder = 0;
int testnumber = 0;
int x = 0;

for(number; number >=1; number--)
{
for (testnumber = number; testnumber >=1; testnumber--)
{
remainder = (number%testnumber);
if (remainder == 0)
{
x++
}
if (x == 2)
{
cout << number << endl;
}
}
}
}





Well, you don't need to check every number, only numbers either above or below the square root of the prime number, and since theres less numbers below, check that. Also, the quickest way is to check all the prime numbers below the square root of the prime number, but its probably quicker to check each number rather than find more primes...

Also, you should stop as soon as you find a number that (prime % n == 0), because that means it is not a prime and you dont have to check any more. (Unless n is the original number or 1, but you shouldnt check those because its useless since you will always get 0)
Topic archived. No new replies allowed.