How do you tell if a number is prime

  • 2020-06-03 07:44:57
  • OfStack

Algorithms about prime Numbers are important number theory knowledge in program competition. Let's look at some algorithms that are commonly used.

Let's review a few basic concepts:

Prime: a natural number greater than 1, if it has no other factors than 1 and itself, is called prime. Prime Numbers are also called prime Numbers. On the contrary, it is called composite.


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

void IsPrime(int);
int main()
{
  int Input;
  cout << " Please enter the number to determine: ";
  cin >> Input;
  IsPrime(Input);
  cin.get();
  cin.get();
  return 0;
}

// Determine if it is prime 
void IsPrime(int x)
{
  if (1 == x)
  {
    cout << "1 Neither prime nor composite! " << endl;
    return;
  }
  for (int i = 2; i <= sqrt(x); i++)
    if (x%i == 0)
    {
      cout << " The number you entered is composite! " << endl;
      return;
    }
  cout << " The number you entered is prime! " << endl;
  return;
}

Related articles: