Given a number N, the task is to find the previous perfect square and perfect cube smaller than N. Examples:
Examples :
Input : N = 6 Output : Perfect Square = 4 Perfect Cube = 1 Input : N = 30 Output : Perfect Square = 25 Perfect Cube = 27
Approach :
- Find the square root of given N.
- Calculate its floor value using floor function in C++.
- Then subtract 1 from it if N is already a perfect square.
- Print square of that number.
- Find the cube root of given N.
- Calculate its floor value using floor function in C++.
- Then subtract 1 from it if N is already a perfect cube.
- Print cube of that number.
Below is the implementation of above approach:
// C++ implementation of above approach
#include <iostream>
#include<cmath>
using namespace std;
// Function to find the previous perfect square
int previousPerfectSquare(int N)
{
int prevN = floor(sqrt(N)) ;
//If N is alreay a perfect square
//decrease prevN by 1.
if(prevN * prevN == N)
prevN -= 1;
return prevN * prevN;
}
// Function to find the previous perfect cube
int previousPerfectCube(int N)
{
int prevN = floor(cbrt(N)) ;
//If N is already a perfect cube
//decrease prevN by 1.
if(prevN * prevN * prevN == N)
prevN -= 1;
return prevN * prevN * prevN;
}
// Driver Code
int main()
{
int n = 30;
cout <<previousPerfectSquare(n)<<"\n";
cout <<previousPerfectCube(n)<<"\n";
return 0;
}