标签:
题目:给你两个b进制数p,m,求p mod m的余数的b进制表示。
分析:数论,大整数。可以转成10进制在转回去,这里直接处理b进制。
处理过程和10进制相同,移位减法即可(借位是+b)。
说明:写的有点复杂╮(╯▽╰)╭。
#include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> typedef struct _bn { int length; int data[1111]; }bignumber; bignumber bigNumber(char buf[]) { bignumber temp; temp.length = strlen(buf); for (int i = 0; buf[i]; ++ i) temp.data[i] = buf[temp.length-1-i]-'0'; return temp; } void bigNumberOutput(bignumber A) { int nowA = A.length-1; if (nowA == -1) printf("0"); while (nowA >= 0) printf("%d",A.data[nowA --]); printf("\n"); } bool biger(bignumber A, bignumber B) { int nowA = A.length-1, nowB = B.length-1; while (nowB >= 0) { if (A.data[nowA] > B.data[nowB]) return true; if (A.data[nowA] < B.data[nowB]) return false; nowA --; nowB --; } return true; } bignumber bigNumberSub(bignumber A, bignumber B, int base) { int nowA = A.length-1, nowB = B.length-1; while (nowB >= 0) A.data[nowA --] -= B.data[nowB --]; while (nowA < A.length) { if (A.data[nowA] < 0) { A.data[nowA] += base; A.data[nowA+1] -= 1; } ++ nowA; } while (A.length > 1 && !A.data[A.length-1]) -- A.length; return A; } bignumber bigNumberMod(bignumber A, bignumber B, int base) { while (A.length > B.length) { if (biger(A, B)) A = bigNumberSub(A, B, base); else{ A.data[A.length-2] += A.data[A.length-1]*base; A.data[A.length --] = 0; } } while (A.length == B.length && biger(A, B)) A = bigNumberSub(A, B, base); return A; } int main() { int base; char buf[1111]; while (~scanf("%d",&base) && base) { scanf("%s",buf); bignumber P = bigNumber(buf); scanf("%s",buf); bignumber M = bigNumber(buf); bigNumberOutput(bigNumberMod(P, M, base)); } return 0; }
标签:
原文地址:http://blog.csdn.net/mobius_strip/article/details/46535709