ACM基本代码模板之快速幂,质数分解,素数筛法

一、快速幂

/*
	快速幂; 
        时间复杂度O(logb)
	输入 a ,b ,m ,输出 (a*b)%m; 
*/ 
#include<bits/stdc++.h>
typedef long long LL;
LL pow_mod(LL a , LL b, LL m)
{
	LL temp=a , ans=1;
	while(b)
	{
		if(b & 1)
			ans = ans*temp%m;
		temp = temp*temp%m;
		b >>= 1;
	}
	return ans;
}
int main()
{
	LL a ,b ,m;
	while(~scanf("%lld%lld%lld",&a,&b,&m))
	{
		printf("%lld\n",pow_mod(a,b,m));
	 } 
	return 0;
 } 

二、质数分解

/*
	质数分解
        时间复杂度:O(sqrt(n))
	输入n,输出n的质数幂乘积
	base数组存放质数,power数组存放对应质数的幂
*/ 
#include<bits/stdc++.h>
using namespace std;
void factor(int n , int *base , int *power ,int &cnt)
{
	cnt = 0;
	int i ,temp=sqrt(n);
	for(i = 2; i <= temp; i++)
	{
		if(n%i == 0)
		{
			base[++cnt] = i;
			power[cnt] = 0;
		}
		while(n%i == 0)
		{
			power[cnt]++;
			n /= i;
		}
	}
	if(n != 1)
	{
		base[++cnt] = n;
		power[cnt] = 1;
	}
}
int main()
{
	int n ,power[50] ,base[50] ,cnt;
	while(cin >> n)
	{
		factor(n,base,power,cnt);
		cout << base[1] << "^(" <<power[1] << ')';
		for(int i = 2; i <= cnt; i++)
			cout << '+' << base[i] << "^(" << power[i] << ')';
		cout << endl;
	}
	return 0;
}

三、质数筛法

/*
	素数筛法
	时间复杂度O(N) 
	求[2,N)以内的所有素数
	ans数组为素数表
*/ 
#include<bits/stdc++.h>
#define N 10000
void solve(int *ans ,int &cnt)
{
	bool valid[N];
	memset(valid,true,sizeof(valid));
	for(int i = 2; i < N; i++)
	{
		if(valid[i])
			ans[cnt++] = i;
		for(int j = 0;((j<cnt) && (i*ans[j]<N)); j++)
			valid[i*ans[j]] = false;
	}
}
int main()
{
	freopen("D://prime_in_10000.txt","w",stdout);
	int ans[N] ,cnt=0;
	solve(ans ,cnt);
	for(int i = 0; i < cnt; i++)
		printf("%d,",ans[i]);
	return 0;
}

四、gcd和lcm

//输入a,b,输出gcd(a,b),lcm(a,b); 
#include<bits/stdc++.h>
int gcd(int a, int b)
{
	return b==0 ? a : gcd(b , a%b);
}
int lcm(int a , int b)
{
	return (a*b) / gcd(a,b);
}
int main()
{
	int a ,b;
	while(~scanf("%d%d",&a,&b))
		printf("gcd=%d  lcm=%d\n",gcd(a,b),lcm(a,b));
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值