在 Project Euler 中练习使用 Mathematica! 😀

Problem 1

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.

注意 below 1000 不包括 1000。 先分别算出3、5、15的倍数和(均可写为等差数列求和),再将前两者相加减去后者 (重复相加的部分)。

(3 + 999)*333/2 + (5 + 995)*199/2 - (15 + 990)*66/2

<aside> 💡

233168

</aside>

Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

首先找到找到 4*10^6 的 n。利用迭代函数 NestWhile,反复应用某个操作直到条件不满足。

<aside> 🍉

匿名函数

使用 # 和 & 符号定义匿名函数,# 表示参数占位符,& 表示函数定义的结束符。

代码如下

NestWhile[# + 1 &, 1, Fibonacci[#] < 4*10^6 &];

第一个参数 # + 1 & 是每次迭代的操作:将输入值递增 1。第二个参数 1 是初始值 (从 n = 1 开始)。第三个参数 Fibonacci[#] < 4*10^6 & 是终止条件:当 Fibonacci[n] 首次不小于 400 万时停止。

然后将符合条件的数求和。

Total@Select[Fibonacci[#] & /@ Range[2, %], EvenQ]

当然可以直接写在一起,也不需要 NestWhile,如下

Total@Select[EvenQ]@Select[Table[Fibonacci[n], {n, 0, 100}], # < 4000000 &]

注意到 Fibonacci 实际上从 0 记的话,第 3 n 个数是偶数,即

Table[Fibonacci[ n], {n, 0, 15}]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}

因为奇数加奇数是偶数,偶数加奇数是奇数。