• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C语言求1000以内的所有素数

OC/C/C++ 水墨上仙 2144次浏览

C语言求1000以内的所有素数
老外的代码,写的还是很严谨的。

/*
  This is a simple program which calculates all prime numbers up to
  1000.  This is not the most efficient algorithm, but it is easy
  to follow.  I'll post some more efficient algorithms soon that
  avoid redundancy, but the goal of this code snippet is a semi-brute
  force method that is easy to understand.
  
  The general approach is to declare everything prime, then start crossing
  off multiples of prime numbers from the prime number list.
  
  I do make use of two facts to make the program not completely brute-force.
  
  One, the outer loop only goes up to the square root of N.  Any non-prime
  number will have a factor less than or equal to its square root.
  
  Two, any multiple of a non-prime number is also a multiple of a smaller
  prime number, so any multiple of a non-prime number has already been
  flagged as non-prime.  Thus there is no need to flag multiples of numbers
  that are non-prime, so the inner for-loop can be short-circuited.
  
  There are some other mathematical rules that can improve efficiency of the
  inner and outer for-loops, but I'll stick with just these two for now for
  easier understanding.
*/
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
    const int N = 1000;
    const int SQR_ROOT_N = (int) (sqrt ((double) N));
    bool prime[N + 1];
    
    prime[0] = false;  // 0 is not prime
    prime[1] = false;  // 1 is not prime
    
    for (int i = 2; i <= N; i++)
         prime[i] = true;  // flag all numbers as prime initially
         
    for (int i = 2; i <= SQR_ROOT_N; i++)
    {
        if (prime[i]) // no need for inner loop if i is not prime
        {
            for (int j = 2 * i; j <= N; j+=i)
                 prime[j] = false;  // j is a multiple of i, thus not prime.
        }
    }
    
    // display prime numbers
    cout << "Here are the prime numbers\n\n";
    for (int i = 2; i <= N; i++)
    {
        if (prime[i])
            cout << i << endl;
    }
    
    return 0;
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C语言求1000以内的所有素数
喜欢 (0)
加载中……