HDU 4548 Beautiful prime number Prime number Problem solution

This question can be directly typed, and it also requires skills to infer whether it can be typed:

1 Inferred maximum value is 1,000,000. It is possible to play numbers below a million

2 can be linearly preprocessed well. Using the prime sieve method is able to approach linear preprocessing.

So it can be clocked.


Basic knowledge points to be familiar with:

1 Prime Sieve Method - Write code in a minute or two

2 General prime number inference method, since the value after adding the number of digits is very small, the general prime number inference can be done, assuming that writing a primality test algorithm will be overkill.

3 Then there is the idea of ​​dynamic programming method to superimpose the preceding US prime numbers to facilitate searching.


It is a basic question, and it is also a water question that some people say. I still like to call it a basic question.

The difficulty lies in inferring well and applying these basics well. Simple and elegant solution, write code.

#include <stdio.h>
#include <string.h>

const int MAX_N = 1000001;
bool isPrime(int n)
{
	if (n == 2) return true;
	for (int r = 2; r * r <= n; r++)
	{
		if (n % r == 0) return false;
	}
	return true;
}

bool isMeiPrime(int n)
{
	int d = 0;
	while (n)
	{
		d += n % 10;
		n /= 10;
	}
	return isPrime(d);
}

int primeNums[MAX_N];
bool primes[MAX_N];

void seive()
{
	memset(primes, 0, MAX_N * sizeof(bool));
	for (int i = 2; i < MAX_N; i++)
	{
		if (!primes[i])
		{
			for (int j = i << 1; j < MAX_N; j += i)
			{
				primes[j] = true;
			}
		}
	}

	primeNums[0] = 0, primeNums[1] = 0;
	for (int i = 2; i < MAX_N; i++)
	{
		if (!primes[i] && isMeiPrime(i)) primeNums[i] = primeNums[i-1] + 1;
		else primeNums[i] = primeNums[i-1];
	}
}

intmain()
{
	seive();
	int T, a, b;
	scanf("%d", &T);
	for (int t = 1; t <= T; t++)
	{
		scanf("%d %d", &a, &b);
		printf("Case #%d: %d\n", t, primeNums[b] - primeNums[a-1]);
	}
	return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324877282&siteId=291194637