杭电 ACM 1212 各位大虾看看错哪儿了?给代码也行!
题目如下:
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
我的代码:
#include <stdio.h>
#include <string.h>
_int64 forlength(_int64 num)
{
_int64 length=0;
while(num>=10)
{
num=num/10;
length++;
}
return length+2;
}
void main()
{
_int64 i,j,k,num,length1,length2,value,record2,a[167],record1;
char word[1000];
while(scanf("%s",word)!=EOF)
{
scanf("%I64d",&num);
if(num!=0)
{
length1=forlength(num);
length2=strlen(word);
i=0;
j=0;
k=0;
for(i=0;i<=length2/length1&&k<length2;i++)
{
value=0;
if(i==0&&word[0]=='-') k=1;
else j=0;
while(k<length2&&j++<length1)
value=value*10+word[k++]-48;
a[i]=value;
}
record1=0;
record2=i;
for(i=0;i<record2;i++)
{
a[i]=(record1*100000+a[i])%num;
record1=a[i];
}
if(word[0]=='-')
printf("%I64d\n",-record1);
else
printf("%I64d\n",record1);
}
}
}
[解决办法]
我一开始也想复杂了,后来发现挺简单的。
直接累加取余就可以了。就20多行代码。
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[1000];
int b;
int i;
int sum;
int lenA;
while (scanf("%s",a) != EOF)
{
scanf("%d",&b);
sum = 0;
lenA = strlen(a);
// negative, start from a[1]
if(a[0] == '-')
for(i=1;i<lenA;i++)
sum = (sum*10 - (a[i]-48)) % b;
// positive, start from a[0]
else
for(i=0;i<lenA;i++)
sum = (sum*10 + (a[i]-48)) % b;
printf("%d\n", sum);
}
return 0;
}
[解决办法]
3楼程序符合题中“my program contains less than 25 lines”的提示。
LZ程序的思路是可行的,但有2个问题:
1 既然在a[i]=(record1*100000+a[i])%num;中按100000计算,那么length1应是常数5,函数forlength没有必要。
2 在把word分解到a中时,用i<=length2/length1控制长度错了,应再定义一个变量count并改为:
count=length2/length1;
if (length2%length1) count++;
for(i=0;i<=count&&k<length2;i++)