代码之家  ›  专栏  ›  技术社区  ›  ilitirit

是否有一种算法可以计算x模y的乘法阶数(对于y<1000),而不需要BigInteger类型?

  •  4
  • ilitirit  · 技术社区  · 17 年前

    我目前使用的算法很快就会遇到非常高的数字。我要提出的算法中的一个步骤 英语字母表的第24个字母 将totient函数应用于 y

    multiplicative order 10模53:

    10^totient(53) == 10^52 == 1 * 10^52
    

    大于数据类型的容量:

      mOrder = 1
      while 10^mOrder % 53 != 1
          if mOrder >= i
              mOrder = 0;
              break
          else
              mOrder = mOrder + 1
    
    2 回复  |  直到 17 年前
        1
  •  7
  •   schnaader    17 年前

    Wikipedia 有关详细信息,还有以下示例代码:

    Bignum modpow(Bignum base, Bignum exponent, Bignum modulus) {
    
        Bignum result = 1;
    
        while (exponent > 0) {
            if ((exponent & 1) == 1) {
                // multiply in this bit's contribution while using modulus to keep result small
                result = (result * base) % modulus;
            }
            // move to the next bit of the exponent, square (and mod) the base accordingly
            exponent >>= 1;
            base = (base * base) % modulus;
        }
    
        return result;
    }
    
        2
  •  6
  •   Svante    7 年前

    为什么要指数化?你就不能乘模吗 n 在循环中?

    (defun multiplicative-order (a n)
      (if (> (gcd a n) 1)
          0
          (do ((order 1 (+ order 1))
               (mod-exp (mod a n) (mod (* mod-exp a) n)))
              ((= mod-exp 1) order))))
    

    或者,在ptheudo(sic)代码中:

    def multiplicative_order (a, n) :
        if gcd (a, n) > 1 :
            return 0
          else:
            order = 1
            mod_exp = a mod n
            while mod_exp != 1 :
                order += 1
                mod_exp = (mod_exp * a) mod n
            return order