我正在完成编写程序以确定哪些数字是素数的经典 C++ 练习之一。我现在正在处理的版本要求我能够确定哪些值与用户输入的名为max.
我试图构建的算法的行为如下:
1) 输入所需的max值。
2)拿这个max然后把它放到一个函数中来计算sqrt(max)。
3) 使用sqrt(max)I 将构造一个质数向量,其值不超过sqrt(max)
4)使用这个向量,然后我将通过创建一个特定的函数来sqrt(max)评估哪些值是该值的素数,以确定列表中的哪些值是素数。然后我将生成所有这些素数的列表。maxmax
有了这个结构,这里就是我的代码:
#include "pch.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::string;
using std::vector;
int determine_prime(int x) {
// function made to determine if a number is prime
// used the fact that to determine if number is prime only need to check if
// prime values less than sqrt(x) divide x
vector<int> vector_of_sqrt_primes = list_of_prime_sqrt();
vp_1 = x % vp_1 = x % vector_of_sqrt_primes[i];
for (int i = 0; i < vector_of_sqrt_primes.size(); i = i + 1) {
if (vp_1 == 0 &&
x != vector_of_sqrt_primes[i]) { // verifying if value is prime
cout << x << " is not a prime number. \n";
return 0;
}
else {
cout << x << " is a prime number. \n";
return 1;
}
}
}
int list_of_prime_sqrt(int y) {
// using this vector as reference for all values less than the sqrt of max
vector<int> vector_of_primes_sqrt = {2};
int vps = 0;
for (int i = 2; i < round(sqrt(y)); i = i + 1) {
for (int j = 0; j < vector_of_primes_sqrt.size(); j = j + 1) {
vps = i % vector_of_primes_sqrt[j];
if (vps == 0 && i != vector_of_primes_sqrt[j]) {
cout << i << " is not a prime number. \n";
} else {
cout << i << " is a prime number. \n";
vector_of_primes_sqrt.push_back(i);
}
}
}
}
int main() {
int max = 0;
vector<int> primes_list = {};
cout << "Please enter the number of integers you would like to inspect "
"whether they are prime.\n";
cin >> max;
list_of_prime_sqrt(max);
for (int i = 1; i < max + 1; i = i + 1) {
int p = determine_prime(i);
if (p == 1) {
primes_list.push_back(i);
}
}
for (int j = 0; j < primes_list.size(); j = j + 1) {
cout << primes_list[j] << "\n";
}
}
所以我希望我能够vector_of_sqrt_primes在determine_prime()函数中使用,然后计算出哪些值是素数,然后将它们返回给我的main(). 但我正在撞墙。所以所有这一切都是为了问我是否有办法做到这一点?我还没有达到能够使用指针或任何高级东西的地步。我正在研究 Stroustroup 编程原则和实践,这是第 4 章。