问题描述:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
解决方案:(ns euler-problem-12.core
(:use [clojure.contrib.math]))
(defn prime?
[num]
(every? #(or (> (rem num %) 0) (= num %)) (apply list (range 2 (inc (ceil (sqrt num)))))))
(defn next-prime
[num]
(loop [x (inc num)]
(if (prime? x)
x
(recur (inc x)))))
(defn prime-factors
[n]
(loop
[curent-n n, p 2, c [ ]]
(if (prime? curent-n)
(conj c curent-n)
(if (= 0 (rem curent-n p))
(recur (/ curent-n p) p (conj c p))
(recur curent-n (next-prime p) c)))))
(defn factors-count
[vprime-factors]
(loop
[last-factor nil, factors vprime-factors, counts [1], c-count 2]
(if (empty? factors)
(apply * counts)
(if (= last-factor (first factors))
(recur last-factor (rest factors) counts (inc c-count))
(recur (first factors) (rest factors) (conj counts c-count) 2)))))
(defn first-triangle-number-500-factors
[]
(loop
[n 2, t-n 1]
(if (> (factors-count (prime-factors (+ t-n n))) 500)
(+ t-n n)
(recur (inc n) (+ t-n n)))))
(first-triangle-number-500-factors)
答案:
76576500