跳到正文

题解

P14663 题解

#SUSPENDED#约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年12月7日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 2 分钟
题目
P14663

版本

  1. v2当前
  2. v1

Solution of P14663

题意:

求出 11 和 nn 之间,完全平方数中有多少个是 33 的倍数。

做法一:暴力

我们直接枚举 11 到 nn 之间的完全平方数并判断。

C++
#include <bits/stdc++.h>
using namespace std;
int main(){
    int T;cin >> T;
    while (T--){
        int n;cin >> n;
        int cnt = 0;
        for (int i = 1;i <= sqrt(n);i++){
            if (i * i % 3 == 0)cnt++;
        }
        cout << cnt << "\n";
    }
}

暴力的优化:

不难想到,当一个数是 33 的倍数时,它的平方也一定是 33 的倍数。

因此,我们只需要枚举 11 到 n\sqrt{n} 范围中 33 的倍数的平方即可。

C++
#include <bits/stdc++.h>
using namespace std;
int main(){
    int T;cin >> T;
    while (T--){
        int n;cin >> n;
        int cnt = 0;
        for (int i = 3;i <= sqrt(n);i+=3){
            cnt++;
        }
        cout << cnt << "\n";
    }
}

正解:

由暴力的优化我们可以想到,我们只需要统计 11 到 n\sqrt{n} 之间 33 的倍数的数量即可。

我们把每三个数看成一组,那么每组中就会有且只有一个 33 的倍数。

因此 11 到 n\sqrt{n} 之间一共会有 n3\frac{\sqrt{n}}{3} 个(实际为向下取整的整数结果)。

因此答案即为 n3\frac{\sqrt{n}}{3}(向下取整)。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main(){
    int T;cin >> T;
    while (T--){
        int x;scanf("%lld",&x);
        int k = sqrt(x);
        printf("%lld\n",k/3);
    }
}

对于每次询问,获取答案的复杂度为 O(1)O(1)。

原文