Pollard 的 Rho 演算法用於進行整數質因子分解,java 中的實現如下


它是一種對給定整數進行因式分解的演算法。以下程式實現了 Rho 演算法以進行質因數分解。

程式

線上演示

public class PollardsRho {
   int num = 65;
   public int gcd(int a, int b) {
      int gcd = 0;
      for(int i = 1; i <= a || i <= b; i++) {
         if( a%i == 0 &amp;&amp; b%i == 0 ) {
            gcd = i;
         }
      }
      return gcd;
   }
   int g(int x) {
      return ((x*x)-1) % num;
   }
   public static void main(String args[]) {
      PollardsRho obj = new PollardsRho();
      int x = 2, y = 2, d = 1;
      while(d==1) {
         x = obj.g(x);
         y = obj.g(obj.g(y));
         d = obj.gcd((x - y), obj.num);
      }
      if (d == obj.num) {
         System.out.println("Cannot calculate GCD for this element");
      } else {
         System.out.println("One of the divisors of given number is "+d);
      }
   }
}

輸出

One of the divisors of given number are 5

更新於: 2020 年 6 月 25 日

192 次瀏覽

開啟您的 職業 生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.