Check if a number can be expressed as x^y
PROBLEM :
Given a positive integer n, find if it can be expressed as xy where y > 1 and x > 0 and x and y both are both integers.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow . Each test cases contains an integer N.
Output:
For each test case in a new line print 1 if the number can be expressed as xy else print 0.
Constraints:
1<=T<=1000
1<=n<=100
Example:
Input:
2
8
5
Output:
1
0
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<math.h>
bool expressedXY(int ) ;
int main()
{
int t,no ;
cin>>t ;
while(t--)
{
cin>>no ;
cout<<(expressedXY(no))<<endl ;
}
return 0;
}
bool expressedXY(int no)
{
if(no==1)
return true ;
int x,y,curr;
for(x=2;x<=sqrt(no);x++)
{
y=2 ;
curr=pow(x,y) ;
while(curr<=no)
{
if(curr==no)
return true ;
else
{
y++ ;
curr=pow(x,y) ;
}
}
}
return false ;
}
---------------------------------------------------------------------------------
Given a positive integer n, find if it can be expressed as xy where y > 1 and x > 0 and x and y both are both integers.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow . Each test cases contains an integer N.
Output:
For each test case in a new line print 1 if the number can be expressed as xy else print 0.
Constraints:
1<=T<=1000
1<=n<=100
Example:
Input:
2
8
5
Output:
1
0
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<math.h>
bool expressedXY(int ) ;
int main()
{
int t,no ;
cin>>t ;
while(t--)
{
cin>>no ;
cout<<(expressedXY(no))<<endl ;
}
return 0;
}
bool expressedXY(int no)
{
if(no==1)
return true ;
int x,y,curr;
for(x=2;x<=sqrt(no);x++)
{
y=2 ;
curr=pow(x,y) ;
while(curr<=no)
{
if(curr==no)
return true ;
else
{
y++ ;
curr=pow(x,y) ;
}
}
}
return false ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment