Find the previous perfect square and perfect cube of N

Updated

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 :

  1. Find the square root of given N.
  2. Calculate its floor value using floor function in C++.
  3. Then subtract 1 from it if N is already a perfect square.
  4. Print square of that number.
  5. Find the cube root of given N.
  6. Calculate its floor value using floor function in C++.
  7. Then subtract 1 from it if N is already a perfect cube.
  8. 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;
}

Output :

25
27
Comment
Mithlesh Upadhyay Published 11 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials