POJ 1995

简单的快速幂取模题

但要注意由于a可能很大,相乘会超范围,所以乘前要先模

#include <iostream>
#include <cstdio>
using namespace std;

int quick(int a,int b,int m){
	int ans=1;
	a%=m;
	while(b){
		if(b&1){
			ans=(ans*a)%m;
			b--;
		}
		a=(a*a)%m;
		b/=2;
	}
	return ans;
}

int main(){
	int t;
	scanf("%d",&t);
	int m,n; int ans,a,b;
	while(t--){
		ans=0;
		scanf("%d",&m);
		scanf("%d",&n);
		for(int i=0;i<n;i++){
			scanf("%d%d",&a,&b);
			ans=(ans+quick(a,b,m))%m;
		}
		printf("%d\n",ans%m);
	}
	return 0;
}

  

时间: 2024-10-12 09:30:44

POJ 1995的相关文章

poj 1995 裸快速幂

1. poj 1995  Raising Modulo Numbers 2.链接:http://poj.org/problem?id=1995 3.总结:今天七夕,来发水题纪念一下...入ACM这个坑也快一年了 题意:求ai^bi和模m.裸快速幂 #include<iostream> #include<cstring> #include<cmath> #include<queue> #include<algorithm> #include<

POJ 1995 Raising Modulo Numbers (数论-整数快速幂)

Raising Modulo Numbers Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 4379   Accepted: 2516 Description People are different. Some secretly read magazines full of interesting girls' pictures, others create an A-bomb in their cellar, oth

快速幂取模(POJ 1995)

http://poj.org/problem?id=1995 以这道题来分析一下快速幂取模 a^b%c(这就是著名的RSA公钥的加密方法),当a,b很大时,直接求解这个问题不太可能 利用公式a*b%c=((a%c)*b)%c 每一步都进行这种处理,这就解决了a^b可能太大存不下的问题,但这个算法的时间复杂度依然没有得到优化 由此可以用快速幂算法优化: http://www.cnblogs.com/qlky/p/5020402.html 再结合取模公式: (a + b) % p = (a % p

POJ 1995 Raising Modulo Numbers (快速幂模板)

Raising Modulo Numbers Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 4938   Accepted: 2864 Description People are different. Some secretly read magazines full of interesting girls' pictures, others create an A-bomb in their cellar, oth

POJ 1995 Raising Modulo Numbers 【快速幂取模】

题目链接:http://poj.org/problem?id=1995 解题思路:用整数快速幂算法算出每一个 Ai^Bi,然后依次相加取模即可. #include<stdio.h> long long quick_mod(long long a,long long b,long long c) { long long ans=1; while(b) { if(b&1) { ans=ans*a%c; } b>>=1; a=a*a%c; } return ans; } int

POJ 1995 Raising Modulo Numbers(快速幂)

嗯... 题目链接:http://poj.org/problem?id=1995 快速幂模板... AC代码: 1 #include<cstdio> 2 #include<iostream> 3 4 using namespace std; 5 6 int main(){ 7 long long N, M, n, a, b, c, sum = 0; 8 scanf("%lld", &N); 9 while(N--){ 10 scanf("%ll

POJ 1995 (快速幂)

这道题普通做法会发生溢出且会超时,应当用快速幂来求解. 快速幂讲解 1 #include <cstdio> 2 #include <cmath> 3 using namespace std; 4 int main(){ 5 int Z; 6 scanf("%d",&Z); 7 while(Z--){ 8 int M, H; 9 unsigned long long sum = 0; 10 scanf("%d%d",&M,&am

Raising Modulo Numbers(POJ 1995 快速幂)

Raising Modulo Numbers Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 5934   Accepted: 3461 Description People are different. Some secretly read magazines full of interesting girls' pictures, others create an A-bomb in their cellar, oth

POJ 1995 Raising Modulo Numbers (快速幂取余)

#include<iostream> using namespace std; int quick_mod(int a,int b,int m) //模板 { a=a%m; int ans=1; while(b) { if(b&1) { ans=(ans*a)%m; } b>>=1; a=(a*a)%m; } return ans; } int main() { int size; cin>>size; int m, h, a, b; while(cin>