Luogu P1217

luoguP1217
Outline: Output all palindromes, then determine whether it’s a prime or not.

Cavets: Prime palindromes have the following features:
1. All palindromes have even digits, e.g. 1221, 111111 etc. are divisible by 11 (except 11 itself), so they’re not prime.
2. All palindromes have even head and tail are not prime numbers. e.g. 212 etc.

for (d1 = 1; d1 <= 9; d1+=2) {    //  Only odd number can be prime 3
		     for (d2 = 0; d2 <= 9; d2++) {
		    	 palindrome = d1 * 100 + d2 * 10 + d1;
		    	 palin.add(palindrome);
		     }
		}
		for (d1 = 1; d1 <= 9; d1+=2) {    // Only odd number can be prime 5
			     for (d2 = 0; d2 <= 9; d2++) {
			         for (d3 = 0; d3 <= 9; d3++) {
			           palindrome = 10000*d1 + 1000*d2 +100*d3 + 10*d2 + d1;//generate the palindromes
			           palin.add(palindrome);
			         }
			     }
			 }
		for (d1 = 1; d1 <= 9; d1+=2) {    //  Only odd number can be prime 7
		     for (d2 = 0; d2 <= 9; d2++) {
		         for (d3 = 0; d3 <= 9; d3++) {
		        	 for (d4 = 0; d4 <= 9; d4++) {
		        		 palindrome = 1000000*d1 + 100000*d2 +10000*d3 + 1000*d4 + 100 * d3 + 10 * d2 + d1;
		        		 palin.add(palindrome);
		        	 }
		         }
		     }
		 }
		 /* Single digit and two digits number have to be added manually. Here I neglected them.*/
		 

Determine whether a number is prime??
Solution A:
If you just wanna know some discrete numbers, like the palindromes in this test. Iterate the number between 2 to sqrt(thisNumber), see if
this number is divisible by the former. If is divisible, then not prime, otherwise it is prime.

Solution B:
If you wanna get prime value from an early stage, or just from 1 to n, then you should just judge whether the current number is divisible by the known prime that is smaller than it. Then, if the number is prime, store it and used in the next judgement (This process must start from 2 to ensure all prime smaller than the current one is in the list).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值