Distribute N in a sequence having K-sized groups of 1, 2, 4 and so on
Last Updated :
17 Jan, 2022
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++
#include <bits/stdc++.h>
using namespace std;
int get( int N, int K)
{
int ans = 0;
int i = 0;
while (K * pow (2, i) < N) {
N -= (K * pow (2, i));
i++;
ans += K;
}
ans += N / ( pow (2, i));
return ans;
}
int main()
{
int N, K;
N = 35;
K = 5;
cout << get(N, K);
return 0;
}
|
Java
class GFG {
static int get( int N, int K)
{
int ans = 0 ;
int i = 0 ;
while (K * ( int )Math.pow( 2 , i) < N) {
N -= (K * ( int )Math.pow( 2 , i));
i++;
ans += K;
}
ans += N / ( int )(Math.pow( 2 , i));
return ans;
}
public static void main(String[] args)
{
int N, K;
N = 35 ;
K = 5 ;
System.out.print(get(N, K));
}
}
|
Python3
def get (N, K):
ans = 0 ;
i = 0 ;
while (K * ( 2 * * i) < N):
N - = (K * ( 2 * * i));
i + = 1
ans + = K;
ans + = (N / / ( 2 * * i));
return ans;
N = 35 ;
K = 5 ;
print (get(N, K));
|
C#
using System;
class GFG
{
static int get ( int N, int K)
{
int ans = 0;
int i = 0;
while (K * ( int )Math.Pow(2, i) < N) {
N -= (K * ( int )Math.Pow(2, i));
i++;
ans += K;
}
ans += N / ( int )(Math.Pow(2, i));
return ans;
}
public static void Main()
{
int N, K;
N = 35;
K = 5;
Console.Write( get (N, K));
}
}
|
Javascript
<script>
const get = (N, K) => {
let ans = 0;
let i = 0;
while (K * Math.pow(2, i) < N) {
N -= (K * Math.pow(2, i));
i++;
ans += K;
}
ans += parseInt(N / (Math.pow(2, i)));
return ans;
}
let N, K;
N = 35;
K = 5;
document.write(get(N, K));
</script>
|
Time Complexity: O(log(N)) where the base of log is K
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...