Smallest and Largest N-digit perfect cubes
Last Updated :
22 Jun, 2022
Given an integer N, the task is to find the smallest and the largest N digit numbers which are also perfect cubes.
Examples:
Input: N = 2
Output: 27 64
27 and 64 are the smallest and the largest 2-digit numbers which are also perfect cubes.
Input: N = 3
Output: 125 729
Approach: For increasing values of N starting from N = 1, the series will go on like 8, 64, 729, 9261, ….. for the largest N-digit perfect cube whose Nth term will be pow(ceil(cbrt(pow(10, (n))))-1, 3).
And 1, 27, 125, 1000, ….. for the smallest N-digit perfect cube whose Nth term will be pow(ceil(cbrt(pow(10, (n – 1)))), 3).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void nDigitPerfectCubes( int n)
{
cout << pow ( ceil (cbrt( pow (10, (n - 1)))), 3) << " " ;
cout << ( int ) pow ( ceil (cbrt( pow (10, (n)))) - 1, 3);
}
int main()
{
int n = 3;
nDigitPerfectCubes(n);
return 0;
}
|
Java
class GFG {
static void nDigitPerfectCubes( int n)
{
int smallest = ( int )Math.pow(Math.ceil(Math.cbrt(Math.pow( 10 , (n - 1 )))), 3 );
System.out.print(smallest + " " );
int largest = ( int )Math.pow(Math.ceil(Math.cbrt(Math.pow( 10 , (n)))) - 1 , 3 );
System.out.print(largest);
}
public static void main(String args[])
{
int n = 3 ;
nDigitPerfectCubes(n);
}
}
|
Python3
from math import ceil
def nDigitPerfectCubes(n):
print ( pow (ceil(( pow ( 10 , (n - 1 ))) * *
( 1 / 3 )), 3 ), end = " " )
print ( pow (ceil(( pow ( 10 , (n))) * *
( 1 / 3 )) - 1 , 3 ))
if __name__ = = "__main__" :
n = 3
nDigitPerfectCubes(n)
|
C#
using System;
class GFG
{
static void nDigitPerfectCubes( int n)
{
int smallest = ( int )Math.Pow(Math.Ceiling(MathF.Cbrt(( float )Math.Pow(10, (n - 1)))), 3);
Console.Write(smallest + " " );
int largest = ( int )Math.Pow(Math.Ceiling(MathF.Cbrt(( float )Math.Pow(10, (n)))) - 1, 3);
Console.Write(largest);
}
static void Main()
{
int n = 3;
nDigitPerfectCubes(n);
}
}
|
PHP
<?php
function nDigitPerfectCubes( $n )
{
print (pow( ceil (pow(pow(10, ( $n - 1)),1/3)), 3). " " );
print ((int)pow( ceil (pow(pow(10, ( $n )),1/3)) - 1, 3));
}
$n = 3;
nDigitPerfectCubes( $n );
?>
|
Javascript
<script>
function nDigitPerfectCubes( n)
{
document.write( Math.pow(Math.ceil(Math.cbrt(Math.pow(10, (n - 1)))), 3) + " " );
document.write( Math.pow(Math.ceil(Math.cbrt(Math.pow(10, (n)))) - 1, 3));
}
let n = 3;
nDigitPerfectCubes(n);
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...