Patrick’s development blog

checking prime numbers

Posted in Articles, C++ by Patrick on February 12, 2008

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.

Advertisements

2 Responses

Subscribe to comments with RSS.

  1. Jithin Joseph said, on July 2, 2008 at 2:34 am

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

  2. patrickbe said, on July 5, 2008 at 9:31 am

    Ah, of course, my bad. What I meant was that it finds all the primes in the range 0-50.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: