UVA10494 If We Were a Child Again【大数除法】

“Oooooooooooooooh!
    If I could do the easy mathematics like my school days!!
    I can guarantee, that I’d not make any mistake this time!!”
    Says a smart university student!!
    But his teacher even smarter – “Ok! I’d assign you such projects in your software lab. Don’t be so sad.”
    “Really!!” – the students feels happy. And he feels so happy that he cannot see the smile in his teacher’s face.
    The first project for the poor student was to make a calculator that can just perform the basic arithmetic operations.
    But like many other university students he doesn’t like to do any project by himself. He just wants to collect programs from here and there. As you are a friend of him, he asks you to write the program. But, you are also intelligent enough to tackle this kind of people. You agreed to write only the (integer) division and mod (% in C/C++) operations for him.
在这里插入图片描述
Input
Input is a sequence of lines. Each line will contain an input number. One or more spaces. A sign (division or mod). Again spaces. And another input number. Both the input numbers are nonnegative integer. The first one may be arbitrarily long. The second number n will be in the range (0 < n < 2^31).
Output
A line for each input, each containing an integer. See the sample input and output. Output should not contain any extra space.
Sample Input
110 / 100
99 % 10
2147483647 / 2147483647
2147483646 % 2147483647
Sample Output
1
9
1
2147483646

问题链接UVA10494 If We Were a Child Again
问题简述:(略)
问题分析
    这个题是计算大数的余数和模除结果,被除数是大数,除数是一般的整数。大数模除则根据模除定律进行,可以从高位开始算,不需要做大数的计算。而大数除法则跟竖式除法计算原理是一样的,也是从高位算起。
    这个题十分经典!!!
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA10494 If We Were a Child Again */

#include <bits/stdc++.h>

using namespace std;

const int N = 1e7;
char s[N], ans[N];

int main()
{
    char op;
    long long n, a;
    int k;
    while(~scanf("%s %c %lld", s, &op, &n)) {
        a = 0, k = 0;
        for(int i = 0; s[i]; i++) {
            a = a * 10 + s[i] - '0';
            ans[k++] = a / n + '0';
            a = a % n;
        }
        ans[k] = '\0';

        if(op == '%')
            printf("%lld\n", a);
        else if(op == '/') {
            int i = 0;
            while(ans[i] == '0')
                i++;
            if(ans[i] == '\0') i--;     // 需要考虑结果为0的情况
            for(; i <= k - 1; i++)
                putchar(ans[i]);
            putchar('\n');
        }
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tigerisland45/p/10386823.html
we