c++ - 两个整数的幂

标签 c++ algorithm logarithm

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

Given a positive integer which fits in a 32 bit signed integer, find if it can be expressed as A^P where P > 1 and A > 0. A and P both should 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/

相关文章:

c++ - 如何组合三个变量以使用boost asio发送?

具有 GSL、LAPACK 或 CBLAS 等数学库的 C++ 性能与具有 R 函数的 Rinside 的 C++ 相比?

c++ - std::iterator、指针和 VC++ 警告 C4996

algorithm - 如何快速找到二进制对数? (最多 O(1))

ruby - 在 Ruby 中计算 Base-n 对数

Matlab计算从-pi到pi而不是0到2pi的弧度

c++ - 向字符串添加字符

c++ - Sprite 的凸多边形化

python - python 的 heapq.merge 使用的算法是什么?

php - 是否有任何 PHP 函数可以通过不区分大小写的比较来解决另一个数组值字符串中的数组值匹配?