## checking prime numbers

It’s amazing how many functions i’ve found on the internet during the time I was writing a prime checker function and **none** of these functions worked, which was very surprising. I learned a few things at least. When checking if a number is a prime, you only have to check if the number is **divisible by any value until its square root**. An exception is number 2 which is a prime number.

The first twenty primes are 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71

And as you probably know, a prime number is always positive (>1) and only divisible by 1 and itself. The following c++ program types the first 50 prime numbers.

**IsPrime.cpp**

`#include <iostream>`

#include <cmath>

`bool isPrime(int n) {`

if (n<=1) return false;

if (n==2) return true;

`for (int i=2;i<sqrt(static_cast<double>(n))+1;i++) {`

if (n%i==0) return false;

}

return true;

}

`int main() {`

for (int i=0;i<50;i++) {

if (isPrime(i)) std::cout << i << " ";

}

`std::cin.get();`

return 0;

}

This function was made rather quickly, but i’m pretty sure it works since the 50 first prime numbers were correct.

Jithin Josephsaid, on July 2, 2008 at 2:34 amHey,

Your program “IsPrime.cpp” doesn’t find first 50 prime! Instead it finds primes between 0 and 50.

patrickbesaid, on July 5, 2008 at 9:31 amAh, of course, my bad. What I meant was that it finds all the primes in the range 0-50.