a^b(取模运算)

a^b(sdtbu oj 1222)

Description

对于任意两个正整数a,b(0 <= a, b < 10000)计算ab各位数字的和的各位数字的和的各位数字的和的各位数字的和。

Input

输入有多组数据,每组只有一行,包含两个正整数a,b。最后一组a=0,b=0表示输入结束,不需要处理。

Output

对于每组输入数据,输出ab各位数字的和的各位数字的和的各位数字的和的各位数字的和。

Sample Input

2 3
5 7
0 0

Sample Output

8
5

用到的知识点

  • $(a + b) \% mod = ((a \% mod) + (b \% mod)) \% mod$
  • $(a - b) \% mod = ((a \% mod) - (b \% mod) + mod) \% mod$
  • $(a * b) \% mod = ((a \% mod) * (b \% mod)) \% mod$
  • 一个数 mod 9 = 该数每一位之和 mod 9
  • 余数不为0,结果就是余数。余数为0,结果是9。

一些注意事项:

0的n次幂都为0

1的n次幂都为1

1000010000大概有1 + 4 * 10000位数字,假设每位最大9,所有位加起来最大360009

6位,每位最大9,所有位加起来最大54

2位,第一位最大5,第二位最大9,加起来最大14

最后结果比9小。

image-20200920172443915

image-20200920172840844

AC代码:

#include <cstdio>
#include <cstdlib>

int main()
{
    int a, b, i;
    while (~scanf("%d%d", &a, &b) && (a != 0 || b != 0))
    {
        if (a == 0)     // 特殊情况, 0的n次幂都是0
        {
            printf("0
");
            continue;
        }
        int ans = 1;
        for (i = 0; i < b; i++)     // 计算 (a * a * ... * a) % 9
        {
            ans = ((ans % 9) * (a % 9)) % 9;
        }
        if (ans)
            printf("%d
", ans);
        else            // ans是0, 说明余数为0, 最后结果应该是9
            printf("9
");
            // 比如 9 ** 9 = 387420489, %9 = 0
            // 3 + 8 + 7 + 4 + 2 + 0 + 4 + 8 + 9 = 45, %9 = 0
            // 4 + 5 = 9, %9 = 0
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yanhua-tj/p/13996573.html