素数最短距离问题
素数距离问题时间限制:3000 ms | 内存限制:65535 KB
难度:2
描述
现在给出你一些数,要求你写出一个程序,输出这些整数相邻最近的素数,并输出其相距长度。
如果左右有等距离长度素数,则输出左侧的值及相应距离。
如果输入的整数本身就是素数,则输出该素数本身,距离输出0输入
第一行给出测试数据组数N(0<N<=10000)
接下来的N行每行有一个整数M(0<M<1000000),
输出
每行输出两个整数 A B.
其中A表示离相应测试数据最近的素数,B表示其间的距离。
样例输入
3
6
8
10
样例输出
5 1
7 1
11 1
//这里效率上不高,我主要是练习使用筛法求素数!
代码如下:
#include <iostream>
#include <cstring>//用到memset
//#include <ctime>
//#include <cstdio>
using namespace std;
#define MAX_SIZE 5000000//定义这么大是为了保证与M最近的素数可能是超过100万
bool isPrime[MAX_SIZE];
void CreatePrimeTable()
{
//clock_t start = clock();
memset(isPrime, true, sizeof(isPrime));
isPrime[0] = isPrime[1] = false;
int i, j;
for (i = 2; i * i <= MAX_SIZE; i++)
{
if (isPrime[i])
{
for (j = i * 2; j <= MAX_SIZE; j += i)
isPrime[j] = false;
}
}
//cout << "TIME:" << clock()-start << "ms" << endl;
}
int main()
{
CreatePrimeTable();
int m;
cin >> m;
for (int i = 1; i <= m; i++)
{
long s;
cin >> s;
if (isPrime[s])
cout << s << " " << 0 << endl;
else
{
long a, b, dis1, dis2;
for (a = s-1; a >= 2; a--)
{
if (isPrime[a])
{
dis1 = s - a;
break;
}
}
for (b = s+1; ; b++)
{
if (isPrime[b])
{
dis2 = b - s;
break;
}
}
if (dis1 <= dis2)
cout << a << " " << dis1 << endl;
else
cout << b << " " << dis2 << endl;
}
}
return 0;
}
最后更新:2017-04-02 15:14:53