/src/library/scala/math/BigInt.scala

http://github.com/greedy/scala-llvm · Scala · 385 lines · 109 code · 72 blank · 204 comment · 16 complexity · 41fcad329c919f7f0c5e02165f1c1c46 MD5 · raw file

  1. /* __ *\
  2. ** ________ ___ / / ___ Scala API **
  3. ** / __/ __// _ | / / / _ | (c) 2006-2011, LAMP/EPFL **
  4. ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
  5. ** /____/\___/_/ |_/____/_/ | | **
  6. ** |/ **
  7. \* */
  8. package scala.math
  9. import java.math.BigInteger
  10. /**
  11. * @author Martin Odersky
  12. * @version 1.0, 15/07/2003
  13. * @since 2.1
  14. */
  15. object BigInt {
  16. private val minCached = -1024
  17. private val maxCached = 1024
  18. private val cache = new Array[BigInt](maxCached - minCached + 1)
  19. @deprecated("Use Long.MinValue", "2.9.0")
  20. lazy val MinLong = BigInt(Long.MinValue)
  21. @deprecated("Use Long.MaxValue", "2.9.0")
  22. lazy val MaxLong = BigInt(Long.MaxValue)
  23. /** Constructs a <code>BigInt</code> whose value is equal to that of the
  24. * specified integer value.
  25. *
  26. * @param i the specified integer value
  27. * @return the constructed <code>BigInt</code>
  28. */
  29. def apply(i: Int): BigInt =
  30. if (minCached <= i && i <= maxCached) {
  31. val offset = i - minCached
  32. var n = cache(offset)
  33. if (n eq null) { n = new BigInt(BigInteger.valueOf(i)); cache(offset) = n }
  34. n
  35. } else new BigInt(BigInteger.valueOf(i))
  36. /** Constructs a <code>BigInt</code> whose value is equal to that of the
  37. * specified long value.
  38. *
  39. * @param l the specified long value
  40. * @return the constructed <code>BigInt</code>
  41. */
  42. def apply(l: Long): BigInt =
  43. if (minCached <= l && l <= maxCached) apply(l.toInt)
  44. else new BigInt(BigInteger.valueOf(l))
  45. /** Translates a byte array containing the two's-complement binary
  46. * representation of a BigInt into a BigInt.
  47. */
  48. def apply(x: Array[Byte]): BigInt =
  49. new BigInt(new BigInteger(x))
  50. /** Translates the sign-magnitude representation of a BigInt into a BigInt.
  51. */
  52. def apply(signum: Int, magnitude: Array[Byte]): BigInt =
  53. new BigInt(new BigInteger(signum, magnitude))
  54. /** Constructs a randomly generated positive BigInt that is probably prime,
  55. * with the specified bitLength.
  56. */
  57. def apply(bitlength: Int, certainty: Int, rnd: scala.util.Random): BigInt =
  58. new BigInt(new BigInteger(bitlength, certainty, rnd.self))
  59. /** Constructs a randomly generated BigInt, uniformly distributed over the
  60. * range 0 to (2 ^ numBits - 1), inclusive.
  61. *
  62. * @param numbits ...
  63. * @param rnd ...
  64. * @return ...
  65. */
  66. def apply(numbits: Int, rnd: scala.util.Random): BigInt =
  67. new BigInt(new BigInteger(numbits, rnd.self))
  68. /** Translates the decimal String representation of a BigInt into a BigInt.
  69. */
  70. def apply(x: String): BigInt =
  71. new BigInt(new BigInteger(x))
  72. /** Translates the string representation of a BigInt in the
  73. * specified <code>radix</code> into a BigInt.
  74. *
  75. * @param x ...
  76. * @param radix ...
  77. * @return ...
  78. */
  79. def apply(x: String, radix: Int): BigInt =
  80. new BigInt(new BigInteger(x, radix))
  81. /** Returns a positive BigInt that is probably prime, with the specified bitLength.
  82. */
  83. def probablePrime(bitLength: Int, rnd: scala.util.Random): BigInt =
  84. new BigInt(BigInteger.probablePrime(bitLength, rnd.self))
  85. /** Implicit conversion from <code>int</code> to <code>BigInt</code>.
  86. */
  87. implicit def int2bigInt(i: Int): BigInt = apply(i)
  88. /** Implicit conversion from long to BigInt
  89. */
  90. implicit def long2bigInt(l: Long): BigInt = apply(l)
  91. }
  92. /**
  93. * @author Martin Odersky
  94. * @version 1.0, 15/07/2003
  95. */
  96. class BigInt(val bigInteger: BigInteger) extends ScalaNumber with ScalaNumericConversions with Serializable {
  97. /** Returns the hash code for this BigInt. */
  98. override def hashCode(): Int =
  99. if (isValidLong) unifiedPrimitiveHashcode
  100. else bigInteger.##
  101. /** Compares this BigInt with the specified value for equality.
  102. */
  103. override def equals(that: Any): Boolean = that match {
  104. case that: BigInt => this equals that
  105. case that: BigDecimal => that.toBigIntExact exists (this equals _)
  106. case x => isValidLong && unifiedPrimitiveEquals(x)
  107. }
  108. override def isValidByte = this >= Byte.MinValue && this <= Byte.MaxValue
  109. override def isValidShort = this >= Short.MinValue && this <= Short.MaxValue
  110. override def isValidChar = this >= Char.MinValue && this <= Char.MaxValue
  111. override def isValidInt = this >= Int.MinValue && this <= Int.MaxValue
  112. def isValidLong = this >= Long.MinValue && this <= Long.MaxValue
  113. protected[math] def isWhole = true
  114. def underlying = bigInteger
  115. /** Compares this BigInt with the specified BigInt for equality.
  116. */
  117. def equals (that: BigInt): Boolean = compare(that) == 0
  118. /** Compares this BigInt with the specified BigInt
  119. */
  120. def compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger)
  121. /** Less-than-or-equals comparison of BigInts
  122. */
  123. def <= (that: BigInt): Boolean = compare(that) <= 0
  124. /** Greater-than-or-equals comparison of BigInts
  125. */
  126. def >= (that: BigInt): Boolean = compare(that) >= 0
  127. /** Less-than of BigInts
  128. */
  129. def < (that: BigInt): Boolean = compare(that) < 0
  130. /** Greater-than comparison of BigInts
  131. */
  132. def > (that: BigInt): Boolean = compare(that) > 0
  133. /** Addition of BigInts
  134. */
  135. def + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger))
  136. /** Subtraction of BigInts
  137. */
  138. def - (that: BigInt): BigInt = new BigInt(this.bigInteger.subtract(that.bigInteger))
  139. /** Multiplication of BigInts
  140. */
  141. def * (that: BigInt): BigInt = new BigInt(this.bigInteger.multiply(that.bigInteger))
  142. /** Division of BigInts
  143. */
  144. def / (that: BigInt): BigInt = new BigInt(this.bigInteger.divide(that.bigInteger))
  145. /** Remainder of BigInts
  146. */
  147. def % (that: BigInt): BigInt = new BigInt(this.bigInteger.remainder(that.bigInteger))
  148. /** Returns a pair of two BigInts containing (this / that) and (this % that).
  149. */
  150. def /% (that: BigInt): (BigInt, BigInt) = {
  151. val dr = this.bigInteger.divideAndRemainder(that.bigInteger)
  152. (new BigInt(dr(0)), new BigInt(dr(1)))
  153. }
  154. /** Leftshift of BigInt
  155. */
  156. def << (n: Int): BigInt = new BigInt(this.bigInteger.shiftLeft(n))
  157. /** (Signed) rightshift of BigInt
  158. */
  159. def >> (n: Int): BigInt = new BigInt(this.bigInteger.shiftRight(n))
  160. /** Bitwise and of BigInts
  161. */
  162. def & (that: BigInt): BigInt = new BigInt(this.bigInteger.and(that.bigInteger))
  163. /** Bitwise or of BigInts
  164. */
  165. def | (that: BigInt): BigInt = new BigInt(this.bigInteger.or (that.bigInteger))
  166. /** Bitwise exclusive-or of BigInts
  167. */
  168. def ^ (that: BigInt): BigInt = new BigInt(this.bigInteger.xor(that.bigInteger))
  169. /** Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that).
  170. */
  171. def &~ (that: BigInt): BigInt = new BigInt(this.bigInteger.andNot(that.bigInteger))
  172. /** Returns the greatest common divisor of abs(this) and abs(that)
  173. */
  174. def gcd (that: BigInt): BigInt = new BigInt(this.bigInteger.gcd(that.bigInteger))
  175. /** Returns a BigInt whose value is (this mod m).
  176. * This method differs from `%` in that it always returns a non-negative BigInt.
  177. */
  178. def mod (that: BigInt): BigInt = new BigInt(this.bigInteger.mod(that.bigInteger))
  179. /** Returns the minimum of this and that
  180. */
  181. def min (that: BigInt): BigInt = new BigInt(this.bigInteger.min(that.bigInteger))
  182. /** Returns the maximum of this and that
  183. */
  184. def max (that: BigInt): BigInt = new BigInt(this.bigInteger.max(that.bigInteger))
  185. /** Returns a BigInt whose value is (<tt>this</tt> raised to the power of <tt>exp</tt>).
  186. */
  187. def pow (exp: Int): BigInt = new BigInt(this.bigInteger.pow(exp))
  188. /** Returns a BigInt whose value is
  189. * (<tt>this</tt> raised to the power of <tt>exp</tt> modulo <tt>m</tt>).
  190. */
  191. def modPow (exp: BigInt, m: BigInt): BigInt =
  192. new BigInt(this.bigInteger.modPow(exp.bigInteger, m.bigInteger))
  193. /** Returns a BigInt whose value is (the inverse of <tt>this</tt> modulo <tt>m</tt>).
  194. */
  195. def modInverse (m: BigInt): BigInt = new BigInt(this.bigInteger.modInverse(m.bigInteger))
  196. /** Returns a BigInt whose value is the negation of this BigInt
  197. */
  198. def unary_- : BigInt = new BigInt(this.bigInteger.negate())
  199. /** Returns the absolute value of this BigInt
  200. */
  201. def abs: BigInt = new BigInt(this.bigInteger.abs())
  202. /** Returns the sign of this BigInt, i.e.
  203. * -1 if it is less than 0,
  204. * +1 if it is greater than 0
  205. * 0 if it is equal to 0
  206. */
  207. def signum: Int = this.bigInteger.signum()
  208. @deprecated("Use ~bigInt (the unary_~ method) instead", "2.10.0")
  209. def ~ : BigInt = ~this
  210. /** Returns the bitwise complement of this BigInt
  211. */
  212. def unary_~ : BigInt = new BigInt(this.bigInteger.not())
  213. /** Returns true if and only if the designated bit is set.
  214. */
  215. def testBit (n: Int): Boolean = this.bigInteger.testBit(n)
  216. /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit set.
  217. */
  218. def setBit (n: Int): BigInt = new BigInt(this.bigInteger.setBit(n))
  219. /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit cleared.
  220. */
  221. def clearBit(n: Int): BigInt = new BigInt(this.bigInteger.clearBit(n))
  222. /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit flipped.
  223. */
  224. def flipBit (n: Int): BigInt = new BigInt(this.bigInteger.flipBit(n))
  225. /** Returns the index of the rightmost (lowest-order) one bit in this BigInt
  226. * (the number of zero bits to the right of the rightmost one bit).
  227. */
  228. def lowestSetBit: Int = this.bigInteger.getLowestSetBit()
  229. /** Returns the number of bits in the minimal two's-complement representation of this BigInt,
  230. * excluding a sign bit.
  231. */
  232. def bitLength: Int = this.bigInteger.bitLength()
  233. /** Returns the number of bits in the two's complement representation of this BigInt
  234. * that differ from its sign bit.
  235. */
  236. def bitCount: Int = this.bigInteger.bitCount()
  237. /** Returns true if this BigInt is probably prime, false if it's definitely composite.
  238. * @param certainty a measure of the uncertainty that the caller is willing to tolerate:
  239. * if the call returns true the probability that this BigInt is prime
  240. * exceeds (1 - 1/2 ^ certainty).
  241. * The execution time of this method is proportional to the value of
  242. * this parameter.
  243. */
  244. def isProbablePrime(certainty: Int) = this.bigInteger.isProbablePrime(certainty)
  245. /** Converts this BigInt to a <tt>byte</tt>.
  246. * If the BigInt is too big to fit in a byte, only the low-order 8 bits are returned.
  247. * Note that this conversion can lose information about the overall magnitude of the
  248. * BigInt value as well as return a result with the opposite sign.
  249. */
  250. override def byteValue = intValue.toByte
  251. /** Converts this BigInt to a <tt>short</tt>.
  252. * If the BigInt is too big to fit in a byte, only the low-order 16 bits are returned.
  253. * Note that this conversion can lose information about the overall magnitude of the
  254. * BigInt value as well as return a result with the opposite sign.
  255. */
  256. override def shortValue = intValue.toShort
  257. /** Converts this BigInt to a <tt>char</tt>.
  258. * If the BigInt is too big to fit in a char, only the low-order 16 bits are returned.
  259. * Note that this conversion can lose information about the overall magnitude of the
  260. * BigInt value and that it always returns a positive result.
  261. */
  262. def charValue = intValue.toChar
  263. /** Converts this BigInt to an <tt>int</tt>.
  264. * If the BigInt is too big to fit in a char, only the low-order 32 bits
  265. * are returned. Note that this conversion can lose information about the
  266. * overall magnitude of the BigInt value as well as return a result with
  267. * the opposite sign.
  268. */
  269. def intValue = this.bigInteger.intValue
  270. /** Converts this BigInt to a <tt>long</tt>.
  271. * If the BigInt is too big to fit in a char, only the low-order 64 bits
  272. * are returned. Note that this conversion can lose information about the
  273. * overall magnitude of the BigInt value as well as return a result with
  274. * the opposite sign.
  275. */
  276. def longValue = this.bigInteger.longValue
  277. /** Converts this BigInt to a <tt>float</tt>.
  278. * if this BigInt has too great a magnitude to represent as a float,
  279. * it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
  280. * <code>Float.POSITIVE_INFINITY</code> as appropriate.
  281. */
  282. def floatValue = this.bigInteger.floatValue
  283. /** Converts this BigInt to a <tt>double</tt>.
  284. * if this BigInt has too great a magnitude to represent as a double,
  285. * it will be converted to <code>Double.NEGATIVE_INFINITY</code> or
  286. * <code>Double.POSITIVE_INFINITY</code> as appropriate.
  287. */
  288. def doubleValue = this.bigInteger.doubleValue
  289. /** Create a NumericRange[BigInt] in range <code>[start;end)</code>
  290. * with the specified step, where start is the target BigInt.
  291. *
  292. * @param end the end value of the range (exclusive)
  293. * @param step the distance between elements (defaults to 1)
  294. * @return the range
  295. */
  296. def until(end: BigInt, step: BigInt = BigInt(1)) = Range.BigInt(this, end, step)
  297. /** Like until, but inclusive of the end value.
  298. */
  299. def to(end: BigInt, step: BigInt = BigInt(1)) = Range.BigInt.inclusive(this, end, step)
  300. /** Returns the decimal String representation of this BigInt.
  301. */
  302. override def toString(): String = this.bigInteger.toString()
  303. /** Returns the String representation in the specified radix of this BigInt.
  304. */
  305. def toString(radix: Int): String = this.bigInteger.toString(radix)
  306. /** Returns a byte array containing the two's-complement representation of
  307. * this BigInt. The byte array will be in big-endian byte-order: the most
  308. * significant byte is in the zeroth element. The array will contain the
  309. * minimum number of bytes required to represent this BigInt, including at
  310. * least one sign bit.
  311. */
  312. def toByteArray: Array[Byte] = this.bigInteger.toByteArray()
  313. }