求质数问题 希望能写出c++完整程序

JANESTAR 2011-09-17 09:59:59
Problem description
Given a big integer number, you are required to find out whether it's a prime number.


Input
The first line contains the number of test cases T (1 <= T <= 20 ), then the following T lines each contains an integer number N (2 <= N < 254).


Output
For each test case, if N is a prime number, output a line containing the word "Prime", otherwise, output a line containing the smallest prime factor of N.


Sample Input
2
5
10

Sample Output
Prime
2

Problem Source
POJ Monthly


Submit Discuss Judge Status Problems Ranklist
...全文
131 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
JANESTAR 2011-09-18
  • 打赏
  • 举报
回复
太好了 谢谢牛人[Quote=引用 3 楼 elemusic 的回复:]

这样?

C/C++ code

#include <iostream>
#include <vector>

using namespace std;

int main()
{
int numlines = 0;
int num = 0;
vector<int> vInts;
cin>>numlines;
if(numlines < 1 || n……
[/Quote]
yzl_rex 2011-09-18
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

int main()
{
int case1;
cin >> case1;
if (case1 < 1 || case1 > 20)//如果你的是poj系统测试的,好像不用这个条件也可以的!你看看是否可以通过测试!
return -1;
while (case1--)
{
int N;
cin >> N;
if (N < 2 || N > 254)
return -1;
int m = N/2;
for (int j = 2; j <= m + 1; j++)
{
if (N%j == 0)
{
cout << j << endl;
break;
}
if (j > m)
{
cout << "prime" << endl;
break;
}
}
}
}
新铺村长 2011-09-18
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 elemusic 的回复:]

这样?

C/C++ code

#include <iostream>
#include <vector>

using namespace std;

int main()
{
int numlines = 0;
int num = 0;
vector<int> vInts;
cin>>numlines;
if(numlines < 1 || n……
[/Quote]
感觉这样可以了
elemusic 2011-09-17
  • 打赏
  • 举报
回复
我看错了,是<1没错.....
elemusic 2011-09-17
  • 打赏
  • 举报
回复
第一个if条件写错了,应该是


if(numlines < 2 || numlines > 20)
elemusic 2011-09-17
  • 打赏
  • 举报
回复
这样?


#include <iostream>
#include <vector>

using namespace std;

int main()
{
int numlines = 0;
int num = 0;
vector<int> vInts;
cin>>numlines;
if(numlines < 1 || numlines > 20)
return -1;

while(numlines--)
{
cin>>num;
if(num < 2 || num > 253)
return -1;
vInts.push_back(num);
}

vector<int>::iterator pos;
for(pos = vInts.begin(); pos != vInts.end(); ++pos)
{
for(num = 2; num < *pos; ++num)
{
if(*pos % num == 0){
break;
}
}
if(num == *pos)
cout<<"Prime"<<endl<<num<<endl;
else
cout<<"the smallest prime factor of "<<*pos<<" is:"<<num<<endl;
}

return 0;
}
  • 打赏
  • 举报
回复
判断
n是否为质数

如果n是2,直接返回

否则
for(int i=2; i+2<sqrt(n); ++i)
if(n%i == 0)
则n不是质数
否则
做其他事
gnosis 2011-09-17
  • 打赏
  • 举报
回复
N (2 <= N < 254). 这么小的范围暴力都可以了
或者就线性筛素数

64,650

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧