# Project Euler, first problem: "Multiples of 3 and 5"¶

    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.

Let's create a predicate that returns `True` if a number is a multiple of 3 or 5 and `False` otherwise.

First we write `multiple-of` which take two numbers and return true if the first is a multiple of the second. We use the `mod` operator, convert the remainder to a Boolean value, then invert it to get our answer:

In [1]:

    [multiple-of mod bool not] inscribe

Next we can use that with `app2` to get both Boolean values (for 3 and 5) and the `or` them. (We use `popd` to get rid of the original number):

In [2]:

    [P 3 5 [multiple-of] app2 or popd] inscribe

In [3]:

    [6 7 8 9 10] [P] map

    [true false false true true]

In [4]:

    clear

Given the predicate function `P` a suitable program is:

    PE1 == 1000 range [P] filter sum

This function generates a list of the integers from 0 to 999, filters that list by `P`, and then sums the result.

Logically this is fine, but pragmatically we are doing more work than we should be; we generate one thousand integers but actually use less than half of them. A better solution would be to generate just the multiples we want to sum, and to add them as we go rather than storing them and adding summing them at the end.

At first I had the idea to use two counters and increase them by three and five, respectively. This way we only generate the terms that we actually want to sum. We have to proceed by incrementing the counter that is lower, or if they are equal, the three counter, and we have to take care not to double add numbers like 15 that are multiples of both three and five.

This seemed a little clunky, so I tried a different approach.

Consider the first few terms in the series:

    3 5 6 9 10 12 15 18 20 21 ...

Subtract each number from the one after it (subtracting 0 from 3):

    3 5 6 9 10 12 15 18 20 21 24 25 27 30 ...
    0 3 5 6  9 10 12 15 18 20 21 24 25 27 ...
    -------------------------------------------
    3 2 1 3  1  2  3  3  2  1  3  1  2  3 ...

You get this lovely repeating palindromic sequence:

    3 2 1 3 1 2 3

To make a counter that increments by factors of 3 and 5 you just add these differences to the counter one-by-one in a loop.

To make use of this sequence to increment a counter and sum terms as we go we need a function that will accept the sum, the counter, and the next term to add, and that adds the term to the counter and a copy of the counter to the running sum. This function will do that:

    PE1.1 == + [+] dupdip

In [5]:

    [PE1.1 + [+] dupdip] inscribe

In [6]:

    0 0 3 PE1.1

    3 3

In [7]:

    clear

    0 0 [3 2 1 3 1 2 3] [PE1.1] step

    60 15

So one `step` through all seven terms brings the counter to 15 and the total to 60.

In [8]:

    clear

    1000 15 div

    66

In [9]:

    15 *

    990

That means we want to run the full list of numbers sixty-six times to get to 990 and then, obviously, the first four numbers 3 2 1 3 to get to 999.

In [10]:

    clear

    [PE1 0 0 66 [[3 2 1 3 1 2 3] [PE1.1] step] times [3 2 1 3] [PE1.1] step pop] inscribe

    PE1

    233168

This form uses no extra storage and produces no unused summands. It's good but there's one more trick we can apply. The list of seven terms takes up at least seven bytes. But notice that all of the terms are less than four, and so each can fit in just two bits. We could store all seven terms in just fourteen bits and use masking and shifts to pick out each term as we go. This will use less space and save time loading whole integer terms from the list.

        3  2  1  3  1  2  3
    0b 11 10 01 11 01 10 11 == 14811

In [11]:

    clear

In [12]:

    [PE1.2 [3 & PE1.1] dupdip 2 >>] inscribe

In [ ]:

    0 0 14811 PE1.2

In [ ]:

    V('3 3 3702 PE1.2')

In [ ]:

    V('0 0 14811 7 [PE1.2] times pop')

And so we have at last:

In [ ]:

    define('PE1 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop')

In [ ]:

    J('PE1')

Let's refactor.

      14811 7 [PE1.2] times pop
      14811 4 [PE1.2] times pop
      14811 n [PE1.2] times pop
    n 14811 swap [PE1.2] times pop

In [ ]:

    define('PE1.3 14811 swap [PE1.2] times pop')

Now we can simplify the definition above:

In [ ]:

    define('PE1 0 0 66 [7 PE1.3] times 4 PE1.3 pop')

In [ ]:

    J('PE1')

Here's our joy program all in one place. It doesn't make so much sense, but if you have read through the above description of how it was derived I hope it's clear.

    PE1.1 == + [+] dupdip
    PE1.2 == [3 & PE1.1] dupdip 2 >>
    PE1.3 == 14811 swap [PE1.2] times pop
    PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop

# Generator Version¶

It's a little clunky iterating sixty-six times though the seven numbers then four more. In the Generator Programs notebook we derive a generator that can be repeatedly driven by the `x` combinator to produce a stream of the seven numbers repeating over and over again.

In [ ]:

    define('PE1.terms [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]')

In [ ]:

    J('PE1.terms 21 [x] times')

We know from above that we need sixty-six times seven then four more terms to reach up to but not over one thousand.

In [ ]:

    J('7 66 * 4 +')

### Here they are...¶

In [ ]:

    J('PE1.terms 466 [x] times pop')

### ...and they do sum to 999.¶

In [ ]:

    J('[PE1.terms 466 [x] times pop] run sum')

Now we can use `PE1.1` to accumulate the terms as we go, and then `pop` the generator and the counter from the stack when we're done, leaving just the sum.

In [ ]:

    J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop')

# A little further analysis renders iteration unnecessary.¶

Consider finding the sum of the positive integers less than or equal to ten.

In [ ]:

    J('[10 9 8 7 6 5 4 3 2 1] sum')

Instead of summing them, observe:

      10  9  8  7  6
    +  1  2  3  4  5
    ---- -- -- -- --
      11 11 11 11 11

      11 * 5 = 55

From the above example we can deduce that the sum of the first N positive integers is:

    (N + 1) * N / 2

(The formula also works for odd values of N, I'll leave that to you if you want to work it out or you can take my word for it.)

In [ ]:

    define('F dup ++ * 2 floordiv')

In [ ]:

    V('10 F')

## Generalizing to Blocks of Terms¶

We can apply the same reasoning to the PE1 problem.

Between 0 and 990 inclusive there are sixty-six "blocks" of seven terms each, starting with:

    [3 5 6 9 10 12 15]

And ending with:

    [978 980 981 984 985 987 990]

If we reverse one of these two blocks and sum pairs...

In [ ]:

    J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip')

In [ ]:

    J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map')

(Interesting that the sequence of seven numbers appears again in the rightmost digit of each term.)

In [ ]:

    J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum')

Since there are sixty-six blocks and we are pairing them up, there must be thirty-three pairs, each of which sums to 6945. We also have these additional unpaired terms between 990 and 1000:

    993 995 996 999

So we can give the "sum of all the multiples of 3 or 5 below 1000" like so:

In [ ]:

    J('6945 33 * [993 995 996 999] cons sum')

It's worth noting, I think, that this same reasoning holds for any two numbers $n$ and $m$ the multiples of which we hope to sum. The multiples would have a cycle of differences of length $k$ and so we could compute the sum of $Nk$ multiples as above.

The sequence of differences will always be a palidrome. Consider an interval spanning the least common multiple of $n$ and $m$:

    |   |   |   |   |   |   |   |
    |      |      |      |      |

Here we have 4 and 7, and you can read off the sequence of differences directly from the diagram: 4 3 1 4 2 2 4 1 3 4.

Geometrically, the actual values of $n$ and $m$ and their lcm don't matter, the pattern they make will always be symmetrical around its midpoint. The same reasoning holds for multiples of more than two numbers.

# The Simplest Program¶

Of course, the simplest joy program for the first Project Euler problem is just:

    PE1 == 233168

Fin.