10929 - You can say 11
Time limit: 3.000 seconds
Introduction to the problem
Your job is, given a positive number N, determine if it is a multiple of eleven.
Description of the input
The input is a file such that each line contains a positive number. A line containing the number 0 is the end of the input. The given numbers can contain up to 1000 digits.
Description of the output
The output of the program shall indicate, for each input number, if it is a multiple of eleven or not.
Sample input:
112233
30800
2937
323455693
5038297
112234
0
Sample output
112233 is a multiple of 11.
30800 is a multiple of 11.
2937 is a multiple of 11.
323455693 is a multiple of 11.
5038297 is a multiple of 11.
112234 is not a multiple of 11.
方法1:直接从个位数开始mod 11计算。
/*0.026s*/
#include<cstdio>
#include<cstring>
char s[1005];
int main(void)
{
int remainder;
while (gets(s), strcmp(s, "0"))
{
remainder = 0;
for (int i = 0; s[i]; i++)
remainder = (remainder * 10 + (s[i] & 15)) % 11;
if (remainder) printf("%s is not a multiple of 11.\n", s);
else printf("%s is a multiple of 11.\n", s);
}
return 0;
}
方法2:若一个整数的奇位数字之和与偶位数字之和的差能被11整除,则这个数能被11整除。
证明:比如num = 10000a4+1000a3+100a2+10a1+a0=(a4+a2+a0-a3-a1)+(9999a4+99a2+1001a3+11a1)
因为11 | 99,所以11 | (9900+99)
因为11 | 1111,所以11 | (1111-110)
所以...
/*0.025s*/
#include<cstdio>
#include<cstring>
char s[1005];
int main(void)
{
int l, i, sum;
while (gets(s), strcmp(s, "0"))
{
l = strlen(s), sum = 0;
for (i = 0; i < l; i += 2) sum += s[i] & 15;
for (i = 1; i < l; i += 2) sum -= s[i] & 15;
if (sum % 11) printf("%s is not a multiple of 11.\n", s);
else printf("%s is a multiple of 11.\n", s);
}
return 0;
}

本文介绍两种高效算法来判断一个大数(最多可达1000位)是否能够被11整除。一种是从个位数开始进行mod 11计算,另一种则是通过比较奇数位和偶数位数字之和的差值。
150

被折叠的 条评论
为什么被折叠?



