• 筛法--求1到100的所有素数


    用筛法求出100以内的全部素数,并按每行五个数显示

    我们知道一个合数可以分解了几个质数想乘,从2开始知道根号下n每次判断一个数是否为素数,如果为素数,就把所有能被这个数整除的数排除,即不是素数。

    首先是一个判断素数的函数

     1 bool sushu(int x)
     2 {
     3     if (x==2)
     4     return true;
     5     for (int i = 2;i <= sqrt(x);i++)
     6     {
     7         if (x%i==0)
     8             return false;
     9     }
    10     return true;
    11 }

     

    把能被素数整除得数排除

     1     for (int i = 2;i <= sqrt(n);i++)
     2     {
     3         if (sushu(i))
     4         {
     5             for (int j= 2;j <= n/i;j++)
     6             {
     7                 a[i*j]=false;
     8             }
     9         }
    10     }

     

    完整代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <math.h>
     5 #include <algorithm>
     6 #include <iomanip>
     7 using namespace std;
     8 bool sushu(int x)
     9 {
    10     if (x==2)
    11     return true;
    12     for (int i = 2;i <= sqrt(x);i++)
    13     {
    14         if (x%i==0)
    15             return false;
    16     }
    17     return true;
    18 }
    19 int main()
    20 {
    21     int const n = 100;
    22     bool a[10000];
    23     memset(a,true,sizeof(a));
    24     a[1]=false;
    25     for (int i = 2;i <= sqrt(n);i++)
    26     {
    27         if (sushu(i))
    28         {
    29             for (int j= 2;j <= n/i;j++)
    30             {
    31                 a[i*j]=false;
    32             }
    33         }
    34     }
    35     int ans=0;
    36     for(int i = 1;i <= n;i++)
    37     {
    38         if (a[i]){
    39             printf ("%-5d",i);
    40             ans++;
    41         }
    42         if (ans==5)
    43         {
    44             ans=0;
    45             cout<<endl;
    46         }
    47     }
    48     return 0;
    49 }

     

  • 相关阅读:
    字典的key都可以是什么
    groupby 的妙用(注意size和count)

    希尔排序
    TCP和UDP
    闭包(python)
    快速排序
    mysql t4模板_Model
    vue前端性能优化
    系统稳定性问题总结
  • 原文地址:https://www.cnblogs.com/very-beginning/p/11991614.html
Copyright © 2020-2023  润新知