Basic remains
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5221 | Accepted: 2203 |
Description
Given a base b and two non-negative base b integers p and m, compute p mod m and print the result as a base b integer. p mod m is defined as the smallest non-negative integer k such that p = a*m + k for some integer a.
Input
Input consists of a number of cases. Each case is represented by a line containing three unsigned integers. The first, b, is a decimal number between 2 and 10. The second, p, contains up to 1000 digits between 0 and b-1. The third, m, contains up to 9 digits
between 0 and b-1. The last case is followed by a line containing 0.
Output
For each test case, print a line giving p mod m as a base-b integer.
Sample Input
2 1100 101 10 123456789123456789123456789 1000 0
Sample Output
10 789
给出一个base进制的数,base的范围好在在2到10之间。然后给出在base进制下的p与m,求在base进制下的p%m。
来回的进制转换。
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;
int base;
string num;
string m;
int change(string n)
{
int i;
int sum = 0;
int len = n.length();
for (i = 0; i < len; i++)
{
sum = sum*base + n[i] - '0';
}
return sum;
}
void res(int mod)
{
int i, n, a[500];
int len = num.length();
int res = 0;
for (i = 0; i < len; i++)
{
res = (res*base + num[i] - '0') % mod;
}
//转换成base进制
n = 0;
if (res != 0)
{
while (res != 0)
{
a[n++] = res % base;
res = res / base;
}
for (i = n - 1; i >= 0; i--)
{
printf("%d", a[i]);
}
}
else
{
printf("0");
}
printf("\n");
}
int main()
{
//freopen("i.txt", "r", stdin);
//freopen("o.txt", "w", stdout);
int mod;
while (cin >> base)
{
if (base == 0)
break;
cin >> num >> m;
mod = change(m);
res(mod);
}
//system("pause");
return 0;
}