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();
            }
  • 相关阅读:
    FZU-2087 统计树边(最小生成树)
    HDU-1599 find the mincost route(floyd求最小环)
    BZOJ-1191 [HNOI2006]超级英雄Hero(二分图匹配)
    FZU-2020 组合(Lucas定理)
    FZU-2232 炉石传说(二分图匹配)
    NOIP2016模拟 拼接mf(模拟)
    2016年11月10日00:26:08
    BZOJ2986 Non-Squarefree Numbers
    BZOJ3624 [Apio2008]免费道路
    BZOJ3224 Tyvj 1728 普通平衡树
  • 原文地址:https://www.cnblogs.com/ericwen/p/primenumbe.html
Copyright © 2011-2022 走看看