1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * https://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 /* 19 * This is not the original file distributed by the Apache Software Foundation 20 * It has been modified by the Hipparchus project 21 */ 22 package org.hipparchus.util; 23 24 import java.math.BigInteger; 25 26 import org.hipparchus.exception.Localizable; 27 import org.hipparchus.exception.LocalizedCoreFormats; 28 import org.hipparchus.exception.MathRuntimeException; 29 import org.hipparchus.exception.MathIllegalArgumentException; 30 31 /** 32 * Some useful, arithmetics related, additions to the built-in functions in 33 * {@link Math}. 34 */ 35 public final class ArithmeticUtils { 36 37 /** Private constructor. */ 38 private ArithmeticUtils() { 39 super(); 40 } 41 42 /** 43 * Add two integers, checking for overflow. 44 * 45 * @param x an addend 46 * @param y an addend 47 * @return the sum {@code x+y} 48 * @throws MathRuntimeException if the result can not be represented 49 * as an {@code int}. 50 */ 51 public static int addAndCheck(int x, int y) 52 throws MathRuntimeException { 53 long s = (long)x + (long)y; 54 if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { 55 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, x, y); 56 } 57 return (int)s; 58 } 59 60 /** 61 * Add two long integers, checking for overflow. 62 * 63 * @param a an addend 64 * @param b an addend 65 * @return the sum {@code a+b} 66 * @throws MathRuntimeException if the result can not be represented as an long 67 */ 68 public static long addAndCheck(long a, long b) throws MathRuntimeException { 69 return addAndCheck(a, b, LocalizedCoreFormats.OVERFLOW_IN_ADDITION); 70 } 71 72 /** 73 * Computes the greatest common divisor of the absolute value of two 74 * numbers, using a modified version of the "binary gcd" method. 75 * See Knuth 4.5.2 algorithm B. 76 * The algorithm is due to Josef Stein (1961). 77 * <br> 78 * Special cases: 79 * <ul> 80 * <li>The invocations 81 * {@code gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)}, 82 * {@code gcd(Integer.MIN_VALUE, 0)} and 83 * {@code gcd(0, Integer.MIN_VALUE)} throw an 84 * {@code ArithmeticException}, because the result would be 2^31, which 85 * is too large for an int value.</li> 86 * <li>The result of {@code gcd(x, x)}, {@code gcd(0, x)} and 87 * {@code gcd(x, 0)} is the absolute value of {@code x}, except 88 * for the special cases above.</li> 89 * <li>The invocation {@code gcd(0, 0)} is the only one which returns 90 * {@code 0}.</li> 91 * </ul> 92 * 93 * @param p Number. 94 * @param q Number. 95 * @return the greatest common divisor (never negative). 96 * @throws MathRuntimeException if the result cannot be represented as 97 * a non-negative {@code int} value. 98 */ 99 public static int gcd(int p, int q) throws MathRuntimeException { 100 int a = p; 101 int b = q; 102 if (a == 0 || 103 b == 0) { 104 if (a == Integer.MIN_VALUE || 105 b == Integer.MIN_VALUE) { 106 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_32_BITS, 107 p, q); 108 } 109 return FastMath.abs(a + b); 110 } 111 112 long al = a; 113 long bl = b; 114 boolean useLong = false; 115 if (a < 0) { 116 if(Integer.MIN_VALUE == a) { 117 useLong = true; 118 } else { 119 a = -a; 120 } 121 al = -al; 122 } 123 if (b < 0) { 124 if (Integer.MIN_VALUE == b) { 125 useLong = true; 126 } else { 127 b = -b; 128 } 129 bl = -bl; 130 } 131 if (useLong) { 132 if(al == bl) { 133 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_32_BITS, 134 p, q); 135 } 136 long blbu = bl; 137 bl = al; 138 al = blbu % al; 139 if (al == 0) { 140 if (bl > Integer.MAX_VALUE) { 141 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_32_BITS, 142 p, q); 143 } 144 return (int) bl; 145 } 146 blbu = bl; 147 148 // Now "al" and "bl" fit in an "int". 149 b = (int) al; 150 a = (int) (blbu % al); 151 } 152 153 return gcdPositive(a, b); 154 } 155 156 /** 157 * Computes the greatest common divisor of two <em>positive</em> numbers 158 * (this precondition is <em>not</em> checked and the result is undefined 159 * if not fulfilled) using the "binary gcd" method which avoids division 160 * and modulo operations. 161 * See Knuth 4.5.2 algorithm B. 162 * The algorithm is due to Josef Stein (1961). 163 * <p> 164 * Special cases: 165 * <ul> 166 * <li>The result of {@code gcd(x, x)}, {@code gcd(0, x)} and 167 * {@code gcd(x, 0)} is the value of {@code x}.</li> 168 * <li>The invocation {@code gcd(0, 0)} is the only one which returns 169 * {@code 0}.</li> 170 * </ul> 171 * 172 * @param a Positive number. 173 * @param b Positive number. 174 * @return the greatest common divisor. 175 */ 176 private static int gcdPositive(int a, int b) { 177 if (a == 0) { 178 return b; 179 } 180 else if (b == 0) { 181 return a; 182 } 183 184 // Make "a" and "b" odd, keeping track of common power of 2. 185 final int aTwos = Integer.numberOfTrailingZeros(a); 186 a >>= aTwos; 187 final int bTwos = Integer.numberOfTrailingZeros(b); 188 b >>= bTwos; 189 final int shift = FastMath.min(aTwos, bTwos); 190 191 // "a" and "b" are positive. 192 // If a > b then "gdc(a, b)" is equal to "gcd(a - b, b)". 193 // If a < b then "gcd(a, b)" is equal to "gcd(b - a, a)". 194 // Hence, in the successive iterations: 195 // "a" becomes the absolute difference of the current values, 196 // "b" becomes the minimum of the current values. 197 while (a != b) { 198 final int delta = a - b; 199 b = Math.min(a, b); 200 a = Math.abs(delta); 201 202 // Remove any power of 2 in "a" ("b" is guaranteed to be odd). 203 a >>= Integer.numberOfTrailingZeros(a); 204 } 205 206 // Recover the common power of 2. 207 return a << shift; 208 } 209 210 /** 211 * Gets the greatest common divisor of the absolute value of two numbers, 212 * using the "binary gcd" method which avoids division and modulo 213 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef 214 * Stein (1961). 215 * <p> 216 * Special cases: 217 * <ul> 218 * <li>The invocations 219 * {@code gcd(Long.MIN_VALUE, Long.MIN_VALUE)}, 220 * {@code gcd(Long.MIN_VALUE, 0L)} and 221 * {@code gcd(0L, Long.MIN_VALUE)} throw an 222 * {@code ArithmeticException}, because the result would be 2^63, which 223 * is too large for a long value.</li> 224 * <li>The result of {@code gcd(x, x)}, {@code gcd(0L, x)} and 225 * {@code gcd(x, 0L)} is the absolute value of {@code x}, except 226 * for the special cases above. 227 * <li>The invocation {@code gcd(0L, 0L)} is the only one which returns 228 * {@code 0L}.</li> 229 * </ul> 230 * 231 * @param p Number. 232 * @param q Number. 233 * @return the greatest common divisor, never negative. 234 * @throws MathRuntimeException if the result cannot be represented as 235 * a non-negative {@code long} value. 236 */ 237 public static long gcd(final long p, final long q) throws MathRuntimeException { 238 long u = p; 239 long v = q; 240 if ((u == 0) || (v == 0)) { 241 if ((u == Long.MIN_VALUE) || (v == Long.MIN_VALUE)){ 242 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_64_BITS, 243 p, q); 244 } 245 return FastMath.abs(u) + FastMath.abs(v); 246 } 247 // keep u and v negative, as negative integers range down to 248 // -2^63, while positive numbers can only be as large as 2^63-1 249 // (i.e. we can't necessarily negate a negative number without 250 // overflow) 251 /* assert u!=0 && v!=0; */ 252 if (u > 0) { 253 u = -u; 254 } // make u negative 255 if (v > 0) { 256 v = -v; 257 } // make v negative 258 // B1. [Find power of 2] 259 int k = 0; 260 while ((u & 1) == 0 && (v & 1) == 0 && k < 63) { // while u and v are 261 // both even... 262 u /= 2; 263 v /= 2; 264 k++; // cast out twos. 265 } 266 if (k == 63) { 267 throw new MathRuntimeException(LocalizedCoreFormats.GCD_OVERFLOW_64_BITS, 268 p, q); 269 } 270 // B2. Initialize: u and v have been divided by 2^k and at least 271 // one is odd. 272 long t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */; 273 // t negative: u was odd, v may be even (t replaces v) 274 // t positive: u was even, v is odd (t replaces u) 275 do { 276 /* assert u<0 && v<0; */ 277 // B4/B3: cast out twos from t. 278 while ((t & 1) == 0) { // while t is even.. 279 t /= 2; // cast out twos 280 } 281 // B5 [reset max(u,v)] 282 if (t > 0) { 283 u = -t; 284 } else { 285 v = t; 286 } 287 // B6/B3. at this point both u and v should be odd. 288 t = (v - u) / 2; 289 // |u| larger: t positive (replace u) 290 // |v| larger: t negative (replace v) 291 } while (t != 0); 292 return -u * (1L << k); // gcd is u*2^k 293 } 294 295 /** 296 * Returns the least common multiple of the absolute value of two numbers, 297 * using the formula {@code lcm(a,b) = (a / gcd(a,b)) * b}. 298 * <p> 299 * Special cases: 300 * <ul> 301 * <li>The invocations {@code lcm(Integer.MIN_VALUE, n)} and 302 * {@code lcm(n, Integer.MIN_VALUE)}, where {@code abs(n)} is a 303 * power of 2, throw an {@code ArithmeticException}, because the result 304 * would be 2^31, which is too large for an int value.</li> 305 * <li>The result of {@code lcm(0, x)} and {@code lcm(x, 0)} is 306 * {@code 0} for any {@code x}. 307 * </ul> 308 * 309 * @param a Number. 310 * @param b Number. 311 * @return the least common multiple, never negative. 312 * @throws MathRuntimeException if the result cannot be represented as 313 * a non-negative {@code int} value. 314 */ 315 public static int lcm(int a, int b) throws MathRuntimeException { 316 if (a == 0 || b == 0){ 317 return 0; 318 } 319 int lcm = FastMath.abs(ArithmeticUtils.mulAndCheck(a / gcd(a, b), b)); 320 if (lcm == Integer.MIN_VALUE) { 321 throw new MathRuntimeException(LocalizedCoreFormats.LCM_OVERFLOW_32_BITS, 322 a, b); 323 } 324 return lcm; 325 } 326 327 /** 328 * Returns the least common multiple of the absolute value of two numbers, 329 * using the formula {@code lcm(a,b) = (a / gcd(a,b)) * b}. 330 * <p> 331 * Special cases: 332 * <ul> 333 * <li>The invocations {@code lcm(Long.MIN_VALUE, n)} and 334 * {@code lcm(n, Long.MIN_VALUE)}, where {@code abs(n)} is a 335 * power of 2, throw an {@code ArithmeticException}, because the result 336 * would be 2^63, which is too large for an int value.</li> 337 * <li>The result of {@code lcm(0L, x)} and {@code lcm(x, 0L)} is 338 * {@code 0L} for any {@code x}. 339 * </ul> 340 * 341 * @param a Number. 342 * @param b Number. 343 * @return the least common multiple, never negative. 344 * @throws MathRuntimeException if the result cannot be represented 345 * as a non-negative {@code long} value. 346 */ 347 public static long lcm(long a, long b) throws MathRuntimeException { 348 if (a == 0 || b == 0){ 349 return 0; 350 } 351 long lcm = FastMath.abs(ArithmeticUtils.mulAndCheck(a / gcd(a, b), b)); 352 if (lcm == Long.MIN_VALUE){ 353 throw new MathRuntimeException(LocalizedCoreFormats.LCM_OVERFLOW_64_BITS, 354 a, b); 355 } 356 return lcm; 357 } 358 359 /** 360 * Multiply two integers, checking for overflow. 361 * 362 * @param x Factor. 363 * @param y Factor. 364 * @return the product {@code x * y}. 365 * @throws MathRuntimeException if the result can not be 366 * represented as an {@code int}. 367 */ 368 public static int mulAndCheck(int x, int y) throws MathRuntimeException { 369 long m = ((long)x) * ((long)y); 370 if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) { 371 throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION); 372 } 373 return (int)m; 374 } 375 376 /** 377 * Multiply two long integers, checking for overflow. 378 * 379 * @param a Factor. 380 * @param b Factor. 381 * @return the product {@code a * b}. 382 * @throws MathRuntimeException if the result can not be represented 383 * as a {@code long}. 384 */ 385 public static long mulAndCheck(long a, long b) throws MathRuntimeException { 386 long ret; 387 if (a > b) { 388 // use symmetry to reduce boundary cases 389 ret = mulAndCheck(b, a); 390 } else { 391 if (a < 0) { 392 if (b < 0) { 393 // check for positive overflow with negative a, negative b 394 if (a >= Long.MAX_VALUE / b) { 395 ret = a * b; 396 } else { 397 throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION); 398 } 399 } else if (b > 0) { 400 // check for negative overflow with negative a, positive b 401 if (Long.MIN_VALUE / b <= a) { 402 ret = a * b; 403 } else { 404 throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION); 405 406 } 407 } else { 408 // assert b == 0 409 ret = 0; 410 } 411 } else if (a > 0) { 412 // assert a > 0 413 // assert b > 0 414 415 // check for positive overflow with positive a, positive b 416 if (a <= Long.MAX_VALUE / b) { 417 ret = a * b; 418 } else { 419 throw new MathRuntimeException(LocalizedCoreFormats.ARITHMETIC_EXCEPTION); 420 } 421 } else { 422 // assert a == 0 423 ret = 0; 424 } 425 } 426 return ret; 427 } 428 429 /** 430 * Subtract two integers, checking for overflow. 431 * 432 * @param x Minuend. 433 * @param y Subtrahend. 434 * @return the difference {@code x - y}. 435 * @throws MathRuntimeException if the result can not be represented 436 * as an {@code int}. 437 */ 438 public static int subAndCheck(int x, int y) throws MathRuntimeException { 439 long s = (long)x - (long)y; 440 if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { 441 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_SUBTRACTION, x, y); 442 } 443 return (int)s; 444 } 445 446 /** 447 * Subtract two long integers, checking for overflow. 448 * 449 * @param a Value. 450 * @param b Value. 451 * @return the difference {@code a - b}. 452 * @throws MathRuntimeException if the result can not be represented as a 453 * {@code long}. 454 */ 455 public static long subAndCheck(long a, long b) throws MathRuntimeException { 456 long ret; 457 if (b == Long.MIN_VALUE) { 458 if (a < 0) { 459 ret = a - b; 460 } else { 461 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, a, -b); 462 } 463 } else { 464 // use additive inverse 465 ret = addAndCheck(a, -b, LocalizedCoreFormats.OVERFLOW_IN_ADDITION); 466 } 467 return ret; 468 } 469 470 /** 471 * Raise an int to an int power. 472 * 473 * @param k Number to raise. 474 * @param e Exponent (must be positive or zero). 475 * @return \( k^e \) 476 * @throws MathIllegalArgumentException if {@code e < 0}. 477 * @throws MathRuntimeException if the result would overflow. 478 */ 479 public static int pow(final int k, 480 final int e) 481 throws MathIllegalArgumentException, 482 MathRuntimeException { 483 if (e < 0) { 484 throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e); 485 } 486 487 int exp = e; 488 int result = 1; 489 int k2p = k; 490 while (true) { 491 if ((exp & 0x1) != 0) { 492 result = mulAndCheck(result, k2p); 493 } 494 495 exp >>= 1; 496 if (exp == 0) { 497 break; 498 } 499 500 k2p = mulAndCheck(k2p, k2p); 501 } 502 503 return result; 504 } 505 506 /** 507 * Raise a long to an int power. 508 * 509 * @param k Number to raise. 510 * @param e Exponent (must be positive or zero). 511 * @return \( k^e \) 512 * @throws MathIllegalArgumentException if {@code e < 0}. 513 * @throws MathRuntimeException if the result would overflow. 514 */ 515 public static long pow(final long k, 516 final int e) 517 throws MathIllegalArgumentException, 518 MathRuntimeException { 519 if (e < 0) { 520 throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e); 521 } 522 523 int exp = e; 524 long result = 1; 525 long k2p = k; 526 while (true) { 527 if ((exp & 0x1) != 0) { 528 result = mulAndCheck(result, k2p); 529 } 530 531 exp >>= 1; 532 if (exp == 0) { 533 break; 534 } 535 536 k2p = mulAndCheck(k2p, k2p); 537 } 538 539 return result; 540 } 541 542 /** 543 * Raise a BigInteger to an int power. 544 * 545 * @param k Number to raise. 546 * @param e Exponent (must be positive or zero). 547 * @return k<sup>e</sup> 548 * @throws MathIllegalArgumentException if {@code e < 0}. 549 */ 550 public static BigInteger pow(final BigInteger k, int e) throws MathIllegalArgumentException { 551 if (e < 0) { 552 throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e); 553 } 554 555 return k.pow(e); 556 } 557 558 /** 559 * Raise a BigInteger to a long power. 560 * 561 * @param k Number to raise. 562 * @param e Exponent (must be positive or zero). 563 * @return k<sup>e</sup> 564 * @throws MathIllegalArgumentException if {@code e < 0}. 565 */ 566 public static BigInteger pow(final BigInteger k, long e) throws MathIllegalArgumentException { 567 if (e < 0) { 568 throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e); 569 } 570 571 BigInteger result = BigInteger.ONE; 572 BigInteger k2p = k; 573 while (e != 0) { 574 if ((e & 0x1) != 0) { 575 result = result.multiply(k2p); 576 } 577 k2p = k2p.multiply(k2p); 578 e >>= 1; 579 } 580 581 return result; 582 583 } 584 585 /** 586 * Raise a BigInteger to a BigInteger power. 587 * 588 * @param k Number to raise. 589 * @param e Exponent (must be positive or zero). 590 * @return k<sup>e</sup> 591 * @throws MathIllegalArgumentException if {@code e < 0}. 592 */ 593 public static BigInteger pow(final BigInteger k, BigInteger e) throws MathIllegalArgumentException { 594 if (e.compareTo(BigInteger.ZERO) < 0) { 595 throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e); 596 } 597 598 BigInteger result = BigInteger.ONE; 599 BigInteger k2p = k; 600 while (!BigInteger.ZERO.equals(e)) { 601 if (e.testBit(0)) { 602 result = result.multiply(k2p); 603 } 604 k2p = k2p.multiply(k2p); 605 e = e.shiftRight(1); 606 } 607 608 return result; 609 } 610 611 /** 612 * Add two long integers, checking for overflow. 613 * 614 * @param a Addend. 615 * @param b Addend. 616 * @param pattern Pattern to use for any thrown exception. 617 * @return the sum {@code a + b}. 618 * @throws MathRuntimeException if the result cannot be represented 619 * as a {@code long}. 620 */ 621 private static long addAndCheck(long a, long b, Localizable pattern) throws MathRuntimeException { 622 final long result = a + b; 623 if (!((a ^ b) < 0 || (a ^ result) >= 0)) { 624 throw new MathRuntimeException(pattern, a, b); 625 } 626 return result; 627 } 628 629 /** 630 * Returns true if the argument is a power of two. 631 * 632 * @param n the number to test 633 * @return true if the argument is a power of two 634 */ 635 public static boolean isPowerOfTwo(long n) { 636 return (n > 0) && ((n & (n - 1)) == 0); 637 } 638 639 /** 640 * Returns the unsigned remainder from dividing the first argument 641 * by the second where each argument and the result is interpreted 642 * as an unsigned value. 643 * <p> 644 * This method does not use the {@code long} datatype. 645 * 646 * @param dividend the value to be divided 647 * @param divisor the value doing the dividing 648 * @return the unsigned remainder of the first argument divided by 649 * the second argument. 650 */ 651 public static int remainderUnsigned(int dividend, int divisor) { 652 if (divisor >= 0) { 653 if (dividend >= 0) { 654 return dividend % divisor; 655 } 656 // The implementation is a Java port of algorithm described in the book 657 // "Hacker's Delight" (section "Unsigned short division from signed division"). 658 int q = ((dividend >>> 1) / divisor) << 1; 659 dividend -= q * divisor; 660 if (dividend < 0 || dividend >= divisor) { 661 dividend -= divisor; 662 } 663 return dividend; 664 } 665 return dividend >= 0 || dividend < divisor ? dividend : dividend - divisor; 666 } 667 668 /** 669 * Returns the unsigned remainder from dividing the first argument 670 * by the second where each argument and the result is interpreted 671 * as an unsigned value. 672 * <p> 673 * This method does not use the {@code BigInteger} datatype. 674 * 675 * @param dividend the value to be divided 676 * @param divisor the value doing the dividing 677 * @return the unsigned remainder of the first argument divided by 678 * the second argument. 679 */ 680 public static long remainderUnsigned(long dividend, long divisor) { 681 if (divisor >= 0L) { 682 if (dividend >= 0L) { 683 return dividend % divisor; 684 } 685 // The implementation is a Java port of algorithm described in the book 686 // "Hacker's Delight" (section "Unsigned short division from signed division"). 687 long q = ((dividend >>> 1) / divisor) << 1; 688 dividend -= q * divisor; 689 if (dividend < 0L || dividend >= divisor) { 690 dividend -= divisor; 691 } 692 return dividend; 693 } 694 return dividend >= 0L || dividend < divisor ? dividend : dividend - divisor; 695 } 696 697 /** 698 * Returns the unsigned quotient of dividing the first argument by 699 * the second where each argument and the result is interpreted as 700 * an unsigned value. 701 * <p> 702 * Note that in two's complement arithmetic, the three other 703 * basic arithmetic operations of add, subtract, and multiply are 704 * bit-wise identical if the two operands are regarded as both 705 * being signed or both being unsigned. Therefore separate {@code 706 * addUnsigned}, etc. methods are not provided. 707 * <p> 708 * This method does not use the {@code long} datatype. 709 * 710 * @param dividend the value to be divided 711 * @param divisor the value doing the dividing 712 * @return the unsigned quotient of the first argument divided by 713 * the second argument 714 */ 715 public static int divideUnsigned(int dividend, int divisor) { 716 if (divisor >= 0) { 717 if (dividend >= 0) { 718 return dividend / divisor; 719 } 720 // The implementation is a Java port of algorithm described in the book 721 // "Hacker's Delight" (section "Unsigned short division from signed division"). 722 int q = ((dividend >>> 1) / divisor) << 1; 723 dividend -= q * divisor; 724 if (dividend < 0L || dividend >= divisor) { 725 q++; 726 } 727 return q; 728 } 729 return dividend >= 0 || dividend < divisor ? 0 : 1; 730 } 731 732 /** 733 * Returns the unsigned quotient of dividing the first argument by 734 * the second where each argument and the result is interpreted as 735 * an unsigned value. 736 * <p> 737 * Note that in two's complement arithmetic, the three other 738 * basic arithmetic operations of add, subtract, and multiply are 739 * bit-wise identical if the two operands are regarded as both 740 * being signed or both being unsigned. Therefore separate {@code 741 * addUnsigned}, etc. methods are not provided. 742 * <p> 743 * This method does not use the {@code BigInteger} datatype. 744 * 745 * @param dividend the value to be divided 746 * @param divisor the value doing the dividing 747 * @return the unsigned quotient of the first argument divided by 748 * the second argument. 749 */ 750 public static long divideUnsigned(long dividend, long divisor) { 751 if (divisor >= 0L) { 752 if (dividend >= 0L) { 753 return dividend / divisor; 754 } 755 // The implementation is a Java port of algorithm described in the book 756 // "Hacker's Delight" (section "Unsigned short division from signed division"). 757 long q = ((dividend >>> 1) / divisor) << 1; 758 dividend -= q * divisor; 759 if (dividend < 0L || dividend >= divisor) { 760 q++; 761 } 762 return q; 763 } 764 return dividend >= 0L || dividend < divisor ? 0L : 1L; 765 } 766 767 }