如何运用同余定理求余数【hdoj 1212 Big Number【大数求余数】】

Big Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5930    Accepted Submission(s): 4146


Problem Description
As we know, Big Number is always troublesome. But it's really important in our ACM. And today, your task is to write a program to calculate A mod B.

To make the problem easier, I promise that B will be smaller than 100000.

Is it too hard? No, I work it out in 10 minutes, and my program contains less than 25 lines.
 

 

Input
The input contains several test cases. Each test case consists of two positive integers A and B. The length of A will not exceed 1000, and B will be smaller than 100000. Process to the end of file.
 

 

Output
For each test case, you have to ouput the result of A mod B.
 

 

Sample Input
2 3
12 7
152455856554521 3250
 

 

Sample Output
2
5
1521
 
此题需要用到同余定理:
   常用的同余定理有以下三种:
   (1)((A mod m)*(B mod m))mod m ==(A*B)mod m
   (2)((A mod m)+(B mod m))mod m ==(A+B)mod m
   (3)((A mod m)-(B mod m)+ m)mod m ==(A-B)mod m
    在减法中,由于a mod n 可能小于b mod n,需要在结果上加上n.
   我们先了解下如何运用同余定理求余数:
   对大数求余数:
 
/*例如10000对m求余:
* 10000%m
* ==(10%m*1000%m)%m
* ==(10%m*(10%m*100%m)%m)%m  
* ==(10%m*(10%m*(10%m*10%m)%m)%m)%m
* 用代码表示就是:
* 假设10000是字符串长度是len 
*/

/*
* 如123对m求余 
* 123%m 
* ==((12%m*10%m)%m+3%m)%m 
* ==(((10%m+2%m)%m*10%m)%m+3%m)%m 
* ==((((1%m*10%m)%m+2%m)%m*10%m)%m+3%m)%m 
*/
gets(str);
int ans=0;
for(i=0;i<len;i++) 
{
	ans=ans*10+str[i];
	ans=ans%m;
}

 对幂求余数:

/*
* 对幂取模如对37的4次方取模 
* (37*37*37*37)%m 
*  ==(37%m*(37*37*37)%m)%m 
*  ==(37%m*(37%m*(37*37)%m)%m)%m 
*  ==(37%m*(37%m*(37%m*37%m)%m)%m)%m
*/ 
//求n^m%1000 
s=n;
for(i=1;i<m;i++)
{
	s=s*n;
	s=s%1000;	
}

 

详细的模运算请参考:http://blog.csdn.net/chocolate_22/article/details/6458029

此题用到了(1)(2)两个:
#include<stdio.h>
#include<string.h>
#define MAX 1100
int main()
{
	int n,m,j,i,s,t;
	char p[MAX];
	while(scanf("%s",p)!=EOF)
	{
		scanf("%d",&n);
		int l=strlen(p);
		s=0;
		for(i=0;i<l;i++)
		{
			s=s*10+p[i]-'0';
			s=s%n;
		}
		printf("%d\n",s);
	}
	return 0;
}

 

你可能感兴趣的:(number)