Post date: Jun 08, 2014 3:43:45 PM
"What is the sum of all amicable numbers under 10000?"
This is basic and benefits from a SQL approach. Just calculate a recordset with each number and the sum of its factors, and join it to itself where the sum of each equals the factors of the other, and where they aren't the same number.
CREATE TABLE #Integers (i BIGINT PRIMARY KEY NOT NULL)
; WITH Ten(i) AS
(
SELECT 0
UNION ALL
SELECT i + 1
FROM Ten
WHERE i < 9
)
INSERT INTO #Integers (i)
SELECT 1000 * k.i + 100 * h.i + 10 * t.i + o.i + 1
FROM Ten o
CROSS JOIN Ten t
CROSS JOIN Ten h
CROSS JOIN Ten k
; WITH Factors (i, factors) AS
(
SELECT i1.i, SUM(factors.i)
FROM #Integers i1
CROSS APPLY
(
SELECT i
FROM #Integers i2
WHERE i1.i % i = 0
AND i < SQRT(i1.i) + 1
AND i < i1.i
UNION
SELECT i1.i / i
FROM #Integers i2
WHERE i1.i % i = 0
AND i < SQRT(i1.i) + 1
AND i > 1
) factors
GROUP BY i1.i
)
SELECT SUM(f1.i)
FROM Factors f1
INNER JOIN Factors f2
ON f2.i = f1.factors
AND f2.factors = f1.i
WHERE f1.i <> f2.i
DROP TABLE #Integers