📌  相关文章
📜  检查一个数字是否是另一个数字的幂

📅  最后修改于: 2021-05-06 21:19:38             🧑  作者: Mango

给定两个正数x和y,请检查y是否为x的幂。
例子 :

Input:  x = 10, y = 1
Output: True
x^0 = 1

Input:  x = 10, y = 1000
Output: True
x^3 = 1

Input:  x = 10, y = 1001
Output: False

一个简单的解决方案是重复计算x的幂。如果幂等于y,则y为幂,否则为非。

C++
// C++ program to check if a number is power of
// another number
#include 
using namespace std;
 
/* Returns 1 if y is a power of x */
bool isPower(int x, long int y)
{
    // The only power of 1 is 1 itself
    if (x == 1)
        return (y == 1);
 
    // Repeatedly comput power of x
    long int pow = 1;
    while (pow < y)
        pow *= x;
 
    // Check if power of x becomes y
    return (pow == y);
}
 
/* Driver program to test above function */
int main()
{
    cout << isPower(10, 1) << endl;
    cout << isPower(1, 20) << endl;
    cout << isPower(2, 128) << endl;
    cout << isPower(2, 30) << endl;
    return 0;
}


Java
// Java program to check if a number is power of
// another number
public class Test {
    // driver method to test power method
    public static void main(String[] args)
    {
        // check the result for true/false and print.
        System.out.println(isPower(10, 1) ? 1 : 0);
        System.out.println(isPower(1, 20) ? 1 : 0);
        System.out.println(isPower(2, 128) ? 1 : 0);
        System.out.println(isPower(2, 30) ? 1 : 0);
    }
    /* Returns true if y is a power of x */
    public static boolean isPower(int x, int y)
    {
        // The only power of 1 is 1 itself
        if (x == 1)
            return (y == 1);
 
        // Repeatedly compute power of x
        int pow = 1;
        while (pow < y)
            pow = pow * x;
 
        // Check if power of x becomes y
        return (pow == y);
    }
}
 
// This code is contributed by Jyotsna.


Python3
# python program to check
# if a number is power of
# another number
 
# Returns true if y is a
# power of x
def isPower (x, y):
     
    # The only power of 1
    # is 1 itself
    if (x == 1):
        return (y == 1)
         
    # Repeatedly compute
    # power of x
    pow = 1
    while (pow < y):
        pow = pow * x
 
    # Check if power of x
    # becomes y
    return (pow == y)
     
     
# Driver Code
# check the result for
# true/false and print.
if(isPower(10, 1)):
    print(1)
else:
    print(0)
 
if(isPower(1, 20)):
    print(1)
else:
    print(0)
if(isPower(2, 128)):
    print(1)
else:
    print(0)
if(isPower(2, 30)):
    print(1)
else:
    print(0)
     
# This code is contributed
# by Sam007.


C#
// C# program to check if a number
// is power of another number
using System;
 
class GFG
{
     
    // Returns true if y is a power of x
    public static bool isPower (int x, int y)
    {
        // The only power of 1 is 1 itself
        if (x == 1)
        return (y == 1);
 
        // Repeatedly compute power of x
        int pow = 1;
        while (pow < y)
        pow = pow * x;
 
        // Check if power of x becomes y
        return (pow == y);
    }
     
    // Driver Code
    public static void Main ()
    {
        //check the result for true/false and print.
        Console.WriteLine(isPower(10, 1) ? 1 : 0);
        Console.WriteLine(isPower(1, 20) ? 1 : 0);
        Console.WriteLine(isPower(2, 128) ? 1 : 0);
        Console.WriteLine(isPower(2, 30) ? 1 : 0);
    }
     
}
 
// This code is contributed by Sam007


PHP


Javascript


C++
// CPP program to check given number number y
// is power of x
#include 
#include 
using namespace std;
 
bool isPower(int x, int y)
{
    // logarithm function to calculate value
    int res1 = log(y) / log(x);
    double res2 = log(y) / log(x); // Note : this is double
 
    // compare to the result1 or result2 both are equal
    return (res1 == res2);
}
 
// Driven program
int main()
{
    cout << isPower(27, 729) << endl;
    return 0;
}


Java
// Java program to check given
// number y is power of x
 
class GFG
{
    static boolean isPower(int x,
                           int y)
    {
        // logarithm function to
        // calculate value
        int res1 = (int)Math.log(y) /
                   (int)Math.log(x);
                    
         // Note : this is double         
        double res2 = Math.log(y) /
                      Math.log(x);
     
        // compare to the result1 or
        // result2 both are equal
        return (res1 == res2);
    }
     
    // Driver Code
    public static void main(String args[])
    {
        if(isPower(27, 729))
            System.out.println("1");
        else
            System.out.println("0");
    }
}
 
// This code is contributed by Sam007


Python3
# Python3 program to check
# given number number y
import math
def isPower(x, y):
    # logarithm function to
    # calculate value
    res1 = math.log(y) // math.log(x);
     
    # Note : this is double
    res2 = math.log(y) / math.log(x);
 
    # compare to the result1 or
    # result2 both are equal
    return 1 if(res1 == res2) else 0;
 
# Driver Code
if __name__=='__main__':
    print(isPower(27, 729));
 
# This code is contributed by mits
# Improved by hsagarthegr8


C#
// C# program to check given
// number y is power of x
using System;
class GFG
{
static bool isPower(int x, int y)
{
    // logarithm function to
    // calculate value
    int res1 = (int)Math.Log(y) /
               (int)Math.Log(x);
                 
    // Note : this is double        
    double res2 = Math.Log(y) /
                  Math.Log(x);
 
    // compare to the result1 or
    // result2 both are equal
    return (res1 == res2);
}
 
// Driver Code
static void Main()
{
    if(isPower(27, 729))
        Console.WriteLine("1");
    else
        Console.WriteLine("0");
}
}
 
// This code is contributed by mits


PHP


Javascript


输出:

1
0
1
0

上述解决方案的时间复杂度为O(Log x y)
优化:
我们可以优化上述解决方案以在O(Log Log y)中工作。这个想法是对功率进行平方运算,而不是将其乘以x,即,将y与x ^ 2,x ^ 4,x ^ 8等进行比较。如果x等于y,则返回true。如果x大于y,则我们在先前功率和当前功率之间(即x ^ i和x ^(i / 2)之间)对x的幂进行二值搜索。
以下是详细步骤。

1) Initialize pow = x, i = 1
2) while (pow < y)
   {
      pow = pow*pow 
      i *= 2
   }    
3) If pow == y
     return true;
4) Else construct an array of powers
   from x^i to x^(i/2)
5) Binary Search for y in array constructed
   in step 4. If not found, return false. 
   Else return true.

替代解决方案:
这个想法是在基数x中取y的对数。如果结果是整数,则返回true。否则为假。

C++

// CPP program to check given number number y
// is power of x
#include 
#include 
using namespace std;
 
bool isPower(int x, int y)
{
    // logarithm function to calculate value
    int res1 = log(y) / log(x);
    double res2 = log(y) / log(x); // Note : this is double
 
    // compare to the result1 or result2 both are equal
    return (res1 == res2);
}
 
// Driven program
int main()
{
    cout << isPower(27, 729) << endl;
    return 0;
}

Java

// Java program to check given
// number y is power of x
 
class GFG
{
    static boolean isPower(int x,
                           int y)
    {
        // logarithm function to
        // calculate value
        int res1 = (int)Math.log(y) /
                   (int)Math.log(x);
                    
         // Note : this is double         
        double res2 = Math.log(y) /
                      Math.log(x);
     
        // compare to the result1 or
        // result2 both are equal
        return (res1 == res2);
    }
     
    // Driver Code
    public static void main(String args[])
    {
        if(isPower(27, 729))
            System.out.println("1");
        else
            System.out.println("0");
    }
}
 
// This code is contributed by Sam007

Python3

# Python3 program to check
# given number number y
import math
def isPower(x, y):
    # logarithm function to
    # calculate value
    res1 = math.log(y) // math.log(x);
     
    # Note : this is double
    res2 = math.log(y) / math.log(x);
 
    # compare to the result1 or
    # result2 both are equal
    return 1 if(res1 == res2) else 0;
 
# Driver Code
if __name__=='__main__':
    print(isPower(27, 729));
 
# This code is contributed by mits
# Improved by hsagarthegr8

C#

// C# program to check given
// number y is power of x
using System;
class GFG
{
static bool isPower(int x, int y)
{
    // logarithm function to
    // calculate value
    int res1 = (int)Math.Log(y) /
               (int)Math.Log(x);
                 
    // Note : this is double        
    double res2 = Math.Log(y) /
                  Math.Log(x);
 
    // compare to the result1 or
    // result2 both are equal
    return (res1 == res2);
}
 
// Driver Code
static void Main()
{
    if(isPower(27, 729))
        Console.WriteLine("1");
    else
        Console.WriteLine("0");
}
}
 
// This code is contributed by mits

的PHP


Java脚本


输出 :

1