I'll probably get flamed for all the color, but oh well...
Code:
#include <iostream>
#include <math.h> //post #9 explains how to fix this
//using namespace std; //post #9 explains about this
int main()
{
// Declare four variables n, i, an, and is_prime respectively.
//Preferably use descriptive names, i.e. numberToTest instead of n
int n; // Number to test for primeness
int i; // Loop counter
//The code will be easier to follow if you declare this near to
//where you use it, particularly since it is used only once.
// double an; // Optimization
bool is_prime; //post #9 explains about this
// Assuming that the number is prime until proven otherwise
is_prime = true;
// Prompt user input
// note use of std:: instead of "using namespace std;"
std::cout << "Please enter a number for the primeness number test: ";
std::cin >> n;
// Test for prime-ness by checking for divisibility
// by all whole numbers from 2 to sqrt(n)
i = 2;
//You seem to have missed the point of the new variable
// as you are not using it to do anything useful
// an = n;
//The point was, although you may need to USE the square
//root of n many times in the while loop, you only need to
// CALCULATE it once for each n. Making unnecessary calls to
//the sqrt function wastes processing time. Therefore,
//declare a new variable before the while loop, store the
//square root of n in it, and use that new variable in the while
//loop's test expression.
double rootN = sqrt(static_cast<double>(n));
// while(i <= sqrt(static_cast<double>(n))){
//In the while loop, you are searching for a number that divides
//n evenly. If you find one, then n is not prime & you set
//is_prime to false. If you get all the way to rootN without
//finding a number that divides n evenly, then n must be prime.
while(i <= rootN){
if(n % i == 0){
is_prime = false;
//The code in here (in the if{} block) is executed only when
//the test expression (n % i == 0) is true. So, if you increment i
//here, and if 2 doesn't evenly integer-divide the n that you input,
//the value of i will never change and the while loop
//continues to test the same n forever.
// i++;
//If you find an i that evenly divides n, then n is not prime and
//any more testing is a waste of time. break gets out of the while loop
//avoiding unnecessary iterations.
break;
}
++i; // post #9 talks about this
}
if(is_prime){
std::cout << "The number is prime." << std::endl;
}else{
std::cout << "The number is not prime." << std::endl;
}
return 0;
}