HCB


私信TA

用户名:uq_66496972241

访问量:1262

签 名:

等  级
排  名 2985
经  验 1993
参赛次数 1
文章发表 5
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

解题思路:

注意事项:

参考代码:


BigInteger的快速幂函数:

import java.math.BigInteger;
import java.util.*;

public class Main{
   public static void main(String[] args) {
       Scanner sc=new Scanner(System.in);
       BigInteger A=sc.nextBigInteger(),B=sc.nextBigInteger(),P=sc.nextBigInteger();
       System.out.println(A.modPow(B, P));
   }
}


算法解决:

import java.util.*;

public class Main{
   public static void main(String[] args) {
       Scanner sc=new Scanner(System.in);
       long A=sc.nextLong(),B=sc.nextLong(),P=sc.nextLong();
       System.out.println(fast_power(A,B,P));
   }

   //a^10=(a^2)^5=(a^2)*((a^2)^2)^2,即2^10=(2^2)^5=4^5,4^5=4*(4^2)^2
   //(a*b)%c=(a%c)*(b%c)
   public static long fast_power(long a,long b,long c) {
       long ans=1;
       a%=c;
       while(b!=0)
       {
           if(b%2==1)//if(b&1)——偶数的二进制最后一位为0,奇数为0,偶数&1为0,奇数&1为1
               ans=(ans*a)%c;
           a=(a*a)%c;
           b/=2;//b>>=1——一个数均分,相当于将其二进制数向右移一位
       }
       return ans;
   }
}


 

0.0分

2 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区