C++判断一个数字是否为质数

关于素数的算法是程序竞赛比较重要的数论知识,我们来看通常会使用的几个算法。

我们先来复习几个基本概念:

质数:对于大于1的自然数,若除了1和它本身,没有别的因数,则称这个数为质数,质数也叫素数。反之,称其为合数。

 

 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 
 5 void IsPrime(int);
 6 int main()
 7 {
 8     int Input;
 9     cout << "请输入要判断的数字:";
10     cin >> Input;
11     IsPrime(Input);
12     cin.get();
13     cin.get();
14     return 0;
15 }
16 
17 //判断是否为质数
18 void IsPrime(int x)
19 {
20     if (1 == x)
21     {
22         cout << "1既不是质数也不是合数!" << endl;
23         return;
24     }
25     for (int i = 2; i <= sqrt(x); i++)
26         if (x%i == 0)
27         {
28             cout << "您所输入的数字为合数!" << endl;
29             return;
30         }
31     cout << "您所输入的数字为质数!" << endl;
32     return;
33 }

 

posted on 2017-05-10 15:34  Arthurian  阅读(7001)  评论(0编辑  收藏  举报