zoukankan      html  css  js  c++  java
  • 蓝桥杯 算法提高——快速幂

    发现官网给的免费蓝桥杯VIP5月初就过期了,从今天开始每天抽空做些题目

    试题

    资源限制、时间限制:1.0s   内存限制:256.0MB
    问题描述
      给定A, B, P,求(A^B) mod P。
    输入格式
      输入共一行。
      第一行有三个数,N, M, P。
    输出格式
      输出共一行,表示所求。
    样例输入
    2 5 3
    样例输出
    2
    数据规模和约定
      共10组数据
      对100%的数据,A, B为long long范围内的非负整数,P为int内的非负整数。

    解题报告:

    太久没打算法题,连快速幂的幂都给模上了,错了2遍才发现。。。

    不加快速乘也能过,但是为了掌握一下快速乘(刚学,原来这么简单),也写上去了

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int inf=0x3f3f3f3f;
     4 typedef long long ll;
     5 ll kadd(ll a,ll b,ll p) {    ///快速乘 
     6     ll ans=0;
     7     while(b) {
     8         if(b&1) ans=(ans+a)%p;
     9         a=(a<<1)%p;
    10         b>>=1;
    11     }
    12     return ans;
    13 }
    14 ll kpow(ll a, ll b, ll p) {    ///快速幂 
    15     ll ans=1;
    16     while(b) {
    17         if(b&1) ans=kadd(ans,a,p);
    18         a=kadd(a,a,p);
    19         b>>=1;
    20     }
    21     return ans;
    22 }
    23 int main()
    24 {
    25     ll a,b,p;
    26     cin>>a>>b>>p;
    27     ll res=kpow(a%p,b,p);
    28     cout<<res<<endl;
    29     return 0;
    30 }
    View Code
  • 相关阅读:
    Spring spEL
    Spring 使用外部部署文件
    Spring 自动装配
    spring 属性配置细节
    hdu 1054 Strategic Game
    fzu 2037 Maximum Value Problem
    将博客搬至CSDN
    HDU 4714 Tree2Cycle
    HDU 1009 The Shortest Path in Nya Graph
    POJ 1942 Paths on a Grid 组合数的优化
  • 原文地址:https://www.cnblogs.com/wuliking/p/12656044.html
Copyright © 2011-2022 走看看