Close

Quick and Dirty Test for Primes

Again, just practicing; this time, on how to determine whether a given number is prime or not. This was actually the first C problem I ever encountered waaay back in the day; I remember failing. Miserably. Anyway, a refresher: in mathematics, a prime number (or a prime) is a natural number which has exactly two distinct natural number divisors: 1 and itself. Which means, naturally, that even numbers (except 2) are out, so I started there. Then I’d test the given number by dividing it by every odd number from 3 to the square of that number (because we don’t need the LARGEST factor; just A factor). After I did this exercise, I looked up other, more sophisticated methods (notably here); mental note to self: learn this.

#include <iostream>
#include <cmath>
using namespace std;

int main(void){
	int num = 0;
	bool isPrime = true;

	cout << "Enter a positive integer greater than 3: ";
	cin >> num;

	if( num % 2 == 0 ){
		// the number is even, so it can't be a prime
		cout << "\nThe number you gave: " << num << " can't be a prime; it's an even number." << endl;
		isPrime = false;
	}else{
		cout << "Checking..." << endl;
		int i = 3;
		do{
			cout << i << endl;
			if( num % i == 0 ){
				i = sqrt(num);
				isPrime = false;
			}
			i = i + 2;

		}while ( i <= sqrt(num) );
	}

	if( isPrime == true ){
		cout << num << " is a Prime number." << endl;
	}else{
		cout << num << " is not a Prime number." << endl;
	}
	return 0;
}
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Tumblr
  • Twitter

Related posts:

  1. More practice: sorting
  2. No Fun with Roman Numerals
  3. Questioning what it takes
  4. Finding Inspiration
  5. The Finale: No More Excuses

Or, you can just browse

This post has no comments yet. Be the first? →

Post a Comment

Your email is never shared. Required fields are marked *

*
*

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution.