Luo Valley P1217 [USACO1.5] palindromic prime Prime Palindromes (C language + + detailed explanatory plurality optimization)

 

// this topic and ideas is not difficult to guess if the number of primes not only in the interval, is a palindrome, then that is palindromic prime, write two functions to determine the number of prime numbers and palindromes can be. However, this problem does not make you goose so easy through (after all, the difficulty is universal - it), chances are you had a sample, but the results obtained are submitted to a RE (time-out), because this question to reach a maximum data million one traversal, certainly a waste of time, so they need some optimization, the portion of the data directly excluded. Specific Optimization as follows:

1: Even the inevitable is not a prime number, so do not consider even number;

2: On a number of knowledge was: even bit palindrome, in addition to 11 others can be divisible by 11, is not necessarily a prime number, so the maximum data only to (ten million numbers between 10000000 to 100000000 10000000 all eight bits, even, may be straight excluded) (see https://www.zhihu.com/question/67646272 )

3: Screening with Eratosthenes prime method, saving time (see https://blog.csdn.net/qq_45472866/article/details/104051475 )

 

AC Here is my code:

#include<stdio.h>

void checkprime(int p);
int prime[10000000];      //只需开到一千万(开到一亿的话,会超内存)
int is_huiwen(int p);

int main() {
	int a, b, left, right, i;     //left为区间左端点,right为右端点
	scanf("%d%d", &a, &b);     
	if (a % 2 == 0)      //把左端点初始化为奇数
		left = a + 1;      
	else
		left = a;
	if (b > 10000000)      //右端点最大只需一千万
		b = 10000000;
	right = b;
	checkprime(right);         //筛法求1~n之间的素数
	for (i = left; i <= right; i += 2) {        //由于只对奇数操作,故每次加2
		if (prime[i] && is_huiwen(i))               //如果一个数既是素数也是回文数
			printf("%d\n", i);           //输出这个数
	}
	return 0;
}

int is_huiwen(int p) {
	int ans, temp;
	temp = p;             //拷贝p,对temp操作
	ans = 0;
	while (temp) {               //得到p的每一位
		ans = ans * 10 + temp % 10;        //把p的低位作为ans的高位
		temp /= 10; 
	}
	if(ans == p)                 //最终得到的ans和p位相反(例如p = 1234, 则ans = 4321),如果p和ans相等,那么p就是回文数
		return 1;
	return 0;
}

void checkprime(int p) {
	int i;
	for (i = 2; i <= p; i++)
		prime[i] = 1;
	for (i = 2; i * i <= p; i++){
		if (prime[i]) 
			for (int j = i; j * i <= p; j++)
				prime[j * i] = 0;
	}
}

 

 

 

Guess you like

Origin blog.csdn.net/qq_45472866/article/details/104104425