Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

This resource has not currently been approved, and is not currently linked to from our directory of resources. It is being displayed here for preview by the author and moderators only.
Rated
Read 490 times

Related Categories

[C++] Prime Number Test - Descriptions & Code

Descriptions & Code

===========<    Descriptions    >==============

-> VSC++ 2005 - Win32 Console App
-> Test to see is a number prime ?
It uses a simple mathematical algorithm :
"a non-prime number has at least a prime denominator, that is less than or equal to the square root of the number", and as an enhance : all even numbers except 2, aren't prime.

===========<    Code    >==============

#include <cmath> // sqrt()
#include <iostream> // system()
using namespace std;

int main()
{
      int n; // n is prime ?
      bool prime =true; // yes, is prime!
 
      cout << "\n Enter a number : ";
      cin >> n;
 
      if ( (n%2 == 0 && n!=2) || (n == 1) ) // dividable by 2 (but not 2) or it's 1 ?
            prime = false;
 
      for (int i=3; i <= sqrt((double)n) && prime; i+=2)
            if ( n%i == 0 )
                  prime = false;
 
 
      if ( prime )
            cout << "\n Number is prime." << endl;
      else
            cout << "\n Number isn't prime." << endl;
 
      system("pause");
      return 0;
}

Comments