Post date: Jan 01, 2017 3:8:47 PM
Akemashite omedetou, kotoshi mo yoroshiku.
"How many numbers under 50,000,000 are equal to the sum of a prime number squared, a prime number cubed, and a prime number to the fourth power?"
7072 squared is over 50 million. Naturally cubes and fourths are even bigger. So we know that no answer will use higher than 7071 cubed (plus some smaller numbers), 368 cubed, or 84 to the fourth power. This is a tiny number. No problem with a simple query.
-- A tiny sieve to get primes under 7072.
CREATE TABLE #Primes (i bigint not null primary key, s bigint null, c bigint null, f bigint null)
INSERT INTO #Primes (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)
; WITH Integers(i) AS
(
SELECT o.i +
(10 * d.i) +
(100 * h.i) +
(1000 * k.i)
FROM #Primes o
CROSS JOIN #Primes d
CROSS JOIN #Primes h
CROSS JOIN #Primes k
WHERE k.i <= 7
)
INSERT INTO #Primes (i)
SELECT i
FROM Integers
WHERE i >= 10
AND i < 7072
DELETE FROM #Primes WHERE i < 2
DECLARE @max int
SELECT @max = MAX(i) FROM #Primes
DECLARE @num int = 1
WHILE 1 = 1
BEGIN
SELECT @num = MIN(i)
FROM #Primes
WHERE i > @num
IF @num > SQRT(@max)
BREAK
DELETE FROM #Primes
WHERE i % @num = 0
AND i > @num
END -- While
-- The fourth value in SQL Server is only accurate to 12 digits (being a float). It goes over that. But we don't care. We only care about accuracy for numbers up to 50 million, 8 digits.
UPDATE #Primes
SET s = SQUARE(i)
, c = POWER(i, 3)
, f = POWER(i, 4)
SELECT COUNT(DISTINCT s.s + c.c + f.f)
FROM #Primes s
CROSS JOIN #Primes c
CROSS JOIN #Primes f
WHERE c.c < 50000000
AND f.f < 50000000
AND s.s + c.c + f.f < 50000000
DROP TABLE #Primes