Count number of triplets (a, b, c) from first N natural numbers such that a * b + c = N
Last Updated :
03 May, 2021
Given an integer N, the task is to count the triplets (a, b, c) from the first N natural numbers such that a * b + c = N.
Examples:
Input: N = 3
Output: 3
Explanation:
Triplets of the form a * b + c = N are { (1, 1, 2), (1, 2, 1), (2, 1, 1) }
Therefore, the required output is 3.
Input: N = 100
Output: 473
Approach: The problem can be solved based on the following observation:
For every possible pairs (a, b), If a * b < N, then only c exists. Therefore, count the pairs (a, b) whose product is less than N.
Follow the steps below to solve the problem:
- Initialize a variable, say cntTriplets, to store the count of triplets of first N natural numbers that satisfy the given condition.
- Iterate over the range [1, N – 1] using variable i and check if N % i == 0 or not. If found to be true, then update cntTriplets += (N / i) – 1.
- Otherwise, update cntTriplets += (N / i).
- Finally, print the value of cntTriplets.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findCntTriplet( int N)
{
int cntTriplet = 0;
for ( int i = 1; i < N; i++) {
if (N % i != 0) {
cntTriplet += N / i;
}
else {
cntTriplet += (N / i) - 1;
}
}
return cntTriplet;
}
int main()
{
int N = 3;
cout << findCntTriplet(N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findCntTriplet( int N)
{
int cntTriplet = 0 ;
for ( int i = 1 ; i < N; i++)
{
if (N % i != 0 )
{
cntTriplet += N / i;
}
else
{
cntTriplet += (N / i) - 1 ;
}
}
return cntTriplet;
}
public static void main(String[] args)
{
int N = 3 ;
System.out.println(findCntTriplet(N));
}
}
|
Python3
def findCntTriplet(N):
cntTriplet = 0 ;
for i in range ( 1 , N):
if (N % i ! = 0 ):
cntTriplet + = N / / i;
else :
cntTriplet + = (N / / i) - 1 ;
return cntTriplet;
if __name__ = = '__main__' :
N = 3 ;
print (findCntTriplet(N));
|
C#
using System;
class GFG
{
static int findCntTriplet( int N)
{
int cntTriplet = 0;
for ( int i = 1; i < N; i++)
{
if (N % i != 0)
{
cntTriplet += N / i;
}
else
{
cntTriplet += (N / i) - 1;
}
}
return cntTriplet;
}
public static void Main(String[] args)
{
int N = 3;
Console.WriteLine(findCntTriplet(N));
}
}
|
Javascript
<script>
function findCntTriplet(N)
{
let cntTriplet = 0;
for (let i = 1; i < N; i++)
{
if (N % i != 0)
{
cntTriplet += Math.floor(N / i);
}
else
{
cntTriplet += Math.floor(N / i) - 1;
}
}
return cntTriplet;
}
let N = 3;
document.write(findCntTriplet(N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...