ͲΜͳ࣮ʁ static VALUE int_pow(long x, unsigned long y) { // ... y &= ~1; do { while (y % 2 == 0) { if (!FIT_SQRT_LONG(x)) { VALUE v; bignum: v = rb_big_pow(rb_int2big(x), LONG2NUM(y)); if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */ return v; if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v); return v; } x = x * x; y >>= 1; } { if (MUL_OVERFLOW_FIXNUM_P(x, z)) { goto bignum; } z = x * z; } } while (--y); if (neg) z = -z; return LONG2NUM(z); } ԿΘ͔Βͳ͍ OVNFSJDDSVCZSVCZc(JU)VC IUUQTHJUIVCDPNSVCZSVCZCMPCEBCDFFGCBBGDOVNFSJDD
ͲΜͳ࣮ʁ DPNQMFYSCSVCJOJVTSVCJOJVTc(JU)VC IUUQTHJUIVCDPNSVCJOJVTSVCJOJVTCMPCFCEDBCCGEBBCBGFE DPSFDPNQMFYSC def ** (other) # ... if other.kind_of?(Complex) # ... elsif other.kind_of?(Integer) if other > 0 x = self z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2) mod == 0) x = Complex(x.real*x.real - x.imag*x.imag, 2*x.real*x.imag) n = div end z *= x n -= 1 end z else # ... end elsif Complex.generic?(other) # ... end end ͳΜͱ͔ಡΊͦ͏
def ** (other) if !other.kind_of?(Float) && other == 0 return Complex(1) end if other.kind_of?(Complex) # ... elsif other.kind_of?(Integer) if other > 0 x = self z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2) mod == 0) x = Complex(x.real*x.real - x.imag*x.imag, 2*x.real*x.imag) n = div end z *= x n -= 1 end z else # ... end elsif Complex.generic?(other) # ... end end other͕0ͷ࣌1Λฦ͢ ࠓճॲཧͷྲྀΕΛ Γ͍͚ͨͩͳͷͰলུ (selfotherਖ਼ͷͷఆ)
def ** (other) if !other.kind_of?(Float) && other == 0 return Complex(1) end if other.kind_of?(Complex) # ... elsif other.kind_of?(Integer) if other > 0 x = self z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2) mod == 0) x = Complex(x.real*x.real - x.imag*x.imag, 2*x.real*x.imag) n = div end z *= x n -= 1 end z else # ... end elsif Complex.generic?(other) # ... end end ࠓճॲཧͷྲྀΕΛ Γ͍͚ͨͩͳͷͰলུ (ֶͰ͖ͳ͍ਓ)
def power(a, other) x = a z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2); mod == 0) x = x * x n = div end z *= x n -= 1 end z end ͘͢͝ಡΊͦ͏ʂ ɹɹɹ ԿΘ͔Βͳ͍ ؆ུԽ͢Δͱ ࣮ߦ͍͢͠Α͏ʹselfΛaʹ͢Δ
def power(a, other) x = a z = x n = other - 1 while n != 0 p " n: #{n}" while (div, mod = n.divmod(2); mod == 0) p x = x * x p n = div end z *= x p " z: #{z}" n -= 1 end z end ࢦ͕2ͷഒͷؒ ৽͍͠ࢦn / 2 ؆ུԽ͢Δͱ x = x2Λ͚ͭͮ͠Δ
def power(a, other) x = a z = x n = other - 1 while n != 0 p " n: #{n}" while (div, mod = n.divmod(2); mod == 0) p x = x * x p n = div end z *= x p " z: #{z}" n -= 1 end z end ྦྷ ࢦ͕ۮͷؒ ࢦ͕حʹͳͬͨΒ zʹྦྷͨ͠xΛֻ͚Δ (((x2)2)2…͠ଓ͚Δ
def power(a, other) x = a z = x n = other - 1 while n != 0 p " n: #{n}" while (div, mod = n.divmod(2); mod == 0) p x = x * x p n = div end z *= x p " z: #{z}" n -= 1 end z end ྦྷ a = 3, other = 3ͷ߹( 33 ) n(ࢦ) = 2 div = 1, mod = 0 n = 1 z = 3 * 9 = 27 n = 0 x = 3 * 3 = 9
rubyͷ࣮ • def power(a, other) x = a z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2); mod == 0) x *= x n = div end z *= x n -= 1 end z end •ࢦΛ2Ͱׂ͍ͬͯ͘ͱܭࢉճ͕૿͑ͳ͍