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

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

1144次浏览 手机上查看

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 = false;  // 0 is not prime
prime = 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;
}
```

[开心洋葱]  • 版权声明

本站的文章和资源来自互联网或者站长的原创，按照 CC BY -NC -SA 3.0 CN协议发布和共享，转载或引用本站文章应遵循相同协议。如果有侵犯版权的资源请尽快联系站长，我们会在24h内删除有争议的资源。
• 合作网站

• 友情链接

• 关于我们

一群热爱思考，热爱生活，有理想的新社会主义接班人的多维思维学习平台，天行健，君子以自强不息。地势坤，君子以厚德载物。
……