/
core.clj
66 lines (54 loc) · 1.85 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(ns euler.core
(:require [clojure.string :as str]
[clojure.set :as set])
(:use [clojure.contrib.math]))
;;;; General Math Functions
(defn square [num]
"Returns the square of a given number"
(* num num))
(defn divisors [num]
"Returns a list of the divisors of given number"
(filter #(zero? (mod num %)) (range 1 (inc (/ num 2)))))
;;;; Prime Numbers
(defn is-prime? [n]
"Returns true if given number is prime"
(and (not (zero? (mod n 2))) (zero? (count (filter #(zero? (rem n %)) (range 3 (inc (sqrt n)) 2))))))
(defn primes-to [n]
"Returns a list of all primes from 2 to n"
(let [n (int n)]
(let [root (int (Math/round (Math/floor (Math/sqrt n))))]
(loop [i (int 3)
a (int-array n)
result (list 2)]
(if (>= i n)
(reverse result)
(recur (+ i (int 2))
(if (< i root)
(loop [arr a
inc (+ i i)
j (* i i)]
(if (>= j n)
arr
(recur (do (aset arr j (int 1)) arr)
inc
(+ j inc))))
a)
(if (zero? (aget a i))
(conj result i)
result)))))))
(defn trinum [num]
(/ (+ (square num) num) 2))
(defn to-binary [num]
"Converts given base 10 number to binary"
(read-string (Integer/toBinaryString num)))
(defn reverse-num [num]
(BigInteger. (str/reverse (str num))))
(defn is-palindrome? [input]
"Returns true if given input is a palindrome"
(let [forward (str input)
reverse (str/reverse forward)]
(= forward reverse)))
(def fib-seq
(lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))
(defn sumdigits [num]
(->> num (str) (re-seq #"\d") (vec) (map read-string) (reduce +)))