大数取余
对3取余:
#include "stdio.h"
#include "string.h"
int main()
{ int c; int mod = 0;
/*如果没有按下Ctrl+C 就一直在while循环里面判断*/
while ((c = getchar()) != EOF){
if (c == '\n')
{/*输出结果*/ printf("%d\n", mod); mod = 0; }
else
{
/*递归计算*/ // c in '0'...'9' c -= '0'; mod = mod +c; mod = (mod*10)%3;
}
}
return 0;
}
对任何数取余:
A是一个大数,B是一个int型的整数,求A%B。A可能无法用已知数据类型存储,直接取余很困难。
可以设置变量t从大数第一位向后遍历赋值,如果大于mod就取余更新,最后t的值就是所求答案。
例:
123 % 4 取一个中间变量t=0
1<4 t=1
— 2 t=1*10+2=12>4 t=t%4=0
— 3 t=0+3=3 t=t%4=3
——————– 余数 3
算法:
int MOD(string a,int mod)
{
int len=a.length();
int t=0;
for( int i = 0; i < len; i++ )
{
t*=10;
t+=a[i]-'0';
if( t >= mod )
t=t%mod;
}
return t;
}
————————————————
版权声明:本文为CSDN博主「EaShion1994」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/EaShion1994/article/details/43916637

浙公网安备 33010602011771号