zoukankan      html  css  js  c++  java
  • 【Java】正数模幂运算、模逆运算方法(有步骤)

    模幂运算

        public static int modPowerShow(int a, int k, int n){
            System.out.println("*************************************************************************");
            System.out.println("****NOTICE:["\" area should be replaced by blank so there is nothing]****");
            System.out.println("****NOTICE:["(3=))" area should be replaced by three line equal]*********");
            System.out.println("*************************************************************************");
            System.out.println("i		ki		x		y");
            int now, x = 1, y = a, power;
            for(int i = 0;;i++){
                now = k % 2;
                System.out.print(i + "		" + now + "		");
                power = (x * y) % n;
                if(now == 1) {
                    System.out.print(x + "x" + y + "(3=)" + power + "		");
                    x = power;
                }
                else System.out.print(x + "		");
                y = (y * y) % n;
                System.out.println(a + "^(2^" + (i+1) + ")" + "(3=)" + y);
                k /= 2;
                if(k == 1)break;
            }
            power = (x * y) % n;
            System.out.println("\		\		" + x + "x" + y + "(3=)" + power);
            return power;
        }
    

    模逆运算

        public static int modInverseShow(int d, int n){
            System.out.println("*************************************************************************");
            System.out.println("****NOTICE:["\" area should be replaced by blank so there is nothing]****");
            System.out.println("*************************************************************************");
            int up = n;
            int down = d;
            int inverseUp = 0;
            int inverse = 1;
            int times, temp;
            System.out.println("\		u		v		q");
            System.out.println(up + "		1		0		\");
            System.out.print(down + "		0		1		");
            for(;;) {
                times = up / down;
                System.out.println(times);
                temp = up - down * times;
                up = down;
                down = temp;
                temp = inverseUp - inverse * times;
                inverseUp = inverse;
                inverse = temp;
                System.out.print(down + "		\		" + inverse + "		");
                if(down == 1)return (inverse > 0) ? inverse : (inverse + n);
                if(down <= 0)return -1;
            }
        }
    

    注意:如果返回值为-1,可能出现意外情况(两数不互素等原因),请自行验算

  • 相关阅读:
    NOIP2014D2T2寻找道路(Spfa)
    【割点】【割边】tarjan
    NOIP2013D1T3货车运输(最大生成树+倍增lca)
    lca最近公共祖先(模板)
    人生第一次hash
    【模板】Tarjan求强连通分量
    【模板】链式前向星+spfa
    二叉树的三种遍历
    hdu 3549 最大流
    hdu 1532&&poj1273 基础最大流
  • 原文地址:https://www.cnblogs.com/blueflameashe/p/13168387.html
Copyright © 2011-2022 走看看