Skip to content

Instantly share code, notes, and snippets.

@kirankulkarni
Created December 14, 2010 11:52
Show Gist options
  • Save kirankulkarni/740316 to your computer and use it in GitHub Desktop.
Save kirankulkarni/740316 to your computer and use it in GitHub Desktop.
Finds nthroot of given number
(ns kk_samples.nthroot)
(defn abs
"Calculate the absolute value of number"
[n]
(if (neg? n)
(* -1 n)
n))
(defn pow
"Calculates nth power of a number"
[number exponent]
(if (zero? exponent)
1
(* number (pow number (- exponent 1)))))
(defn isroot?
"Tests if root is close enough to real nth root of number"
[number n root]
(let [diff (- (pow root n) number)]
(if (< (abs diff) 0.001)
true
false)))
(defn nthroot
"finds the nthroot of the given number"
[number n]
(loop [root 1.0]
(if(isroot? number n root)
root
(recur (/ (+ (* root (- n 1)) (/ number (pow root (- n 1)))) n)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment