📌  相关文章
📜  检查数字是否可以表示为a ^ b |套装2

📅  最后修改于: 2021-05-04 18:49:53             🧑  作者: Mango

您给了数字n。检查数字是否可以pow(a,b)(a ^ b)的形式表示。

例子:

Input : 4
Output : Yes
22 = 4

Input : 12
Output : No

我们在“检查数字是否可以表示为x ^ y(x升为幂y)”中讨论了两种方法。在这篇文章中,讨论了一种更有效的解决方案。这个想法是基于对数的。

Consider a no. N which needs 
to be expressed in the form (a^b).
N = ab
Taking log both sides:
log (N) = a.log (b)
a = log(N)/log(b)

请牢记此逻辑,以开发以下提到的最有效的解决方案:

C++
// CPP program to check if a number
// can be expressed as a^b.
#include 
using namespace std;
 
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;
}
 
// Driver code
int main()
{
    int n = 16;
    cout << (isPower(n) ? "Yes" : "No");
    return 0;
}


Java
//Java program to check if a number
//can be expressed as a^b.
 
public class GFG {
 
    static boolean isPower(int a)
    {
    if (a == 1)
        return true;
 
    for (int i = 2; i * i <= a; i++) {
        double val = Math.log(a) / Math.log(i);
        if ((val - (int)val) < 0.00000001)
            return true;
    }
 
    return false;
    }
     
    // Driver code
    public static void main(String[] args) {
         
        int n = 16;
        System.out.println(isPower(n) ? "Yes" : "No");
 
    }
}


Python 3
# Python 3 Program to check if a number
# can be expressed as a^b
 
from math import *
 
def isPower(a) :
    if a== 1 :
        return True
 
    for i in range(2, int(sqrt(a)) + 1) :
        val = log(a) / log(i)
 
        if (round((val - int(val)),8) < 0.00000001):
            return True
     
    return False
 
 
# Driver Code
if __name__ == "__main__" :
 
    n = 16
 
    if isPower(n) :
        print("Yes")
    else :
        print("No")
 
# This code is contributed by ANKITRAI1


C#
// C# program to check if a number
// can be expressed as a^b.
using System;
 
class GFG
{
 
public static bool isPower(int a)
{
    if (a == 1)
    {
        return true;
    }
 
    for (int i = 2; i * i <= a; i++)
    {
        double val = Math.Log(a) /
                     Math.Log(i);
        if ((val - (int)val) < 0.00000001)
        {
            return true;
        }
    }
return false;
}
 
// Driver code
public static void Main(string[] args)
{
    int n = 16;
    Console.WriteLine(isPower(n) ?
                           "Yes" : "No");
}
}
 
// This code is contributed
// by Shrikant13


PHP


输出
Yes

时间复杂度: O(sqrt(n))