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

generic stringstream function in c++

Posted in C++ by Patrick on February 9, 2008

Something i’ve found useful while programming in C++, is the use of std::stringstream to convert different datatypes to std::string. Fortunately, the process is the same for all types. That’s why a generic helper-function is preferable and will simplify the process considerably.

In order to use stringstreams, the library <sstream> has to be included. The following will create a reusable stringstream helper-function using templates.

template <typename T> std::string to_string(const T& value) {
std::stringstream os;
os << value;
return os.str();
}

The parameter contains the value that will be converted into a string, so you only have to assign a string to the function.

// assign a new string to the return value of to_string and show the contents
std::string str = to_string(5.12);
std::cout << str;