I need to solve a test question that asks to count how many apples can be eaten in total when X
apples are given as a start amount, Y
apples are eaten every time, and 1
apple is added every time apples are eaten.
My current solution uses a recursive function and therefore would cause an infinite loop if Y
is smaller than X
or if given X
is way large.
public class Apples
{
// Counts iterations. If we eat less than we add new every, it'll loop infinetely!
private static int _recursions;
private static int _applesRemaining;
private static int _applesEaten;
public static int CountApples(int startingAmount, int newEvery)
{
if (newEvery > startingAmount) newEvery = startingAmount;
Console.WriteLine("startingAmount: " + startingAmount + ", newEvery: " + newEvery);
_applesRemaining = startingAmount;
/* Eat 'newEvery' amount */
_applesRemaining -= newEvery;
_applesEaten += newEvery;
Console.WriteLine("Eat: " + newEvery + ", remaining: " + _applesRemaining);
/* Get one additional candy */
_applesRemaining += 1;
Console.WriteLine("Added 1.");
if (_applesRemaining > 1 && _recursions++ < 1000)
{
CountApples(_applesRemaining, newEvery);
}
else
{
if (_recursions > 1000) Console.WriteLine("ABORTED!");
/* Eat the one we've just added last. */
_applesEaten += 1;
}
return _applesEaten;
}
public static void Main(string[] args)
{
Console.WriteLine(CountApples(10, 2) + "\n");
}
}
How can I make this more efficient? There's probably a more elegant way to do this but I can't figure it out.
EDIT: Original test question text:
/**
* You are given startingAmount of Apples. Whenever you eat a certain number of
* apples (newEvery), you get an additional apple.
*
* What is the maximum number of apples you can eat?
*
* For example, if startingAmount equals 3 and newEvery equals 2, you can eat 5 apples in total:
*
* Eat 2. Get 1. Remaining 2.
* Eat 2. Get 1. Remaining 1.
* Eat 1.
*/