二分【2】快速幂 单峰序列

目录

快速幂

递归写法(a^b%m)

迭代写法 

 单峰序列


快速幂

a^n

n为奇数,转化为a*a^(n-1)

n为偶数,转化为计算b=a^(n/2),在计算b^2

a^b%m)

递归写法(a^b%m)

#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
ll a,b,m;
ll kuaisumi(ll a,ll b,ll m)
{	 if(b==0) {return 1; }
	if(b%2==1) {return (a%m)*kuaisumi(a,b-1,m)%m;}//b奇数
	else
	{
		ll A=kuaisumi(a,b/2,m)%m;return A*A%m;
	 } 
	 //缺一个递归出口:

	
	 
}

int main()
{
	scanf("%lld %lld %lld",&a,&b,&m);
	printf("%lld",kuaisumi(a,b,m));
	
}
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
ll a,b,m;
ll kuaisumi(ll a,ll b,ll m)
{	 if(b==0) {return 1; }
	if(b%2==1) {return (a%m)*kuaisumi(a,b-1,m)%m;}//b奇数
	else
	{
		ll A=kuaisumi(a,b/2,m)%m;return A*A%m;
	 } 
	 //缺一个递归出口:

	
	 
}

int main()
{
	scanf("%lld %lld %lld",&a,&b,&m);
	printf("%lld",kuaisumi(a,b,m));
	
}

迭代写法 

#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
ll a,b,m;

int main()
{
	scanf("%lld %lld %lld",&a,&b,&m);
	ll ans=1;
	while(b>0)
	{if(b&1) {ans=ans*a%m;b--;}
	else {b/=2;a=a*a%m;
	}
	 } 
	printf("%lld",ans);
	
}

 单峰序列

左增右减,找峰顶

#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=100001;int n,num[N]; 
int bis(int a[],int left,int right)
{
while(left<right)
{
	int mid=left+(right-left)/2;
	if(a[mid]>a[mid-1])
	{
		if(a[mid]>a[mid+1]) return mid;
		else left=mid+1;
	}
	else right=mid-1;

}
return left;	
}


int main()
{
	scanf("%d",&n);for(int i=0;i<n;i++) scanf("%d",&num[i]);
	
	printf("%d",bis(num,0,n-1));
}

预告:二分【3】 旋转数组 

相关推荐

  1. 二分【2快速 序列

    2024-06-14 16:08:07       8 阅读
  2. 快速 FastPower

    2024-06-14 16:08:07       45 阅读
  3. 【算法】数论---快速

    2024-06-14 16:08:07       42 阅读
  4. 【数论】矩阵快速

    2024-06-14 16:08:07       30 阅读
  5. 快速算法详解

    2024-06-14 16:08:07       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-14 16:08:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-14 16:08:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-14 16:08:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-14 16:08:07       18 阅读

热门阅读

  1. 现在的AI大模型,业已进入到深度洗牌期

    2024-06-14 16:08:07       9 阅读
  2. 数据中心一体化智能运维实践

    2024-06-14 16:08:07       7 阅读
  3. cfa复习的最后冲刺阶段刷什么题目最有效果

    2024-06-14 16:08:07       7 阅读
  4. 新人学习笔记之(注释和关键字)

    2024-06-14 16:08:07       6 阅读
  5. Python大作业(实训)任务书

    2024-06-14 16:08:07       7 阅读
  6. cfa复习有哪些中文教材

    2024-06-14 16:08:07       8 阅读
  7. HCIP认证笔记(单选题)

    2024-06-14 16:08:07       6 阅读