无涯教程-进程 - Prime number函数

25 阅读1分钟

质数是大于1并除以1或本身的数字。换句话说,质数不能除以自身或1以外的其他数字。例如,2、3、5、7、11、13、17、19、23 ....是质数。

让我们看一下C ++中的素数程序。在此C ++程序中,我们将接受用户的输入,并检查数字是否为质数。

#include <iostream>
using namespace std;
int main()
{
  int n, i, m=0, flag=0;
  cout << "Enter the Number to check Prime: ";
  cin >> n;
  m=n/2;
  for(i = 2; i <= m; i++)
  {
      if(n % i == 0)
      {
          cout<<"Number is not Prime."<<endl;
          flag=1;
          break;
      }
  }
  if (flag==0)
      cout << "Number is Prime."<<endl;
  return 0;
}

输出:

Enter the Number to check Prime: 17  
 Number is Prime.   
Enter the Number to check Prime: 57  
Number is not Prime.

参考链接

www.learnfk.com/c++/prime-n…