Perfect cube greater than a given number
Given a number N, the task is to find the next perfect cube greater than N.
Examples:
Input: N = 6
Output: 8
8 is a greater number than 6 and
is also a perfect cube
Input: N = 9
Output: 27
Approach:
- Find the cube root of given N.
- Calculate its floor value using floor function in C++.
- Then add 1 to it.
- Print cube of that number.
Below is the implementation of the above approach:
C++
#include <cmath>
#include <iostream>
using namespace std;
int nextPerfectCube( int N)
{
int nextN = floor (cbrt(N)) + 1;
return nextN * nextN * nextN;
}
int main()
{
int n = 35;
cout << nextPerfectCube(n);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
static int nextPerfectCube( int N)
{
int nextN = ( int )Math.floor(Math.cbrt(N)) + 1 ;
return nextN * nextN * nextN;
}
public static void main(String args[])
{
int n = 35 ;
System.out.print(nextPerfectCube(n));
}
}
|
Python 3
from math import *
def nextPerfectCube(N) :
nextN = floor(N * * ( 1 / 3 )) + 1
return nextN * * 3
if __name__ = = "__main__" :
n = 35
print (nextPerfectCube(n))
|
C#
using System;
class GFG
{
static int nextPerfectCube( int N)
{
int nextN = ( int )Math.Floor(Math.Pow(N,
( double )1/3)) + 1;
return nextN * nextN * nextN;
}
public static void Main()
{
int n = 35;
Console.Write(nextPerfectCube(n));
}
}
|
PHP
<?php
function nextPerfectCube( $N )
{
$nextN = (int)( floor (pow( $N ,(1/3))) + 1);
return $nextN * $nextN * $nextN ;
}
$n = 35;
print (nextPerfectCube( $n ));
?>
|
Javascript
<script>
function nextPerfectCube(N)
{
let nextN = Math.floor(Math.cbrt(N)) + 1;
return nextN * nextN * nextN;
}
let n = 35;
document.write(nextPerfectCube(n));
</script>
|
Time Complexity: O(logN) because it using cbrt function
Auxiliary Space: O(1)
Last Updated :
12 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...