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


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.

Steps

To solve this, we will follow these steps −

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

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
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;
}

Input

6, 16

Output

3

Updated on: 03-Mar-2022

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements