📌  相关文章
📜  N除以K的幂的商的总和不超过N

📅  最后修改于: 2021-04-17 15:07:21             🧑  作者: Mango

给定两个正整数NK ,任务是找出N除以K的幂的商之和,该商小于或等于N。

例子:

方法:想法是在K的当前乘方小于或等于N时迭代一个循环,并在每次迭代中始终将商与和相加。
请按照以下步骤解决问题:

  • 初始化一个变量,例如sum ,以存储所需的和。
  • 初始化一个变量,例如i = 1 (= K 0 ),以存储K的幂。
  • 迭代,直到i的值≤N,并执行以下操作:
    • 将由N除以i所得的商存储在变量X中
    • K添加XANS价值和乘获得K的下一个动力。
  • 打印总和的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate sum of
// quotients obtained by dividing
// N by powers of K <= N
int findSum(int N, int K)
{
    // Store the required sum
    int ans = 0;
    int i = 1;
 
    // Iterate until i exceeds N
    while (i <= N) {
 
        // Update sum
        ans += N / i;
 
        // Multiply i by K to
        // obtain next power of K
        i = i * K;
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given N and K
    int N = 10, K = 2;
    findSum(N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to calculate sum of
  // quotients obtained by dividing
  // N by powers of K <= N
  static void findSum(int N, int K)
  {
 
    // Store the required sum
    int ans = 0;
    int i = 1;
 
    // Iterate until i exceeds N
    while (i <= N)
    {
 
      // Update sum
      ans += N / i;
 
      // Multiply i by K to
      // obtain next power of K
      i = i * K;
    }
 
    // Print the result
    System.out.println(ans);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    // Given N and K
    int N = 10, K = 2;
    findSum(N, K);
  }
}
 
// This code is contributed by shubhamsingh10


Python3
# Python3 program for the above approach
 
# Function to calculate sum of
# quotients obtained by dividing
# N by powers of K <= N
def findSum(N, K):
   
    # Store the required sum
    ans = 0
    i = 1
 
    # Iterate until i exceeds N
    while (i <= N):
 
        # Update sum
        ans += N // i
 
        # Multiply i by K to
        # obtain next power of K
        i = i * K
 
    # Prthe result
    print (ans)
 
# Driver Code
if __name__ == '__main__':
   
    # Given N and K
    N, K = 10, 2
    findSum(N, K)
 
    # This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate sum of
// quotients obtained by dividing
// N by powers of K <= N
static void findSum(int N, int K)
{
 
    // Store the required sum
    int ans = 0;
    int i = 1;
     
    // Iterate until i exceeds N
    while (i <= N)
    {
         
        // Update sum
        ans += N / i;
         
        // Multiply i by K to
        // obtain next power of K
        i = i * K;
    }
     
    // Print the result
    Console.Write(ans);
}
 
// Driver code
static void Main()
{
     
    // Given N and K
    int N = 10, K = 2;
     
    findSum(N, K);
}
}
 
// This code is contributed by code_hunt


输出:
18

时间复杂度: O(log K (N))
辅助空间: O(1)