Given two positive integers N and K, the task is to find the sum of the quotients of the division of N by powers of K which are less than or equal to N.
Examples:
Input: N = 10, K = 2
Output: 18
Explanation:
Dividing 10 by 1 (= 20). Quotient = 10. Therefore, sum = 10.
Dividing 10 by 2 (= 21). Quotient = 5. Therefore, sum = 15.
Divide 10 by 4 (= 22). Quotient = 2. Therefore, sum = 17.
Divide 10 by 8 (= 23). Quotient = 1. Therefore, sum = 18.
Input: N = 5, K=2
Output: 8
Explanation:
Dividing 5 by 1 (= 20). Quotient = 5. Therefore, sum = 5.
Divide 5 by 2 (= 21). Quotient = 2. Therefore, sum = 7.
Divide 5 by 4 (= 22). Quotient = 1. Therefore, sum = 8.
Approach: The idea is to iterate a loop while the current power of K is less than or equal to N and keep adding the quotient to the sum in each iteration.
Follow the steps below to solve the problem:
- Initialize a variable, say sum, to store the required sum.
- Initialize a variable, say i = 1 (= K0) to store the powers of K.
- Iterate until the value of i ? N, and perform the following operations:
- Store the quotient obtained on dividing N by i in a variable, say X.
- Add the value of X to ans and multiply i by K to obtain the next power of K.
- Print the value of the sum as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findSum( int N, int K)
{
int ans = 0;
int i = 1;
while (i <= N) {
ans += N / i;
i = i * K;
}
cout << ans;
}
int main()
{
int N = 10, K = 2;
findSum(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void findSum( int N, int K)
{
int ans = 0 ;
int i = 1 ;
while (i <= N)
{
ans += N / i;
i = i * K;
}
System.out.println(ans);
}
public static void main(String[] args)
{
int N = 10 , K = 2 ;
findSum(N, K);
}
}
|
Python3
def findSum(N, K):
ans = 0
i = 1
while (i < = N):
ans + = N / / i
i = i * K
print (ans)
if __name__ = = '__main__' :
N, K = 10 , 2
findSum(N, K)
|
C#
using System;
class GFG{
static void findSum( int N, int K)
{
int ans = 0;
int i = 1;
while (i <= N)
{
ans += N / i;
i = i * K;
}
Console.Write(ans);
}
static void Main()
{
int N = 10, K = 2;
findSum(N, K);
}
}
|
Javascript
<script>
function findSum(N, K)
{
var ans = 0;
var i = 1;
while (i <= N) {
ans += Math.floor(N / i);
i = i * K;
}
document.write(ans);
}
var N = 10, K = 2;
findSum(N, K);
</script>
|
Time Complexity: O(logK(N))
Auxiliary Space: O(1)