HDU 1212 Big Number 大数取模

Big Number

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/32768 K (Java/Others)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Total Submission(s): 6979????Accepted Submission(s): 4804




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.

?



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
  
  

?



Author

Ignatius.L

?



Source

杭电ACM省赛集训队选拔赛之热身赛

?

点击打开题目链接HDU1212

输入 A 和 B ,输出 A mod B ,A 的长度不超过1000,B 小于100000

先看下面三个公式:

(a + b) % n = ((a % n) + (b % n)) % n

(a – b) % n = ((a % n) – (b % n) + n) % n

ab % n = (a % n)(b % n) % n

注意在减法中,a % n 可能小于 b % n,要在结尾加上 n ,而在乘法中要注意

a % n 和 b % n 相乘是否会溢出。

对于本题,我们把大数写成“自左向右”的形式:1234 = ((1 * 10) + 2) * 10 + 3) * 10 + 4

然后用前面的公式,每步取模,像这样:

#include <cstdio>
#include <cstring>

int main()
{
    char n[1010];
    int m;
    while (~scanf ("%s%d",n,&m))
    {
        int len = strlen(n);
        int ans = 0;
        for (int i = 0; i < len; i++)   //每步取模
            ans = (int)((ans * 10 + n[i] - '0') % m);
        printf("%d\n",ans);
    }

    return 0 ;
}

当然也可以用Java中的大数,十分方便:

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			BigInteger n = scanner.nextBigInteger();	//输入
			BigInteger m = scanner.nextBigInteger();
			System.out.println(n.mod(m));				//取模
		}
	}
}

相关文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注