How can I convert a long int to a rational in Clojure?
That does not work:
user> (class (/ 5 1))
java.long.Long
You don't need to explicitly convert a long into a rational.
Clojure will convert
a rational (clojure.lang.Ratio) into a long (java.lang.Long) when it can: when the denominator is or can be made to be 1;
longs or other ints into a rational when it must: when a division cannot be resolved to a denominator of 1.
Thus
(type (/ 4 2))
; java.lang.Long
(type (/ 4 3))
; clojure.lang.Ratio
There's rationalize. But that doesn't do what you want -- it still returns a long if the denominator is a 1. However, if you want this for type testing purposes, the Clojure function rational? returns true for longs.
If you really want Ratio types, I think you'll have to write it yourself, since the source of rationalize dives immediately into the underlying Java.
(clojure.lang.Ratio.
(. BigInteger (valueOf 3))
(. BigInteger (valueOf 1)))
; 3/1
Perhaps:
(defn myrationalize
[num]
(if (integer? num)
(clojure.lang.Ratio.
(. BigInteger (valueOf num))
(. BigInteger (valueOf 1)))
(rationalize num)))
Related
I tried to compute factorial through defmulti and defmethod.
(defmulti factorial identity)
(defmethod factorial 0 [_] 1)
(defmethod factorial :default [num]
(* num (factorial (dec num))))
It works fine for small numbers
(-> 10 factorial) ;;3628800
(-> 2 factorial) ;; 2
it shows Integer Overflow Exception for factorial 40
(-> 40 factorial)
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow
My curiosity is
How can we compute factorial for Big Numbers using defmulti and defmethod?
Clojure's implementation of number types builds on the host platform's number types. Your solution works when you define the arbitrary size flag N, because the underlying number type changes on the JVM.
(type 10) ;=> java.lang.Long
(type 10N) ;=> clojure.lang.BigInt
clojure.lang.BigInt uses either java.math.BigInteger or a Java long as the underlying type, depending on the bit size of the number.
On a different host, the Javascript engine of a browser, both types are JavaScript's native Numbers. The factorial function gives a result up to 170 in ClojureScript. It does not throw when overflowing, but returns the JavaScript number value Infinity:
(factorial 170) ; => 7.257415615307994e+306
(factorial 170N) ; => 7.257415615307994e+306
(factorial 171N) ; => Infinity
Update: This answer (pointed out by #cske) gives a neat solution to use the *' operator, which bumps up the number type in case it would overflow:
(defmethod factorial :default [num]
(*' num (factorial (dec num))))
(factorial 40) ; => 815915283247897734345611269596115894272000000000N
I have solved it
(-> 40N factorial) ;;815915283247897734345611269596115894272000000000N
Hi I am programming in clojure and though the problem of modulo inverse has nothing to do with language i am stuck at this code -
(defn EulerDiv [x p]
(let [ToMod (+ p 2)]
(loop [num 1 toPow (int p) numDouble x]
(if (= 0 toPow)
num
(let [numDouble2 (rem (* numDouble numDouble) ToMod)
halfToPow (int (/ toPow 2))]
(if (odd? toPow)
(recur (rem (* num numDouble) ToMod)
halfToPow
numDouble2)
(recur num halfToPow numDouble2))
))))
)
It seems to give me right answers for small Primes but when i am using it in a problem with Bigger primes i am getting answers other than result like :
(= 2 (mod (* 4 (EulerDiv 2 (- 3 2))) 3))
This prints true
(def ToMod (+ 10e8 7))
( = 1 (int (mod (* 2 (EulerDiv 2 (- ToMod 2))) ToMod)) )
This prints false.
Also there is rem and mod in clojure.
mod makes the output positive and hence i can not use it in between the calculations.
It is a programming contest but this is just part of solution and this info of modulo inverse was also provided in the problem page.
The problem is that of programming calculator grammar for evaluating evpressions like 4/-2/(2 + 8)
You are straying from integer arithmetic.
Given integers, the / function can produce rationals: (/ 1 2) is 1/2, not 0.
And 1e9 is 1.0E9, a double, not an integer.
There are appropriate substitutes available. Look at the arithmetic section here for an integer division function, and at the cast section for something to convert a number to an integer.
All the best!
So, I grabbed the latest numeric tower for a couple quick calculations and noticed that the numbers returned have "N" at the end. Why? What does it mean?
clojure.math.numeric-tower=> (expt 64 20)
1329227995784915872903807060280344576N
clojure.math.numeric-tower=> (expt 36 20)
13367494538843734067838845976576N
That is the literal form of BigInt:
user=> (type 1N)
clojure.lang.BigInt
versus, for example:
user=> (type 1)
java.lang.Long
or
user=> (type 1.0)
java.lang.Double
There's also the M suffix for BigDecimal.
user=> (type 1M)
java.math.BigDecimal
I'm not sure of all the rules for promotion to arbitrary precision (BigInt, BigDecimal). I think most of the "regular" math functions won't promote to arbitrary precision, but there are a few that do (e.g. +', -', *', inc', dec').
e.g. Regular + overflows:
user=> (+ Long/MAX_VALUE 1)
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1388)
but +' promotes:
user=> (+' Long/MAX_VALUE 1)
9223372036854775808N
How can the absolute number of a value be calculated in Clojure?
(abs 1) => 1
(abs -1) => 1
(abs 0) => 0
As of Clojure 1.11, it is simply (abs -1) in both Clojure and Clojurescript.
In versions before, for double, float, long and int you can use the java.lang.Math method abs (Math/abs -1)
Take care it won't work for decimals, ratio's, bigint(eger)s and other Clojure numeric types. The official clojure contrib math library that tries guarantee working correctly with all of these is clojure.math.numeric-tower
you could always do
(defn abs [n] (max n (- n)))
The deprecated clojure.contrib.math provides an abs function.
The source is:
(defn abs "(abs n) is the absolute value of n" [n]
(cond
(not (number? n)) (throw (IllegalArgumentException.
"abs requires a number"))
(neg? n) (- n)
:else n))
As #NielsK points out in the comments, clojure.math.numeric-tower is the successor project.
abs is now available in the core clojure library since Clojure 1.11 release.
Docs for abs https://clojure.github.io/clojure/branch-master/clojure.core-api.html#clojure.core/abs
Usage: (abs a)
Returns the absolute value of a.
If a is Long/MIN_VALUE => Long/MIN_VALUE
If a is a double and zero => +0.0
If a is a double and ##Inf or ##-Inf => ##Inf
If a is a double and ##NaN => ##NaN
Added in Clojure version 1.11
I want to calculate !1000 in clojure, how can I do this without getting a integer-overflow exception?
My factorial code is right now: (reduce * (range 1 1001)).
You could use the *' operator which supports arbitrary precision by automatically promoting the result to BigInt in case it would overflow:
(reduce *' (range 1 1001))
Put N at the end of the number which makes it a bigint,
(reduce * (range 1N 1001N))
Coerce the parameters to clojure.lang.BigInt
(reduce * (range (bigint 1) (bigint 1001)))
I.e. if you are working with an third-party library that doesn't use *'
(defn factorial' [n]
(factorial (bigint n)))