将 N 分配到具有 1、2、4 等 K 组大小的序列中
给定一个数字 N和一个整数K 。任务是按顺序分配N ,使得第一个 序列的K个数是2 0 ,接下来的K个数是2 1 ,依此类推,使得序列的和最多为N 。找到序列的最大尺寸。
例子:
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
方法:按照以下步骤解决问题:
- 让变量ans存储程序的输出。
- 进行从1 到 i的循环,计算K*pow(2, i) < N的序列大小。通过在每个循环中将K添加到 ans 并从N中减去K*pow(2, i) 。
- 剩余序列的大小通过将N/pow(2, i)添加到ans来计算。
下面是上述方法的实现:
C++
// C++ code to implement the above approach
#include
using namespace std;
// Function to find the size of sequence
int 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 code
int main()
{
int N, K;
N = 35;
K = 5;
cout << get(N, K);
return 0;
}
Java
// Java code to implement the above approach
class GFG {
// Function to find the size of sequence
static int 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 * (int)Math.pow(2, i) < N) {
N -= (K * (int)Math.pow(2, i));
i++;
ans += K;
}
// Calculate Size of remaining sequence
ans += N / (int)(Math.pow(2, i));
return ans;
}
// Driver code
public static void main(String[] args)
{
int N, K;
N = 35;
K = 5;
System.out.print(get(N, K));
}
}
// This code is contributed by ukasp.
Python3
# Python code to implement the above approach
# Function to find the size of sequence
def get (N, K):
ans = 0;
i = 0;
# Loop to calculate size of sequence
# upto which K*pow(2, i) < N.
while (K * (2 ** i) < N):
N -= (K * (2 ** i));
i += 1
ans += K;
# Calculate Size of remaining sequence
ans += (N // (2 ** i));
return ans;
# Driver code
N = 35;
K = 5;
print(get(N, K));
# This code is contributed by Saurabh Jaiswal
C#
// C# code to implement the above approach
using System;
class GFG
{
// Function to find the size of sequence
static int 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 * (int)Math.Pow(2, i) < N) {
N -= (K * (int)Math.Pow(2, i));
i++;
ans += K;
}
// Calculate Size of remaining sequence
ans += N / (int)(Math.Pow(2, i));
return ans;
}
// Driver code
public static void Main()
{
int N, K;
N = 35;
K = 5;
Console.Write(get(N, K));
}
}
// This code is contributed b Samim Hossain Mondal.
Javascript
输出
15
时间复杂度:O(log(N)),其中 log 的基数为 K
辅助空间:O(1)