东方博宜OJ 1137:纯粹素数 ← 约数的成对性

【题目来源】
https://oj.czos.cn/p/1137

【题目描述】
纯粹素数是这样定义的:一个素数,去掉最高位,剩下的数仍为素数,再去掉剩下的数的最高位,余下的数还是素数。这样下去一直到最后剩下的个位数也还是素数。
求出所有小于 3000 的四位的纯粹素数。

【输入格式】


【输出格式】
按从小到大的顺序输出若干个纯粹素数,每行一个。

【算法分析】
● 约数的成对性‌:对于任意整数 x,如果 i 是 x 的约数,那么 x/i 也是 x 的约数。
这意味着,如果 i×j=x,那么在这对约数 (i,j) 中,必然有一个小于或等于 sqrt(x)。另一个大于或等于 sqrt(x)。只有当 x 是完全平方数时,两者相等。

● 判定素数的经典代码:https://blog.csdn.net/hnjzsyjyj/article/details/148121301

bool isPrime(int n) {
    if(n<2) return false;
    for(int i=2; i<=sqrt(n); i++) {
        if(n%i==0) return false;
    }
    return true;
}

本素数判定的经典代码,就利用了“约数的成对性”。

● 本题的难点,在于如何多次去掉数的最高位。巧妙之处在于利用 while 循环进行求余操作。即:若去掉 n 位数的最高位,则将其对 10 的 n-1 次方求余。例如,若去掉 127 的最高位,则需计算 127%100 的值。

例题:给定正整数 N,反复去掉当前数的最高位得到新数,并将每次生成的新数(含初始数 N 本身)累加,直至剩余数字为一位数时停止。

#include <bits/stdc++.h>
using namespace std;

int f(int x) {
    int t=x,sum=x;
    while(t>0) {
        int p=1;
        while(p*10<=t) {
            p*=10;
        }
        t%=p;
        sum+=t;
    }
    return sum;
}

int main() {
    int x;
    cin>>x;
    cout<<f(x);

    return 0;
}

/*
in:123
out:149
*/

【算法代码】
基于“约数的成对性”优化编写判定素数的代码。

#include <bits/stdc++.h>
using namespace std;

bool isPrime(int x) {
    if(x<2) return false;
    for(int i=2; i*i<=x; i++) {
        if(x%i==0) return false;
    }
    return true;
}

bool isPurePrime(int x) {
    int t=x;
    while(t>0) {
        if(!isPrime(t)) return false;
        int p=1;
        while(p*10<=t) {
            p*=10;
        }
        t%=p;
    }
    return true;
}

int main() {
    for(int i=1000; i<3000; i++) {
        if(isPurePrime(i)) {
            cout<<i<<endl;
        }
    }

    return 0;
}

/*
1013
1097
1103
1223
1283
1307
1367
1373
1523
1607
1613
1823
1907
1997
2003
2017
2053
2083
2113
2137
2347
2383
2467
2503
2617
2647
2683
2797
2953
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/149547149
https://blog.csdn.net/hnjzsyjyj/article/details/148121301
https://blog.csdn.net/hnjzsyjyj/article/details/149666210
https://blog.csdn.net/hnjzsyjyj/article/details/157615246

posted @ 2026-06-15 14:51  Triwa  阅读(6)  评论(0)    收藏  举报