UVa 10394-Twin Primes

大憨熊 提交于 2020-01-08 13:07:32

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

问题描述】

    Twin primes are pairs of primes of the form (p, p+2). The term "twin prime" was coined by Paul Stäckel (1892-1919). The first few twin primes are (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43). In this problem you are asked to find out the S-th twin prime pair where S is an integer that will be given in the input. 

Input

    The input will contain less than 10001 lines of input. Each line contains an integers S (1<=S<=100000), which is the serial number of a twin prime pair. Input file is terminated by end of file. 

Output

    For each line of input you will have to produce one line of output which contains the S-th twin prime pair. The pair is printed in the form (p1,<space>p2). Here <space> means the space character (ASCII 32). You can safely assume that the primes in the 100000-th twin prime pair are less than 20000000.

Sample Input
1

2

3

4

Sample Output 

(3, 5)

(5, 7)

(11, 13)

(17, 19)


【解题思路

     先离线计算素数筛,再筛选出双素数保存较小的一个,判断输出。


【具体实现

#include<iostream>

#define N 20000000
#define n 100000
#define Inp 10001

using namespace std;

int SIGN[N] = { 0 };
int ANS[n] = { 0 };

int main(){
	/*素数筛*/
	SIGN[0] = SIGN[1] = 1;
	for (int i = 2; i < N;++i)
	if (!SIGN[i])
	for (int j = i * 2; j < N; j += i)
		SIGN[j] = 1;

	/*若为双素数,保存较小的*/
	int s=0;
	for (int k = 3; k < N;++k)
	if (SIGN[k] == 0 && SIGN[k + 2] == 0)
		ANS[++s] = k;


	int num;
	int times = 0;
	while (cin >> num)
	if (num >= 1 && num <= n&&times < Inp)
		cout << '(' << ANS[num] << ',' << ' ' << ANS[num] + 2 << ')' << endl;

	return 0;
}


【额外补充

1.int型数组

函数体外定义,不初始化会被默认初始化为0;

函数体外定义,初始化第一个,后面的都会默认初始化为0;

函数体外定义,初始化前一部分,后面的都会默认初始化为0;

函数体内定义,不初始化会是垃圾值。

函数体内定义,初始化第一个,后面的都会默认初始化为0;

函数体内定义,初始化前一部分,后面的都会默认初始化为0;

2.float型数组

函数体外定义,不初始化会被默认初始化为0;

函数体外定义,初始化第一个,后面的都会默认初始化为0;

函数体外定义,初始化前一部分,后面的都会默认初始化为0;

函数体内定义,不初始化会是垃圾值。

函数体内定义,初始化第一个,后面的都会默认初始化为0;

函数体内定义,初始化前一部分,后面的都会默认初始化为0;

3.char型数组

函数体外定义,不初始化会被默认初始化为空;

函数体外定义,初始化第一个,后面的都会默认初始化为空;

函数体外定义,初始化前一部分,后面的都会默认初始化为空;

函数体内定义,不初始化会被默认初始化为空;

函数体内定义,初始化第一个,后面的都会默认初始化为空;

函数体内定义,初始化前一部分,后面的都会默认初始化为空;


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!