📜  查找给定的整数是否为3的幂

📅  最后修改于: 2021-04-27 22:57:31             🧑  作者: Mango

给定一个正整数,编写一个函数以查找是否为3的幂。
例子:

Input : 3
Output :Yes

Input :6
Output :No

方法:
逻辑很简单。除3的幂以外的任何整数都可以除以3的最高幂3的值,该整数可以容纳3 ^ 19 = 1162261467(假设整数使用32位存储)将提醒非零。

C++
// C++ program to check if a number is power
// of 3 or not.
#include 
 
// Returns true if n is power of 3, else false
bool check(int n)
{
    if (n <= 0)
        return false;
    /* The maximum power of 3 value that
       integer can hold is 1162261467 ( 3^19 ) .*/
    return 1162261467 % n == 0;
}
 
// Driver code
int main()
{
    int n = 9;
    if (check(n))
        printf("Yes");
    else
        printf("No");
 
    return 0;
}


Java
// Java program to check if a number is power
// of 3 or not.
public class Power_3 {
 
    // Returns true if n is power of 3, else false
    static boolean check(int n)
    {
        /* To prevent
        java.lang.ArithmeticException: / by zero and
        negative n */
        if (n <= 0)
            return false;
        /* The maximum power of 3 value that
           integer can hold is 1162261467 ( 3^19 ) .*/
        return 1162261467 % n == 0;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int n = 9;
        if (check(n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh


Python
# Python program to check if a number is power
# of 3 or not.
  
# Returns true if n is power of 3, else false
def check(n):
    """ The maximum power of 3 value that
       integer can hold is 1162261467 ( 3^19 ) ."""
    return 1162261467 % n == 0
  
# Driver code
n = 9
if (check(n)):
    print ("Yes")
else:
    print ("No")
 
# This code is contributed by Sachin Bisht


C#
// C# program to check if a number
// is power of 3 or not.
using System;
 
public class GFG {
 
    // Returns true if n is power
    // of 3, else false
    static bool check(int n)
    {
        if (n <= 0)
            return false;
        /* The maximum power of 3
        value that integer can hold
        is 1162261467 ( 3^19 ) .*/
        return 1162261467 % n == 0;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 9;
        if (check(n))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
 
// This code is contributed by
// nitin mittal.


PHP


Javascript


输出:

Yes

时间复杂度: O(1)