WAP to print x raised to the power y
Answers
Answer:
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 xy where y > 1 and x > 0. x and y both are integers.
Examples :
Input: n = 8
Output: true
8 can be expressed as 23
Input: n = 49
Output: true
49 can be expressed as 72
Input: n = 48
Output: false
48 can't be expressed as xy
The idea is simple try all numbers x starting from 2 to square root of n (given number). For every x, try x^y where y starts from 2 and increases one by one until either x^y becomes n or greater than n.
Below is the implementation of above idea.
// C++ program to check if a given number can be expressed
// as power
#include <bits/stdc++.h>
using namespace std;
// Returns true if n can be written as x^y
bool isPower(unsigned n)
{
if (n==1) return true;
// Try all numbers from 2 to sqrt(n) as base
for (int x=2; x<=sqrt(n); x++)
{
unsigned y = 2;
unsigned p = pow(x, y);
// Keep increasing y while power 'p' is smaller
// than n.
while (p<=n && p>0)
{
if (p==n)
return true;
y++;
p = pow(x, y);
}
}
return false;
}
// Driver Program
int main()
{
for (int i =2; i<100; i++)
if (isPower(i))
cout << i << " ";
return 0;
Explanation:
One optimization in above solution is to avoid call to pow() by multiplying p with x one by one.
// C++ program to check if a given number can be expressed
// as power
#include <bits/stdc++.h>
using namespace std;
// Returns true if n can be written as x^y
bool isPower(unsigned int n)
{
// Base case
if (n <= 1) return true;
// Try all numbers from 2 to sqrt(n) as base
for (int x=2; x<=sqrt(n); x++)
{
unsigned p = x;
// Keep multiplying p with x while is smaller
// than or equal to x
while (p <= n)
{
p *= x;
if (p == n)
return true;
}
}
return false;
}
// Driver Program
int main()
{
for (int i =2; i<100; i++)
if (isPower(i))
cout << i << " ";
return 0;
} Output:
4 8 9 16 25 27 32 36 49 64 81
Alternate Implementation :
// C++ program to check if a given number can be expressed
// as power
#include <bits/stdc++.h>
using namespace std;
// Returns true if n can be written as x^y
bool isPower(unsigned n)
{
float p;
if (n <= 1)
return 1;
for (int i = 2; i <= sqrt(n); i++) {
p = log2(n) / log2(i);
if ((ceil(p) == floor(p)) && p > 1)
return true;
}
return false;
}
// Driver Program
int main()
{
for (int i = 2; i < 100; i++)
if (isPower(i))
cout << i << " ";
return 0;
}
Answer:
class power
{
public static void main(String[] args)
{
double x = 5,y = 2,z;
System.out.println("Math.pow(x,y)");
/*
z=Math.pow(x,y);
System.out.println(z);
*/
}
}
we have to initialize the variable and print the value
we can't print x^y
sorry
but this is a right way...
here is your answer above :)
hope it helps!
plz mark me as brainliest!
Explanation: