Prime Power Triples
May 22, 2020
The easy brute force calculation uses three loops; the trick is that some numbers can be generated in more than one way, so they must be collected in a set instead of simply being counted:
(define (euler87 n) (length (unique = (sort < (list-of s (a in (primes (iroot 2 n))) (b in (primes (iroot 3 n))) (c in (primes (iroot 4 n))) (s is (+ (* a a) (* b b b) (* c c c c))) (< s n))))))
We collect solutions in a list, then sort, cast out duplicates, and count. Here’s an example:
> (euler87 50) 4
You can run the program at https://ideone.com/B8JkdH.
Nifty little drill. Here is my take on it using Julia 1.4.1: https://pastebin.com/DVjwfbAx
The original approach I took was way too sluggish, so I ended up using a slicker one. There is also a verbose option for viewing the specific combinations: main(n, true), where n is the maximum integer to explore (in this case 50 000 000). The default for this parameter is false.
Glad the blog is back! Cheers
Easy to solve by brute force, once you realise that there are not that many prime powers to look at.
Welcome back! Hope all is well with everybody.
Not sure I like those multiple calls to primerange etc. Here’s another Python solution that generates a single list of prime numbers. Takes a couple of seconds for the Euler problem (here we just count up to a million):
Very glad to hear you are well and that things are settling down somewhat.
Here’s my solution in Python, using a standard Sieve of Eratosthenes and precalculating the required prime powers. Runs in about half a second on my desktop.
A solution in (not necessarily well-written) Icon. Also, note that prime-power triples aren’t unique; for example, 210 = 11^2 + 2^3 + 3^4 = 2^2 + 5^3 + 3^4. Code that doesn’t handle duplicates is producing incorrect counts.
Here’s a solution in Python.
Here’s a refactored version of my last solution.
Here’s another refactor to make it shorter, at the cost of readability.