I'm working on problems at
projecteuler.net in Clojure.
There is a particular problem that my code doesn't seem to work for. The
problem is:
==================================
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?
========================================
I've written the following clojure code to solve it:
(defn triangle [n] (reduce + (range n)))
(defn factors [n] (conj
(filter #(= 0 (mod n %)) (range 1 (+ 1 (/ n 2))))n ))
(defn num-of-factors [n] (count (factors n)))
(def lazytri (lazy-seq (map triangle (range))))
(take 1 (filter #(> (num-of-factors %) 499) lazytri))
with the cutoff of 499, this runs forever as far as I can tell. In fact
it will work up to 100, but not at 200.
The following Java code quickly returns the same answer as the clojure
code for the same cutoffs, and quickly returns the correct answer for
the 499 cutoff.
Why doesn't my clojure code return for these larger values?
=================================================================
public class Triangles {
public static void main(String[] args){
int number = 0;
int i = 1;
while(numberOfDivisors(number) < 500){
number += i;
i++;
System.out.println(number);
}
}
private static int numberOfDivisors(int number){
int nod = 0;
int sqrt = (int) Math.sqrt(number);
for(int i = 1; i<= sqrt; i++){
if(number % i == 0){
nod += 2;
}
}
//Correction if the number is a perfect square
if (sqrt * sqrt == number) {
nod--;
}
return nod;
}
}