C++ 中的五次方根
在这个问题中,我们给定一个数字 N。我们的任务是找到该数字五次方根的向下取整值。
五次方根是一个数,当它自身相乘 5 次时,结果等于该数。
如果 N1/5 = a,则 a*a*a*a*a = N。
让我们来看一个例子来理解这个问题:
输入:N = 325
输出:3
解释:
325 的五次方根是 3.179,其向下取整值为 3。
解决方案:
一个简单的解决方案是从 1 到 n 遍历。并找到一个数,当它自身相乘五次时,结果等于该数。
在这里,无法找到精确值,因为这些数并不总是完美的五次方。因此,我们将找到第一个使得五次方大于 n 的值,然后返回该值 -1 来获得五次方根的向下取整值。
程序演示了我们解决方案的工作原理:
示例
#include<iostream>
using namespace std;
int calcFifthRoot(int n) {
if (n == 0 || n == 1)
return n;
int a = 0;
for(a = 1; a*a*a*a*a < n ; a++){
}
return (a - 1);
}
int main() {
int n = 325;
cout<<"The Floor of fifth root of "<<n<<" is "<<calcFifthRoot(n);
return 0;
}输出 -
The Floor of fifth root of 325 is 3
此算法很好,但是可能存在更好的解决方案。这可以通过更新搜索算法并使用二分查找算法来搜索该数字的五次方根来实现。
程序演示了我们解决方案的工作原理:
示例
#include<iostream>
using namespace std;
int calcFifthRoot(int n)
{
if (n == 0 || n == 1)
return n;
int start = 1, end = n, root = 0;
while (start <= end)
{
int a = (start + end) / 2;
long int apowfive = a*a*a*a*a;
if (apowfive == n)
return a;
if (apowfive < n) {
start = a + 1;
root = a;
}
else
end = a - 1;
}
return root;
}
int main() {
int n = 250;
cout<<"The floor of fifth root of "<<n<<" is "<<calcFifthRoot(n);
return 0;
}输出 -
The floor of fifth root of 250 is 3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP