• 算法获取质数(素数)数组


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

    我看网上大多数的实现都是用自然数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();
            }
  • 相关阅读:
    python获取当前路径
    python的StringIO
    python判断两个文件是否相同
    Linux查找文件内容
    python日志syslog运用
    python获取当前运行程序的名字
    python连接Linux命令行
    python预编译函数compile,exec,eval
    python日志模块
    Scala安装教程
  • 原文地址:https://www.cnblogs.com/ericwen/p/primenumbe.html
Copyright © 2020-2023  润新知