湘大oj-数码积性练习笔记

一.题目描述

二.初始代码

问题:时间超限

cs 复制代码
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
int s(int n)//数码和
{
   
    int num = 0;
    while (n)
    {
        num += n % 10;
        n /= 10;
    }
    return num;
}
bool check(int n)
{
    for (int i = 2;i * i <= n;i++)
    {
        if (n % i != 0)
            continue;
        int x = i, y = n / i;
        if (s(n) == s(x) * s(y))
            return true;
    }
    return false;
}
bool N[10000010] = { false };
void Sum()
{
    for (int i = 1;i <= 10000000;i++)
    {
        if (check(i))
            N[i] = true;
    }
    return;
}
int main()
{
    int t;scanf("%d", &t);
    Sum();
    while (t--)
    {
        int L, R;
        scanf("%d %d", &L, &R);
        int cnt = 0;
        for (int i = L;i <= R;i++)
        {
            if (N[i])
                cnt++;
        }
        printf("%d\n", cnt);
    }
    return 0;
}

三.反思问题

考虑到可以在遍历样例前将所有可能的n记录下来,但忽略了每个数值都遍历寻找因数的代价过大(因子问题可以考虑用埃式筛法解决),没有考虑到可以运用前缀和的方法存储个数提高效率,也没有考虑到可以提前用数组存储各数值数码和提高效率.......

关键优化点总结

  1. 避免对每个数单独分解因子,而是通过双重循环生成所有可能的乘积

  2. 提前计算数码和,避免重复计算

  3. 使用前缀和快速回答区间查询

  4. 利用乘积对称性减少循环次数

最终AC代码

cs 复制代码
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
//全局变量,分配在数据段,不会溢出
int s[10000010] = { 0 };
bool N[10000010] = { false };
int pre[10000010] = { 0 };
int main()
{
    int t;scanf("%d", &t);
    //数码和可以预处理,用数组存储提高效率
    for (int i = 1;i <= 1e7;i++)
    {
        s[i] = s[i / 10] + (i % 10);
    }
    
    //结合埃式筛选法遍历找出满足"数码积性"的n(素数,合数问题)
    for (int i = 2;i <= 1e7;i++)
    {
        if (!N[i])
        {
            for (int j = i;(long long)j * i <= 1e7;j++)
            {
                int n = j * i;
                if (s[n] == s[j] * s[i])
                    N[n] = true;
            }
        }
    }

    //区间个数运用前缀和
    for (int i = 4;i <= 1e7;i++)
    {
        pre[i] = pre[i - 1] +( N[i] ? 1 : 0);
    }
    while (t--)
    {
        int L, R;
        scanf("%d %d", &L, &R);
        printf("%d\n", pre[R] - pre[L - 1]);
    }
    return 0;
}
相关推荐
JieE21216 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2122 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2123 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2123 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术3 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050733 天前
(一)小红的数组操作
算法·编程语言