loop function is taking too long

Viewed 235

I'm trying to do a function who implements a sum of n cubes:

1^3 + 2^3 + 3^3 + ... + n^3 = sum

My function should receive a sum and return a n or -1 if n doesn't exists.

Some examples:

(find-n 9)   ; should return 2 because 1^3 + 2^3 = 9
(find-n 100) ; should return 4 because 1^3 + 2^3 + 3^3 + 4^3 = 100
(find-n 10)  ; should return -1

After some work I made these two functions:

; aux function
(defn exp-3 [base] (apply *' (take 3 (repeat base))))

; main function
(defn find-n [m]
  (loop [sum 0
         actual-base 0]
       (if (= sum m) 
           actual-base
           (if (> sum m)
               -1
               (recur (+' sum (exp-3 (inc actual-base))) (inc actual-base))))))

These functions are working properly but is taking too long to evaluate operations with BigNumbers, as example:

(def sum 1025247423603083074023000250000N)
(time (find-n sum))
; => "Elapsed time: 42655.138544 msecs"
; => 45001000

I'm asking this question to raise some advices of how can I make this function faster.

4 Answers
Related