问题
This piece of code which works fine it tells you to enter a number, then it puts the number in a for loop and it checks if it's dividable by i, if true it prints not prime if not prints prime.
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
bool f = true;
for (int i = 2; i < x; i++) {
f = false;
if (i % x == 0)
f = true;
if (f)
cout << "not primary";
else
cout << "primary";
}
}
but when i convert it to an array like so:
#include <iostream>
using namespace std;
int main() {
cout << "the number of array:" << endl;
int n;
cin >> n;
cout << "enter them = \n";
int *p = new int[n];
for (int i = 0; i < n; i++)
cin >> p[i];
bool f = true;
for (int i = 0; i < n; i++)
for (int j = 2; j < p[i]; j++) {
f = false;
if (p[i] % j == 0)
f = true;
if (f)
cout << "This is not a primary number!\n";
else
cout << "this is a primary number!\n";
}
delete p;
}
it stores just the first number and i get that but how to increment it lets say n =3 so p[3] = {4,6,7}; my question is how tell the compiler in the j condition if (p[0] % j) then(p[1] %j) it seems that it just takes p[0]
回答1:
This will work much better
#include <iostream>
using namespace std;
int main() {
cout << "the number of array:" << endl;
int n;
cin >> n;
cout << "enter them = \n";
int *p = new int[n];
for (int i = 0; i < n; i++)
cin >> p[i];
for (int i = 0; i < n; i++) {
bool f = false; // we set f to false for each number
for (int j = 2; j < p[i]; j++) {
if (p[i] % j == 0) {
f = true;
break; // we break the loop if it's a prime number
}
}
if (f)
cout << p[i] << " is not a primary number!\n";
else
cout << p[i] << " is a primary number!\n";
}
delete[] p; // Here you forget brackets [], when you use new[] you must use delete[].
}
Doc for delete operator.
I let some problem like int
. You should not use signed number for iteration or stock a size. Because you are a beginner, I don't want to confuse you. So I let it.
来源:https://stackoverflow.com/questions/40945872/finding-the-primary-numbers-in-an-array-of-pointer