how do i determine if a number is prime or not in C++?

how do i determine if a number is prime or not in C++?

There's no standard C++ function to my knowledge to test whether a number is prime or not. There may be one in an optional library such as the boost libraries. There are lots and lots of related threads on Daniweb, other forums, and google. Just type in "C++ prime numbers" or a slight variety of that in Daniweb's search box and a whole bunch of threads will come up. It's a very common programming assignment.

Try this.

template<class type> inline
bool IsPrime(type val) {
	if (val==2)return 1;
	else if (val == 1) return 0;
	else if (val%2==0) return 0;
	register bool prime = 1;
	for (register type i = 3; i < val/2;i+=2) {
		if (!(val%i)) {
			prime = 0;
			break;
		}
	}
	return prime;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.