Given a positive integer N, the task is to find the number of triplets of positive integers (X, Y, Z), whose product is at most N.
Examples:
Input: N = 2
Output: 4
Explanation: Below are the triplets whose product is at most N(= 2):
- (1, 1, 1): Product is 1*1*1 = 1.
- (1, 1, 2): Product is 1*1*2 = 2.
- (1, 2, 1): Product is 1*2*1 = 2.
- (2, 1, 1): Product is 2*1*1 = 2.
Therefore, the total count is 4.
Input: 6
Output: 25
Naive Approach: The simplest approach to solve the given problem is to generate all possible triplets whose values lie over the range [0, N] and count those triplets whose product of values is at most N. After checking for all the triplets, print the total count obtained.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by generating all possible pairs (i, j) over the range [1, N] and increment the count of all possible pairs by N / (i * j). Follow the steps below to solve the problem:
- Initialize a variable, say ans, that stores the count of all possible triplets.
- Generate all possible pairs (i, j) over the range [1, N] and if the product of the pairs is greater than N, then check for the next pairs. Otherwise, increment the count of all possible pairs by N/(i*j).
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countTriplets( int N)
{
int ans = 0;
for ( int i = 1; i <= N; i++) {
for ( int j = 1; j <= N; j++) {
if (i * j > N)
break ;
ans += N / (i * j);
}
}
return ans;
}
int main()
{
int N = 10;
cout << countTriplets(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countTriplets( int N)
{
int ans = 0 ;
for ( int i = 1 ; i <= N; i++)
{
for ( int j = 1 ; j <= N; j++)
{
if (i * j > N)
break ;
ans += N / (i * j);
}
}
return ans;
}
public static void main(String[] args)
{
int N = 10 ;
System.out.print(countTriplets(N));
}
}
|
Python3
def countTriplets(N):
ans = 0
for i in range ( 1 , N + 1 ):
for j in range ( 1 , N + 1 ):
if (i * j > N):
break
ans + = N / / (i * j)
return ans
if __name__ = = "__main__" :
N = 10
print (countTriplets(N))
|
C#
using System;
class GFG{
static int countTriplets( int N)
{
int ans = 0;
for ( int i = 1; i <= N; i++)
{
for ( int j = 1; j <= N; j++)
{
if (i * j > N)
break ;
ans += N / (i * j);
}
}
return ans;
}
public static void Main(String[] args)
{
int N = 10;
Console.Write(countTriplets(N));
}
}
|
Javascript
<script>
function countTriplets( N){
let ans = 0;
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= N; j++) {
if (i * j > N)
break ;
ans += Math.floor(N / (i * j));
}
}
return ans;
}
let N = 10;
document.write( countTriplets(N));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1), since no extra space has been taken.