1 ! Copyright (C) 2009 Kye W. Shi.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: math math.functions math.primes project-euler.common
7 ! https://projecteuler.net/problem=87
12 ! The smallest number expressible as the sum of a prime square,
13 ! prime cube, and prime fourth power is 28. In fact, there are
14 ! exactly four numbers below fifty that can be expressed in such
17 ! 28 = 2^2 + 2^3 + 2^4
18 ! 33 = 3^2 + 2^3 + 2^4
19 ! 49 = 5^2 + 2^3 + 2^4
20 ! 47 = 2^2 + 3^3 + 2^4
22 ! How many numbers below fifty million can be expressed as the
23 ! sum of a prime square, prime cube, and prime fourth power?
27 :: prime-powers-less-than ( primes pow n -- prime-powers )
28 primes [ pow ^ ] map [ n <= ] filter ;
30 ! You may think to make a set of all possible sums of a prime
31 ! square and cube and then subtract prime fourths from numbers
32 ! ranging from 1 to 'n' to find this. As n grows large, this is
33 ! actually more inefficient!
35 ! Prime numbers grow ~ n / log n
37 ! Thus there are (n / log n)^(1/2) prime squares <= n,
38 ! (n / log n)^(1/3) prime cubes <= n,
39 ! and (n / log n)^(1/4) prime fourths <= n.
41 ! If we compute the cartesian product of these, this takes
42 ! O((n / log n)^(13/12)).
44 ! If we instead precompute sums of squares and cubes, and
45 ! iterate up to n, checking each fourth power against it, this
48 ! O(n * (n / log n)^(1/4)) = O(n^(5/4)/(log n)^(1/4)) >> O((n / log n)^(13/12))
50 ! When n = 50,000,000, the first equation is approximately 10
51 ! million and the second is approximately 2 billion.
53 :: prime-triples ( n -- answer )
54 n sqrt primes-upto :> primes
55 primes 2 n prime-powers-less-than :> primes^2
56 primes 3 n prime-powers-less-than :> primes^3
57 primes 4 n prime-powers-less-than :> primes^4
58 primes^2 primes^3 [ + ] cartesian-map concat
59 primes^4 [ + ] cartesian-map concat
60 [ n <= ] filter members length ;
64 :: euler087 ( -- answer )
65 50,000,000 prime-triples ;