当前位置: 代码迷 >> 综合 >> Luogu P1217
  详细解决方案

Luogu P1217

热度:13   发布时间:2023-12-05 05:35:30.0

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 3for (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 5for (d2 = 0; d2 <= 9; d2++) {
    for (d3 = 0; d3 <= 9; d3++) {
    palindrome = 10000*d1 + 1000*d2 +100*d3 + 10*d2 + d1;//generate the palindromespalin.add(palindrome);}}}for (d1 = 1; d1 <= 9; d1+=2) {
        // Only odd number can be prime 7for (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).