# Count all sub-sequences having product <= K – Recursive approach in C++

In this tutorial, we will be discussing a program to find the number of sub-sequences having product <= k.

For this we will be provided with an array and a value K. Our task is to find the number of sub sequences having their product as K.

## Example

Live Demo

#include <bits/stdc++.h>
#define ll long long
using namespace std;
//keeping count of discarded sub sequences
ll power(ll a, ll n){
if (n == 0)
return 1;
ll p = power(a, n / 2);
p = p * p;
if (n & 1)
p = p * a;
return p;
}
//recursive approach to count
void solve(int i, int n, float sum, float k,
float* a, float* prefix){
if (sum > k) {
discard_count += power(2, n - i);
return;
}
if (i == n)
return;
float rem = prefix[n - 1] - prefix[i];
if (sum + a[i] + rem > k)
solve(i + 1, n, sum + a[i], k, a, prefix);
if (sum + rem > k)
solve(i + 1, n, sum, k, a, prefix);
}
int countSubsequences(const int* arr,
int n, ll K){
float sum = 0.0;
float k = log2(K);
float prefix[n], a[n];
for (int i = 0; i < n; i++) {
a[i] = log2(arr[i]);
sum += a[i];
}
prefix = a;
for (int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + a[i];
}
ll total = power(2, n) - 1;
if (sum <= k) {
}
solve(0, n, 0.0, k, a, prefix);
}
int main() {
int arr[] = { 4, 8, 7, 2 };
int n = sizeof(arr) / sizeof(arr);
ll k = 50;
cout << countSubsequences(arr, n, k);
return 0;
}

## Output

9

Updated on: 17-Feb-2020

104 Views 