Check if a number can be expressed as x^y (x raised to power y)
Given a positive integer n, find if it can be expressed as x^y where y > 1 and x > 0. x and y both are integers.
Examples :
Input: n = 8
Output: true
8 can be expressed as 2^3
Input: n = 49
Output: true
49 can be expressed as 7^2
Input: n = 48
Output: false
48 can't be expressed as x^y
We have discussed two different approaches in below post.
Check if a number can be expressed as x^y (x raised to power y).
The idea is find Log n in different bases from 2 to square root of n. If Log n for a base becomes integer then result is true, else result is false.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPower(unsigned int n)
{
for (int x=2; x<=sqrt(n); x++) {
float f = log(n) / log(x);
if ((f - (int)f) == 0.0)
return true;
}
return false;
}
int main()
{
for (int i = 2; i < 100; i++)
if (isPower(i))
cout << i << " ";
return 0;
}
|
Java
class GFG {
static boolean isPower(int n)
{
for (int x = 2; x <=
(int)Math.sqrt(n); x++)
{
float f = (float)Math.log(n) /
(float) Math.log(x);
if ((f - (int)f) == 0.0)
return true;
}
return false;
}
public static void main(String args[])
{
for (int i = 2; i < 100; i++)
if (isPower(i))
System.out.print( i + " ");
}
}
|
Python3
import math
def isPower(n):
for x in range(2,int(math.sqrt(n)) + 1):
f = math.log(n) / math.log(x);
if ((f - int(f)) == 0.0):
return True;
return False;
for i in range(2, 100):
if (isPower(i)):
print(i, end = " ");
|
C#
using System;
class GFG
{
static bool isPower(int n)
{
for (int x = 2;
x <= (int)Math.Sqrt(n); x++)
{
float f = (float)Math.Log(n) /
(float) Math.Log(x);
if ((f - (int)f) == 0.0)
return true;
}
return false;
}
public static void Main()
{
for (int i = 2; i < 100; i++)
if (isPower(i))
Console.Write( i + " ");
}
}
|
PHP
<?php
function isPower($n)
{
for ($x = 2; $x <= sqrt($n); $x++)
{
$f = log($n) / log($x);
if (($f - (int)$f) == 0.0)
return true;
}
return false;
}
for ($i = 2; $i < 100; $i++)
if (isPower((int)$i))
echo $i." ";
?>
|
Javascript
<script>
function isPower(n) {
for (x = 2; x <= parseInt( Math.sqrt(n)); x++)
{
var f = Math.log(n) / Math.log(x);
if ((f - parseInt( f)) == 0.0)
return true;
}
return false;
}
for (i = 2; i < 100; i++)
if (isPower(i))
document.write(i + " ");
</script>
|
Output: 4 8 9 16 25 27 32 36 49 64 81
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.