Distribute N in a sequence having K-sized groups of 1, 2, 4 and so on
Given a number N, and an integer K. The task is to distribute N in a sequence such that the first K numbers of the sequence is 20, the next K numbers are 21, and so on such that the sum of the sequence is at most N. Find the largest size of the sequence.
Examples:
Input: N = 35, K = 5
Output: 15
Explanation: The sequence is 1 1 1 1 1 2 2 2 2 2 4 4 4 4 4.
The summation of the sequence is 35.Input: N = 16, K = 3
Output: 8
Explanation: The sequence is 1 1 1 2 2 2 4.
The summation of the sequence is 13, which is less that 16
Approach: Follow the below steps to solve the problem:
- Let variable ans store the output of the program.
- Take a loop from 1 to i, which calculates the size of the sequence up to which K*pow(2, i) < N. By adding K to ans and subtracting K*pow(2, i) from N in each loop.
- The size of the remaining sequence is calculated by adding N/pow(2, i) to ans.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std;// Function to find the size of sequenceint get(int N, int K){ int ans = 0; int i = 0; // Loop to calculate size of sequence // upto which K*pow(2, i) < N. while (K * pow(2, i) < N) { N -= (K * pow(2, i)); i++; ans += K; } // Calculate Size of remaining sequence ans += N / (pow(2, i)); return ans;}// Driver codeint main(){ int N, K; N = 35; K = 5; cout << get(N, K); return 0;} |
Javascript
<script> // JavaScript code to implement the above approach // Function to find the size of sequence const get = (N, K) => { let ans = 0; let i = 0; // Loop to calculate size of sequence // upto which K*pow(2, i) < N. while (K * Math.pow(2, i) < N) { N -= (K * Math.pow(2, i)); i++; ans += K; } // Calculate Size of remaining sequence ans += parseInt(N / (Math.pow(2, i))); return ans; } // Driver code let N, K; N = 35; K = 5; document.write(get(N, K));// This code is contributed by rakeshsahni</script> |
15
Time Complexity: O(log(N)) where the base of log is K
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

