Check if a number can be expressed as a^b | Set 2
Last Updated :
31 Aug, 2022
You have given a number n. Check if a number can be represented in the form of pow(a, b) (a^b).
Examples:
Input : 4
Output : Yes
22 = 4
Input : 12
Output : No
We have discussed two approaches in Check if a number can be expressed as x^y (x raised to power y). In this post, a more efficient solution is discussed. The idea is based on logarithmic.
Consider a no. N which needs
to be expressed in the form (a^b).
N = ab
Taking log both sides:
log (N) = b.log (a)
b = log(N)/log(a)
Keep this logic in mind to develop the most efficient solution mentioned below:
C++
#include <bits/stdc++.h>
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 ;
}
int main()
{
int n = 16;
cout << (isPower(n) ? "Yes" : "No" );
return 0;
}
|
Java
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 ;
}
public static void main(String[] args) {
int n = 16 ;
System.out.println(isPower(n) ? "Yes" : "No" );
}
}
|
Python 3
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
if __name__ = = "__main__" :
n = 16
if isPower(n) :
print ( "Yes" )
else :
print ( "No" )
|
C#
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 ;
}
public static void Main( string [] args)
{
int n = 16;
Console.WriteLine(isPower(n) ?
"Yes" : "No" );
}
}
|
PHP
<?php
function isPower( $a )
{
if ( $a == 1)
return true;
for ( $i = 2; $i * $i <= $a ; $i ++)
{
$val = log( $a ) / log( $i );
if (( $val - $val ) < 0.00000001)
return true;
}
return false;
}
$n = 16;
echo (isPower( $n ) ? "Yes" : "No" );
|
Javascript
<script>
function isPower(a)
{
if (a == 1)
return true ;
for (let i = 2; i * i <= a; i++) {
let val = Math.log(a) / Math.log(i);
if ((val - Math.floor(val)) < 0.00000001)
return true ;
}
return false ;
}
let n = 16;
document.write(isPower(n) ? "Yes" : "No" );
</script>
|
Time Complexity : O(sqrt(n))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...