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;
}
Related posts:







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