算法7——求素数(暴力枚举)

PD:

Besides the ordinary Boy Friend and Girl Friend, here we define a more academic kind of friend: Prime Friend. We call a nonnegative integer A is the integer B’s Prime Friend when the sum of A and B is a prime.

So an integer has many prime friends, for example, 1 has infinite prime friends: 1, 2, 4, 6, 10 and so on. This problem is very simple, given two integers A and B, find the minimum common prime friend which will make them not only become primes but also prime neighbor. We say C and D is prime neighbor only when both of them are primes and integer(s) between them is/are not.

Input:

The first line contains a single integer T, indicating the number of test cases.

Each test case only contains two integers A and B.

Technical Specification

1. 1 <= T <= 1000

2. 1 <= A, B <= 150

Output:

For each test case, output the case number first, then the minimum common prime friend of A and B, if not such number exists, output -1.

Sample Input:

2

2 4

3 6

Sample Output:

Case 1: 1

Case 2: -1

题意:

  即求一个数,能使a,b与之相加后,成为素数,并且a与b之间没有其他的素数。

做法:

  该题的关键是将20000000之前的素数打表,然后求其每个之间的差值,相等的存放到同一个数组中。

annotation:

   本文转载自微信公众号《ACM算法日常》,原文链接:https://mp.weixin.qq.com/s/qsOYvygfPdDWt2qc28CSwA

Code:

#include <stdio.h>
#include <math.h>
#include <memory.h>
#include <Windows.h>
const int MAX_VALUE=2E7;          /*设定最大素数小于20000000  */     
static int primes[MAX_VALUE];     /*最后用于存放生出的素数表*/
static char is_prime[MAX_VALUE+1];  /*初始数组*/
int creatprimetable()             /* 产生素数表函数*/
{
	int size=0;
	memset(is_prime,1,sizeof(is_prime));   /*memset函数用于对数组进行初始化,此处全部设为1*/
	int s=sqrt((double)MAX_VALUE)+1;		
	/*下面使用开根号法:对大于2的数N求平方根得到S,如果N能被2-S之间的数整除,那么N不是质数*/
	for(int i=2;i<=s;i++)
	{
		if(is_prime[i])
		{
			for(int j=2;j<=MAX_VALUE/i;j++)
				is_prime[i*j]=0;}}
	/*遍历找出所有素数并放在数组primes中*/
	for(int i=2;i<=MAX_VALUE;i++)
		if(is_prime[i])
			primes[size++]=i;
	 is_prime[0] = is_prime[1] = 0;
	 return size;
}

int main()
{
	/*输入test case 数目*/
	int count;
	scanf("%d",&count);
	int size=creatprimetable();
	int case_number=1;
	double start=GetTickCount();
	while(count--)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		if(a>b)
		{
			a=a^b;b=a^b;a=a^b;
		}
		int prime=-1;
		/*筛选并算出符合条件 的prime friend 具体数值*/
		for(int i=0;i<size-1;i++)
		{
			if(primes[i]>=a&&primes[i+1]>=b)		/*要确保a与b之间只有一个素数以确保符合题意要求,构成prime neighbor;*/
				if(primes[i]-a==primes[i+1]-b)
				{
					prime=primes[i]-a;
					break;
				}
		}
		printf("case %d:%d\n",case_number++,prime);
	}
	double end=GetTickCount();
	printf("The run time:%.0lfms\n",end-start);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41345173/article/details/81950248