Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler 31: Why does this solution work?

Tags:

algorithm

I have been studying various solution to Project Euler question #31:

In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).

It is possible to make £2 in the following way: 1x£1 + 1x50p + 2x20p + 1x5p + 1x2p + 3x1p

How many different ways can £2 be made using any number of coins?

I am confused why this particular brute force solution works (source):

int target  = 200;
int ways = 0;

for (int a = target; a >= 0; a -= 200) {
    for (int b = a; b >= 0; b -= 100) {
        for (int c = b; c >= 0; c -= 50) {
            for (int d = c; d >= 0; d -= 20) {
                for (int e = d; e >= 0; e -= 10) {
                    for (int f = e; f >= 0; f -= 5) {
                        for (int g = f; g >= 0; g -= 2) {
                            ways++;
                        }
                    }
                }
            }
        }
    }
}

Based on this solution I would expect there to be one more nested for-loop at the innermost level that is decrementing by 1, for coins of 1p value.

For example, when do we count the scenario where 200p is made up of only 1p coins?

As it stands currently, the code leads to the correct answer. But if an additional for-loop was added then it would seem the answer should be much bigger. What am I missing?

like image 363
Anticipation Avatar asked May 16 '26 06:05

Anticipation


1 Answers

Because the for-loops count up ways to make a number <= 200, assuming the remainder is made up of 1p coins. For example, consider the first iteration, where a = b = c = d = e = f = g = 200, this is exactly the case you asked about explicitly, where 200p is made of all 1's.

like image 143
U2EF1 Avatar answered May 19 '26 04:05

U2EF1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!