zoukankan      html  css  js  c++  java
  • 算法获取质数(素数)数组

    写一个方法得到一个素数数组,这些素数不能大于给定的自然数。

    我看网上大多数的实现都是用自然数n除以2到n/2+1的数,如果整除了,就判定不是素数。

    我的想法不一样,我一个数组保存已经得到的素数,然后用n除以这些素数,如果整除了,就判定不是素数。

    具体实现如下:

            static int[] GetPrimeNumbers(int boundary)
            {
                List<int> primeList = new List<int>();
                int n = 2;
                while (n <= boundary)
                {
                    bool isPrime = true;
                    for (int i = 0; i < primeList.Count; i++)
                    {
                        if (n % primeList[i] == 0)
                        {
                            isPrime = false;
                            break;
                        }
                    }

                    if (isPrime)
                    {
                        primeList.Add(n);
                    }

                    if (n < 3)
                    {
                        n++;
                    }
                    else
                    {
                        n += 2;
                    }
                }

                return primeList.ToArray();
            }
  • 相关阅读:
    事件总线2
    微信小程序视频录制教程
    vue插件开发-toast
    云计算中的测试,可从哪些维度入手
    ES配置及FAQ
    Azkaban安装及问题
    python 反编译 compileall
    平凡利用redis进行数据读写的一种优化
    彻底弄懂Redis的内存淘汰策略
    c# 判断年龄精确到日
  • 原文地址:https://www.cnblogs.com/ericwen/p/primenumbe.html
Copyright © 2011-2022 走看看