zoukankan      html  css  js  c++  java
  • 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 }

    作者:耑新新,发布于  博客园

    转载请注明出处,欢迎邮件交流:zhuanxinxin@aliyun.com

  • 相关阅读:
    2020年3月22日
    2021年3月21日
    2021年3月20日
    人件集阅读笔记02
    2021年3月19日
    2021年3月18日
    2021年3月17日
    2021年3月16日
    2021年3月15日
    梦断代码阅读笔记01
  • 原文地址:https://www.cnblogs.com/Arthurian/p/6833321.html
Copyright © 2011-2022 走看看