Reputation: 27
I am trying to solve the Chocolate Feast challenge on HackerRank:
Little Bob loves chocolate, and he goes to a store with $N in his pocket. The price of each chocolate is $C. The store offers a discount: for every M wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat?
Input Format: The first line contains the number of test cases, T. T lines follow, each of which contains three integers, N, C, and M.
Output Format: Print the total number of chocolates Bob eats.
Constraints:
1≤T≤1000
2≤N≤105
1≤C≤N
2≤M≤N
Sample input:
3
10 2 5
12 4 4
6 2 2
Sample Output:
6
3
5
Explanation In the first case, he can buy 5 chocolates with $10 and exchange the 5 wrappers to get one more chocolate. Thus, the total number of chocolates is 6.
In the second case, he can buy 3 chocolates for $12. However, it takes 4 wrappers to get one more chocolate. He can't avail the offer and hence the total number of chocolates remains 3.
In the third case, he can buy 3 chocolates for $6. Now he can exchange 2 of the 3 wrappers and get 1 additional piece of chocolate. Now he can use his 1 unused wrapper and the 1 wrapper of the new piece of chocolate to get one more piece of chocolate. So the total is 5.
Here is my attempt at a solution in C:
#include<stdio.h>
int main(){
int t; //total test cases
scanf("%d",&t);
for(int a0 = 0; a0 < t; a0++){
int n; //money
int c; //cost of 1 chocolate
int m; //no of wrappers to buy a new chocolate
scanf("%d %d %d",&n,&c,&m);
int tc=0,nw=0,nc=0,w=0;//tc=totalChocolates nw=newWrappers nc=newChocolates w=wrappers
tc=n/c;
w=tc;
while(w>=m){
nc=(w/m);
tc+=nc;
w-=m;
nw=w%m;
w+=nw;
}
printf("%d\n",tc);
}
return 0;
}
The problem is that my program passes some test cases whereas it fails in some others, but I am not able to find where the error is. Moreover for some other test the time taken is above 2 secs.
Test case
Input
Excepted output
Upvotes: 0
Views: 3458
Reputation: 213060
Your logic here is rather muddled:
while(w>=m){
nc=(w/m);
tc+=nc;
w-=m;
nw=w%m;
w+=nw;
}
If you change it to this then it passes all the test cases:
while(w>=m){
nc=(w/m); // how many additional bars can we buy ?
tc+=nc; // accumulate total bars purchased
w-=(nc*m); // deduct no of wrappers used to purchase additional bars
w+=nc; // accumulate additional wrappers
}
Upvotes: 3
Reputation: 75062
This program (before editing) outputs 10
instead of 9
for this input.
1
5 1 2
Try this in the while
loop:
m*nc
instead of m
from w
nc
instead of nw
to tc
Upvotes: 0