Count cubes of size K inscribed in a cube of size N
Last Updated :
16 Apr, 2021
Given two integers N and K, the task is to find the number of cubes of size K that can be contained in a cube of size N.
Examples:
Input: N = 2, K = 1
Output: 8
Explanation:
There are 8 cubes of size 1 that can be drawn inside the bigger cube of size 2.
Input: N = 5, K = 2
Output: 64
Explanation:
There are 64 cubes of size 2 can be drawn inside the bigger cube of size 5.
Approach: The key observation to solve the problem is that the number of cubes inside the cube of size N is (N2 * (N+1)2)/4. Therefore, the cubes of size K inside the cube of size N is:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int No_of_cubes( int N, int K)
{
int No = 0;
No = (N - K + 1);
No = pow (No, 3);
return No;
}
int main()
{
int N = 5;
int K = 2;
cout << No_of_cubes(N, K);
return 0;
}
|
Java
class GFG{
static int No_of_cubes( int N,
int K)
{
int No = 0 ;
No = (N - K + 1 );
No = ( int ) Math.pow(No, 3 );
return No;
}
public static void main(String[] args)
{
int N = 5 ;
int K = 2 ;
System.out.print(No_of_cubes(N, K));
}
}
|
Python3
def No_of_cubes(N, K):
No = 0
No = (N - K + 1 )
No = pow (No, 3 )
return No
N = 5
K = 2
print (No_of_cubes(N, K))
|
C#
using System;
class GFG{
static int No_of_cubes( int N, int K)
{
int No = 0;
No = (N - K + 1);
No = ( int )Math.Pow(No, 3);
return No;
}
public static void Main()
{
int N = 5;
int K = 2;
Console.Write(No_of_cubes(N, K));
}
}
|
Javascript
<script>
function No_of_cubes(N, K)
{
let No = 0;
No = (N - K + 1);
No = Math.pow(No, 3);
return No;
}
let N = 5;
let K = 2;
document.write(No_of_cubes(N, K));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...