]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/087/087.factor
factor: trim using lists
[factor.git] / extra / project-euler / 087 / 087.factor
1 USING: math math.functions math.primes
2 project-euler.common sequences sets ;
3
4 IN: project-euler.087
5
6 ! https://projecteuler.net/index.php?section=problems&id=87
7
8 ! DESCRIPTION
9 ! -----------
10
11 ! The smallest number expressible as the sum of a prime square,
12 ! prime cube, and prime fourth power is 28. In fact, there are
13 ! exactly four numbers below fifty that can be expressed in such
14 ! a way:
15
16 ! 28 = 2^2 + 2^3 + 2^4
17 ! 33 = 3^2 + 2^3 + 2^4
18 ! 49 = 5^2 + 2^3 + 2^4
19 ! 47 = 2^2 + 3^3 + 2^4
20
21 ! How many numbers below fifty million can be expressed as the
22 ! sum of a prime square, prime cube, and prime fourth power?
23
24 <PRIVATE
25
26 :: prime-powers-less-than ( primes pow n -- prime-powers )
27     primes [ pow ^ ] map [ n <= ] filter ;
28
29 ! You may think to make a set of all possible sums of a prime
30 ! square and cube and then subtract prime fourths from numbers
31 ! ranging from 1 to 'n' to find this. As n grows large, this is
32 ! actually more inefficient!
33 !
34 ! Prime numbers grow ~ n / log n
35 !
36 ! Thus there are (n / log n)^(1/2) prime squares <= n,
37 !                (n / log n)^(1/3) prime cubes   <= n,
38 !            and (n / log n)^(1/4) prime fourths <= n.
39 !
40 ! If we compute the cartesian product of these, this takes
41 ! O((n / log n)^(13/12)).
42 !
43 ! If we instead precompute sums of squares and cubes, and
44 ! iterate up to n, checking each fourth power against it, this
45 ! takes:
46 !
47 ! O(n * (n / log n)^(1/4)) = O(n^(5/4)/(log n)^(1/4)) >> O((n / log n)^(13/12))
48 !
49 ! When n = 50,000,000, the first equation is approximately 10
50 ! million and the second is approximately 2 billion.
51
52 :: prime-triples ( n -- answer )
53     n sqrt primes-upto                :> primes
54     primes 2 n prime-powers-less-than :> primes^2
55     primes 3 n prime-powers-less-than :> primes^3
56     primes 4 n prime-powers-less-than :> primes^4
57     primes^2 primes^3 [ + ] cartesian-map concat
58              primes^4 [ + ] cartesian-map concat
59     [ n <= ] filter members length ;
60
61 PRIVATE>
62
63 :: euler087 ( -- answer )
64     50,000,000 prime-triples ;
65
66 SOLUTION: euler087