以下是一个求质数的C++程序示例:

#include <iostream>
using namespace std;

int main() {
  int n;
  bool isPrime = true;

  cout << "请输入一个正整数:";
  cin >> n;

  // 判断n是否为质数
  for (int i = 2; i <= n / 2; ++i) {
    if (n % i == 0) {
      isPrime = false;
      break;
    }
  }

  if (isPrime)
    cout << n << " 是质数";
  else
    cout << n << " 不是质数";

  return 0;
}

在这个程序中,我们首先从用户那里获取一个正整数。然后,我们使用一个循环来判断这个数字是否为质数。如果n可以被2到n/2之间的任意整数整除,则它不是质数,程序输出“不是质数”。否则,它是质数,程序输出“是质数”。

帮我写一段求质数的C++语言代码

原文地址: https://www.cveoy.top/t/topic/wGZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录