Solution of P14663
题意:
求出 和 之间,完全平方数中有多少个是 的倍数。
做法一:暴力
我们直接枚举 到 之间的完全平方数并判断。
#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";
}
}暴力的优化:
不难想到,当一个数是 的倍数时,它的平方也一定是 的倍数。
因此,我们只需要枚举 到 范围中 的倍数的平方即可。
#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";
}
}正解:
由暴力的优化我们可以想到,我们只需要统计 到 之间 的倍数的数量即可。
我们把每三个数看成一组,那么每组中就会有且只有一个 的倍数。
因此 到 之间一共会有 个(实际为向下取整的整数结果)。
因此答案即为 (向下取整)。
#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);
}
}对于每次询问,获取答案的复杂度为 。