private def gcdPositive()

in core/src/main/scala/com/spotify/featran/transformers/PolynomialExpansion.scala [245:274]


  private def gcdPositive(p: Int, q: Int): Int =
    // assert q != 0
    if (p == 0) {
      q
    } else {
      var a = p
      var b = q
      val aTwos = Integer.numberOfTrailingZeros(a)
      a = a >> aTwos
      val bTwos = Integer.numberOfTrailingZeros(b)
      b = b >> bTwos
      val shift = if (aTwos <= bTwos) aTwos else bTwos
      // "a" and "b" are positive.
      // If a > b then "gdc(a, b)" is equal to "gcd(a - b, b)".
      // If a < b then "gcd(a, b)" is equal to "gcd(b - a, a)".
      // Hence, in the successive iterations:
      //  "a" becomes the absolute difference of the current values,
      //  "b" becomes the minimum of the current values.
      while (a != b) {
        val delta = a - b
        b = Math.min(a, b)
        a = Math.abs(delta)

        // Remove any power of 2 in "a" ("b" is guaranteed to be odd).
        a >>= Integer.numberOfTrailingZeros(a)
      }

      // Recover the common power of 2.
      a << shift
    }