Count of sorted triplets (a, b, c) whose product is at most N
Given an integer N, the task is to find the count of triplets (a, b, c) such that a <= b <= c and a * b * c <= N.
Examples:
Input: N = 5
Output: 6
Explanation: The triplets that follow the required conditions are (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5) and (1, 2, 2). Hence the count of value triplets is 6.
Input: N = 20
Output: 40
Approach: The given problem can be solved based on the following observations:
- Since a <= b <=c, it can be observed that the value of a must lie in the range [1, N1/3].
- Similarly, for a given a the value of b must lie in the range [a, (N/a)1/2].
- Similarly, when the value of a and b is fixed, the value of c must lie in the range [b, N/(a*b)]. Hence the number of possible values of c is the count of integers in the range [b, N/(a*b)]. Therefore, for each valid a and b, the number of possible values of c are N/(a*b) – b + 1.
Therefore, using the above observations below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
long long validTriplets( int N)
{
long long ans = 0;
for ( long long a = 1; a * a * a <= N; a++) {
for ( long long b = a; a * b * b <= N; b++) {
ans += N / a / b - b + 1;
}
}
return ans;
}
int main()
{
int N = 5;
cout << validTriplets(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static long validTriplets( int N)
{
long ans = 0 ;
for ( long a = 1 ; a * a * a <= N; a++) {
for ( long b = a; a * b * b <= N; b++) {
ans += N / a / b - b + 1 ;
}
}
return ans;
}
public static void main(String[] args)
{
int N = 5 ;
System.out.print(validTriplets(N));
}
}
|
Python3
def validTriplets(N):
ans = 0 ;
for a in range ( 1 , int (N * * ( 1 / 3 )) + 1 ):
b = a;
while (a * b * b < = N):
ans + = N / a / b - b + 1 ;
b + = 1
return int (ans);
N = 5 ;
print (validTriplets(N));
|
C#
using System;
class GFG {
static long validTriplets( int N)
{
long ans = 0;
for ( long a = 1; a * a * a <= N; a++) {
for ( long b = a; a * b * b <= N; b++) {
ans += N / a / b - b + 1;
}
}
return ans;
}
public static void Main()
{
int N = 5;
Console.WriteLine(validTriplets(N));
}
}
|
Javascript
<script>
function validTriplets(N)
{
let ans = 0;
for (let a = 1; a * a * a <= N; a++)
{
for (let b = a; a * b * b <= N; b++)
{
ans += N / a / b - b + 1;
}
}
return Math.floor(ans);
}
let N = 5;
document.write(validTriplets(N));
</script>
|
Time Complexity: O(N2/3)
Auxiliary Space: O(1)
Last Updated :
24 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...