# [Lisp] Largest Prime Factor in Clojure

Page 1 of 1

## 0 Replies - 1346 Views - Last Post: 20 April 2010 - 12:49 PM

### #1 erik.price Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

# [Lisp] Largest Prime Factor in Clojure

Posted 20 April 2010 - 12:49 PM

Description: Returns the largest prime factor of a number
```(defn lpf
"Finds the Largest Prime Factor of a number"
[num]
(cond
(< num 2) -1 ; return -1 if the given number is < 2 (2 is the first prime)
:else (loop [div (if (odd? num) ; bind the initial divisor to 2 if even, 3 if odd
3
2)
lim num] ; set the limit to number
(cond
; base case, divisor is greater than limit
(< (/ lim div) 1) (if (= (dec div) 2) ; special case to handle (lpf 2)
(dec div) ; return 2
(- div 2)) ; div will be 2 over from recursive calls, so sub
; if divisor divides evenly into limit
(= (rem lim div) 0) (recur (if(even? div)
(inc div) ; if divisor is even, make odd adding 1
(+ 2 div)) ; divisor is odd add 2 (e.g. 3 inc to 5)
(/ lim div)) ; set div as the result of lim / div
; if divisor doesn't divide evenly
:else (recur (if(even? div)
(inc div)  ; change divisor
(+ 2 div))
lim))))) ; limit stays the same
```

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }