如何运用同余定理求余数【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.
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.
我们先了解下如何运用同余定理求余数:
对大数求余数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /*例如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; } |
对幂求余数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /* * 对幂取模如对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)两个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #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; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 用一种新的分类方法梳理设计模式的脉络