数论初步之大整数取模(同余取模)

来源:互联网 发布:北京行知打工子弟学校 编辑:程序博客网 时间:2024/06/08 09:44

首先应该是把整数写成"自左向右"的形式,例如 123 = (1 * 10 + 2) * 10 + 3;

有了这个就很容易看出 123 % m =  (1 * 10 + 2) * 10 + 3   % m;

这样就可以一步一步的取模了

贴出代码:

/* *大整数的取模取模 *运用到的是同于取模 *如果有需要改正的 *请指出,呵呵 *题目描述:输入正整数,n和m,输出n % m的值, n <= 10^100, m <= 10^9  */#include <stdio.h>#include <iostream>#include <string.h>#include <string>using namespace std;const int start = '0';int main(){char str[111];int m;scanf("%s %d", str, &m);int n = strlen(str);int ans = 0;for (int i = 0; i < n; i++){ans = (int)((long long)ans * 10 + str[i] - start) % m;}printf("%d\n", ans);system("pause");return 0; }


原创粉丝点击