• 【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,可能出现意外情况(两数不互素等原因),请自行验算

  • 相关阅读:
    国内外手机号码正则表达式
    apt安装Neo4j
    经典决策树模型
    自动文档摘要评价方法
    scrapy-splash解析javascript
    ubuntu安装splash
    iptables的删除命令中的相关问题
    ARTS第七周
    ARTS第六周
    ARTS第五周
  • 原文地址:https://www.cnblogs.com/blueflameashe/p/13168387.html
Copyright © 2020-2023  润新知