HDUOJ 1212 大数取余 C++版+java版
Big Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10701 Accepted Submission(s): 7154
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
Recommend
Eddy
我自己写的:
题意:大数取余
用一个string 接受第一个输入,
其实就是模拟一下除法运算。
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int main()
{
string a;
int n[1005];
int mod; //表示除数
int i,j;
int quotient[1000]; //表示商
int residue; // 表示余数
while(cin>>a>>mod)
{
memset(n,0,sizeof(n));
memset(quotient,0,sizeof(quotient));
int current;
int len=a.length();
for(i=0;i<len;i++)
{
n[i]=a[i]-'0';
}
residue=0;
int pre=0;
for(j=0;j<i;)
{
current=residue; // 把余数赋给当前数,然后进行运算
while(current<mod) // 找到一个大于除数的数
{
current=current*10+n[j];
j++;
if(j>i)
{
residue=current/10;
break;
}
}
if(j>i)
break;
residue=current%mod;
quotient[pre]=current/mod; //存商
pre=j;
}
cout<<residue<<endl;
}
return 0;
}
看完评论区别人写的:
好精彩!
数学不好的痛
原理:
(a+b)%c = ((a%c)+(b%c))%c
(a*b)%c = ((a%c)*(b%c))%c
#include<stdio.h>
void main()
{
char x[1000];
int n;
while(scanf("%s %d",x,&n)!=EOF)
{
int i,t=0;
for(i=0;x[i];i++)
{
t=t*10+(x[i]-'0');
t%=n;
}
printf("%d\n",t);
}
}
java版
简单粗暴
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
BigDecimal a = sc.nextBigDecimal();
int b = sc.nextInt();
System.out.println(a.remainder(new BigDecimal(b)));
}
}
}
精彩,精彩
不懂的话,问我哦,乐意解答