I was creating a very simple program that determines how many coins you need to return the change to a client, using a greedy algorithm. The algorithm is really obvious, you just need to determine which is the bigger coin you can use, subtract its value from the change and update the coins counter.
I have thought of two really similar implementations.
note: changeInt is the change, multiplied by 100 and converted into a integer.
1) A single "complex" loop
while(changeInt != 0) {
if(changeInt - 25 >= 0){
changeInt -= 25;
coins++;
}
else if(changeInt - 10 >= 0){
changeInt -= 10;
coins++;
}
else if(changeInt - 5 >= 0){
changeInt -= 5;
coins++;
}
else if(changeInt - 1 >= 0){
changeInt -= 1;
coins++;
}
}
2) Multiple simple loops
while(changeInt - 25 >= 0)
{
changeInt -= 25;
coins++;
}
while(changeInt - 10 >= 0)
{
changeInt -= 10;
coins++;
}
while(changeInt - 5 >= 0)
{
changeInt -= 5;
coins++;
}
while(changeInt - 1 >= 0)
{
changeInt -= 1;
coins++;
}
Now, I know the performance will probably be similar in both cases, since the algorithm is the same, but I was wondering which approach is better.
The single loop is the first idea I came up with, then I thought of the second method and it intuitively seems better to me.
I don't really care about my exact scenario, I'm more interested in the general one (several simple loops vs few more complex loops)
1) Which approach is better in terms of performance?
2) Is the difference noticeable, at least when working with huge numbers?
3) Is one approach significantly more readable than the other? (not sure if I can ask that here)
Thank you!