d3v*_*pro 8 c++ algorithm math integer integer-arithmetic
在c ++中是否有任何预定义的函数来检查数字是否为任何数字的平方并且对于多维数据集是否相同.
Chr*_*ung 13
不,但写一个很容易:
bool is_perfect_square(int n) {
if (n < 0)
return false;
int root(round(sqrt(n)));
return n == root * root;
}
bool is_perfect_cube(int n) {
int root(round(cbrt(n)));
return n == root * root * root;
}
Run Code Online (Sandbox Code Playgroud)
sqrt(x),或一般来说,pow(x, 1./2)或pow(x, 1./3)
例如:
int n = 9;
int a = (int) sqrt((double) n);
if(a * a == n || (a+1) * (a+1) == n) // in case of an off-by-one float error
cout << "It's a square!\n";
Run Code Online (Sandbox Code Playgroud)
编辑:或一般情况下:
bool is_nth_power(int a, int n) {
if(n <= 0)
return false;
if(a < 0 && n % 2 == 0)
return false;
a = abs(a);
int b = pow(a, 1. / n);
return pow((double) b, n) == a || pow((double) (b+1), n) == a;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38685 次 |
| 最近记录: |