C++ program to count number of minimum coins needed to get sum k

C++Server Side ProgrammingProgramming

Suppose we have two numbers n and k. We have unlimited number of coins worth values 1 to n. We want to take some values whose sum is k. We can select multiple same valued coins to get total sum k. We have to count the minimum number of coins needed to get the sum k.

So, if the input is like n = 6; k = 16, then the output will be 3, because (2 * 6) + 4.


To solve this, we will follow these steps −

c := (n + k - 1) / n
return c


Let us see the following implementation to get better understanding −

using namespace std;

int solve(int n, int k){
   int c=(n+k-1)/n;
   return c;
int main(){
   int n = 6;
   int k = 16;
   cout << solve(n, k) << endl;


6, 16


Updated on 03-Mar-2022 11:24:02