Algorithm for calculating the total cost in groups N
I have a limited supply of objects, and as the objects are purchased, the price increases accordingly in groups of N (each time N objects are bought, the price increases). When you're trying to purchase multiple properties, what's the easiest way to calculate the total cost?
Example:
I have 24 foo. For every N (use case 3) that was bought, the price increases by 1.
So if I buy 1 at price 1, there are 23 left and 2 are left at price 1.
After 1 has been bought, someone wants to buy 6. Well, the total cost would be = (2 * 1) + (3 * 2) + (1 * 3)
source to share
Borrowing RBarryYoung notation, the first N items are worth B each, the second N items are worth B + i each, the third N items are worth B + 2 * i each, etc.
To buy items X: Q: = X div N (gender division), whole groups are bought, plus R: = X mod N additional items. The first cost Q * N * (B + (B + (Q - 1) * I)) / 2, since with linearly increasing item costs, the average item cost is equal to the average cost of the first item, B and the last item cost, B + ( Q - 1) * I. The last items cost R * (B + Q * I), so the resulting function f (X) is
f(X) := (Q * N * (B + (B + (Q - 1) * I))) div 2 + R * (B + Q*I).
To compute the cost of elements (zero) indexed from X inclusive to X 'exclusive, use f(X') - f(X)
.
source to share