查找指针数组中的主要数字

时间:2016-12-03 08:40:36

标签: c++ primes

这段代码工作得很好,它告诉你输入一个数字,然后就可以了 for循环中的数字,它检查它是否可被i分割,如果为真,如果不打印则不打印素数。

#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";
  }
}

但是当我把它转换成这样的数组时:

#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;
}

它只存储第一个数字,我得到了但是如何增加它 让我们说n = 3 所以p [3] = {4,6,7}; 我的问题是如何在j条件下告诉编译器 如果(p [0]%j)那么(p [1]%j)似乎它只需要p [0]

1 个答案:

答案 0 :(得分:0)

这会更好用

#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

我遇到了像int这样的问题。您不应使用带符号的数字进行迭代或存储大小。因为你是初学者,我不想让你迷惑。所以我放手了。