gpt4 book ai didi

c++ - 两个整数的幂

转载 作者:行者123 更新时间:2023-12-01 15:10:10 25 4
gpt4 key购买 nike

我正在尝试解决有关两个整数的幂的问题。问题描述如下:

Given a positive integer which fits in a 32 bit signed integer, findif it can be expressed as A^P where P > 1 and A > 0. A and P bothshould be integers.
Example:
Input: n = 8
Output: true
8 can be expressed as 2^3

Input: n = 49
Output: true
49 can be expressed as 7^2

现在,我已经按照以下方法解决了这个问题。

int Solution::isPower(int A) {
if(A == 1)
{
return true;
}

for(int x = 2; x <= sqrt(A); x++)
{
unsigned long long product = x * x;

while(product <= A && product > 0)
{
if(product == A)
{
return true;
}

product = product * x;
}
}

return false;
}

但是,我从 geeksforgeeks 找到了另一个解决方案它仅使用对数除法来确定该值是否可以用两个整数的幂表示。

bool isPower(int a) 
{
if (a == 1)
return true;

for (int i = 2; i * i <= a; i++) {
double val = log(a) / log(i);
if ((val - (int)val) < 0.00000001)
return true;
}

return false;
}

谁能解释一下上面的对数解?提前致谢。

最佳答案

它使用数学来解决这个问题。

9=3^2
Log 9 = log 3^2... Adding log at both side
Log 9 = 2 * log 3...using log property
2 = log 9 / log 3

如你所见,最后一条语句等同于代码双 val = log(a)/log(i);

然后它检查 Val - round(val) 是否为 0...如果这是真的,val 就是 ans,否则它不会是 0。对数不给出精确的 ans。

关于c++ - 两个整数的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63658617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com