PAT1003数素数

本文详细解析PAT1003编程题,主要探讨如何有效地数素数,涉及素数筛法和算法优化技巧,适合编程初学者和准备算法竞赛的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本题的主要问题就在于运行的效率喽,主要就是要用好判断A是否是素数只要从2到根号A即可。


// ConsoleApplication1.cpp: 定义控制台应用程序的入口点。
//
//#include "stdafx.h"
#include <iostream>
#include <list>
#include <cmath>
using namespace std;
bool IfRight(int TestNum)
{
 if (TestNum == 1)return false;
 else
 {
  for (int i = 2; i<=sqrt(TestNum); i++)
  {
   if (!(TestNum%i)) return false;
  }
  return true;
 }
}
int main()
{
 int M = 0, N = 0;
 cin >> M >> N;
 int NumM = 0, NumN = 0;
 int i = 1, count = 0;
 int temp = 0;
 bool flag = true;
 list<int> TestList;
 while (i>0)
 {
  if (IfRight(i))
  {
   count++;
  }
  if ((count == M) && flag)
  {
   NumM = i;
   flag = false;
  }
  if (count == N) { NumN = i; break; }
  i++;
 }
 for (i = NumM; i <= NumN; i++)
 {
  if (IfRight(i))TestList.push_back(i);
 }
 while (TestList.size() >= 10)
 {
  for (i = 0; i < 9; i++)
  {
   temp = TestList.front();
   TestList.pop_front();
   cout << temp << " ";
  }
  temp = TestList.front();
  TestList.pop_front();
  cout << temp <<endl;
 }
 
  while (TestList.size() != 1)
  {
   temp = TestList.front();
   TestList.pop_front();
   cout << temp << " ";
  }
  
   temp = TestList.front();
   TestList.pop_front();
   cout << temp << endl;
  
 
 //system("pause");
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值