使用嵌入循环查找1-239之间的素数
Finding a prime numbers between 1 - 239 using embedded loop
我不知道如何使用嵌入式循环找到1到239之间的所有素数。这是我到目前为止的代码,我知道我走在正确的轨道上,但我不知道从这里到哪里,因为这没有返回正确的输出
#include <iostream>
using namespace std;
int main()
{
int n, x, y, is_prime;
n = 0;
while (n < 239)
{
n++;
is_prime=1;
x=2;
while (x < n)
{
y = n % x;
if (y == 0)
{is_prime = 0;
x = n;}
else x++;
}
if (is_prime = 1)
cout << n;
cout << endl;
}
system("pause");
return 0;
}
你很接近。这里有一些工作代码,但如果这是一项任务,试着自己解决,如果你陷入困境,就看看答案。
#include <iostream>
using namespace std;
bool isPrime(int n){
//first check if n equals 2 or n is divisible by 2
if (n == 2) return 1;
if (n%2 == 0) return 0;
//start at 3, only check the odds, and stop at square root of n
for (int i = 3; i * i <= n; i+=2){
if (n%i == 0)
return 0;
}
return 1;
}
int main()
{
//2 is the only even prime number
cout << 2 << " ";
//now the rest are odds
for (int i = 3; i <= 239; i+=2){
if (isPrime(i)){
//print i if it is a prime number
cout << i << " ";
}
}
cout << endl;
}
输出:
2 3 5 7 11 13 17 19 23 31 37 41 47 53 59 61 67 71 73 83 89 97101 103 107 109 113 127 131 137 139 149 151 157 163 173 179 181191 193 197 199 211 223 227 229 233 239
超简化:
#include <iostream>
using namespace std;
int main()
{
cout << 2 << " ";
int prime = 1;
for (int i = 3; i <= 239; i+=2){
for (int j = 3; j * j <= i; j+=2){
if (i%j == 0){
prime = 0;
break;
}
}
if (prime == 1){
cout << i << " ";
}
prime = 1;
}
cout << endl;
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 使用嵌入循环查找1-239之间的素数
- 基本的依偎循环计算1 - 239之间的质数,包括