Number of times the largest Perfect Cube can be subtracted from N
Last Updated :
17 Oct, 2022
Given a number N, at every step, subtract the largest perfect cube( ? N) from N. Repeat this step while N > 0. The task is to count the number of steps that can be performed.
Examples:
Input: N = 100
Output: 4
First step, 100 – (4 * 4 * 4) = 100 – 64 = 36
Second step, 36 – (3 * 3 * 3) = 36 – 27 = 9
Third step, 9 – (2 * 2 * 2) = 9 – 8 = 1
Fourth step, 1 – (1 * 1 * 1) = 1 – 1 = 0
Input: N = 150
Output: 5
First step, 150 – (5 * 5 * 5) = 150 – 125 = 25
Second step, 25 – (2 * 2 * 2) = 25 – 8 = 17
Third step, 17 – (2 * 2 * 2) = 17 – 8 = 9
Fourth step, 9 – (2 * 2 * 2) = 9 – 8 = 1
Fifth step, 1 – (1 * 1 * 1) = 1 – 1 = 0
Approach:
- Get the number from which the largest perfect cube has to be reduced.
- Find the cube root of the number and convert the result as an integer. The cube root of the number might contain some fraction part after the decimal, which needs to be avoided.
- Subtract the cube of the integer found in the previous step. This would remove the largest possible perfect cube from the number in the above step.
N = N - ((int) ?N)3
- Repeat the above two steps with the reduced number, till it is greater than 0.
- Print the number of times a perfect cube has been reduced from N. This is the final result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSteps( int n)
{
int steps = 0;
while (n) {
int largest = cbrt(n);
n -= (largest * largest * largest);
steps++;
}
return steps;
}
int main()
{
int n = 150;
cout << countSteps(n);
return 0;
}
|
Java
class GFG{
static int countSteps( int n)
{
int steps = 0 ;
while (n > 0 ) {
int largest = ( int ) Math.cbrt(n);
n -= (largest * largest * largest);
steps++;
}
return steps;
}
public static void main(String[] args)
{
int n = 150 ;
System.out.print(countSteps(n));
}
}
|
Python3
from math import floor
def countSteps(n):
steps = 0
while (n):
largest = floor(n * * ( 1 / 3 ))
n - = (largest * largest * largest)
steps + = 1
return steps
n = 150
print (countSteps(n))
|
C#
using System;
class GFG{
static int countSteps( int n)
{
int steps = 0;
while (n > 0) {
int largest = ( int ) Math.Pow(n,( double )1/3);
n -= (largest * largest * largest);
steps++;
}
return steps;
}
public static void Main(String[] args)
{
int n = 150;
Console.Write(countSteps(n));
}
}
|
Javascript
<script>
function countSteps(n)
{
let steps = 0;
while (n)
{
let largest = Math.floor(Math.cbrt(n));
n -= (largest * largest * largest);
steps++;
}
return steps;
}
let n = 150;
document.write(countSteps(n));
</script>
|
Time complexity: O(logn), as using inbuilt cbrt function
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...