P6685 可持久化动态仙人掌的直径问题
题目背景
众所周知,一场考试需要一道签到题。
题目描述
给定 n,m,求有多少个正整数 x,使得 x^m ≤ n。
输入格式
一行两个正整数 n,m。
输出格式
一个整数表示正整数 xx 的个数。
输入
5 2
输出
2
我的思路
看到这题时,我想到的是C语言中pow库函数,又因库函数调用又比自己实现的函数慢,自己实现幂函数,我又想到快速幂。
故有一下代码:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int n,m;
int ans;
int binpow(int base,int pow){
int result = 1;
while (pow){
if (pow & 1)
result *= base;
base *= base;
pow >>= 1;
}
return result;
}
int main()
{
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1;i <= n;i ++){
if (binpow(i,m) <= n){
ans ++;
}
}
printf("%d",ans);
return 0;
}
可是只能k两个点。好像int、longlong都爆了。还有这里相当于两层循环,可能会超时。
因为pow()函数返回值是double(8字节,最大值为2^64),范围比long long 大的多。所以使用pow函数。(传送门 👈 )
注意: 这里因为 pow() 不稳定,所以要套上 round() 保险。
round 四舍五入,float时返回int值,double时返回long值
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n,m;
int ans;
int main()
{
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1;i <= n;i ++){
if (round(pow(i,m)) <= n){
ans ++;
} else break;
}
printf("%d",ans);
return 0;
}
运用数学知识。因为pow中的形参都是double类型。
将幂函数
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
int n,m;
int main()
{
cin >> n >> m;
int x = round(pow(n,1.0/m));
printf("%d",x);
return 0;
}