I am looking for a way to optimize this code so that it runs faster. I am trying to calculate the total items used, if for every x items used, you get one additional item to use.
This is the code I currently have. I get the correct result, but with a large amount of items, it is taking too long to calculate.
public static int TotalItems(int startingTotalItems, int newItemInterval)
{
int itemsUsed = 0;
int itemsUsedThisInterval = 0;
int totalItems = startingTotalItems;
while (totalItems > 0)
{
totalItems--;
itemsUsed++;
itemsUsedThisInterval++;
if (itemsUsedThisInterval == newItemInterval)
{
totalItems++;
itemsUsedThisInterval = 0;
}
}
return itemsUsed;
}
public static void Main(string[] args)
{
Console.WriteLine(TotalItems(3, 2));
}
Console output: 5
//-- psudo
// Start with 3 items
// Use 2 items
// Now I have 1 item plus I get 1 new additional item, giving a total of 2 items
// Use 2 items
// Now I have 0 items but since I used another 2 items, I get 1 more new additional item
// Use 1
// I have used a total of 5 items - Thisis the result
//--
I think the issue is the use of the while loop. I would think that there would be an efficient algorithm I could apply for this but but, so far, I have not had any luck finding one.
What my boss is saying is "Your code took too long to calculate an answer. Analyze how your code behaves when the input increases in size and see if you can make it work faster."