AtCoder题解 —— AtCoder Regular Contest 111 —— A - Simple Math 2 —— 数论:快速幂

题目相关

题目链接

AtCoder Regular Contest 111 A 题,https://atcoder.jp/contests/arc111/tasks/arc111_a

Problem Statement

Given positive integers N N N and M M M, find the remainder when ⌊ 1 0 N M ⌋ \left \lfloor \frac{10^N}{M}\right \rfloor M10N is divided by M M M.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample 1

Sample Input 1

1 2

Sample Output 1

1

Explaination

We have ⌊ 1 0 1 5 ⌋ = 5 \left \lfloor \frac{10^1}{5}\right \rfloor=5 5101=5, so we should print the remainder when 5 5 5 is divided by 2 2 2, that is 1 1 1.

Sample 2

Sample Input 2

2 7

Sample Output 2

0

Sample 2

Sample Input 2

1000000000000000000 9997

Sample Output 2

9015

Constraints

  • 1 ≤ N ≤ 1 0 18 1 ≤ N ≤ 10^{18} 1N1018
  • 1 ≤ M ≤ 10000 1 ≤ M ≤ 10000 1M10000

题解报告

题目翻译

给两个正整数 N N N M M M,请求 ⌊ 1 0 N M ⌋ \left \lfloor \frac{10^N}{M}\right \rfloor M10N 的结果对 M M M 取余是多少。

题目分析

本题是一个标准的数学题。
由于 N N N 的最大值是 1e18,因此,我们没有办法直接计算出 1 0 N 10^N 10N 的结果,这是一个天文数字,已经超过了 long long 能表示的范围。因此,我们需要使用快速幂取余的技巧。
本题最终计算结果为 ⌊ 1 0 N M ⌋ m o d M \left \lfloor \frac{10^N}{M}\right \rfloor mod \quad M M10NmodM,因此,我们考虑计算 ⌊ 1 0 N M 2 ⌋ \left \lfloor \frac{10^N}{M^2}\right \rfloor M210N 的结果,下面我们来证明这两个结果是一样的。
⌊ 1 0 N − k M 2 M ⌋ ≡ ⌊ 1 0 N M − k M ⌋ ≡ ⌊ 1 0 N M ⌋ − k M ≡ ⌊ 1 0 N M ⌋ ( m o d M ) ( k ∈ Z \left \lfloor \frac{10^N-kM^2}{M}\right \rfloor \equiv \left \lfloor \frac{10^N}{M}-kM\right \rfloor \equiv \left \lfloor \frac{10^N}{M}\right \rfloor -kM\equiv \left \lfloor \frac{10^N}{M}\right \rfloor (mod \quad M) (k\in \mathbb{Z} M10NkM2M10NkMM10NkMM10N(modM)(kZ

数据范围估计

N N N 的最大值是 1e18,必须使用 long long。

AC 参考代码

//https://atcoder.jp/contests/arc111/tasks/arc111_a
//A - Simple Math 2
#include <bits/stdc++.h>

using namespace std;

//如果提交到OJ,不要定义 __LOCAL
//#define __LOCAL

typedef long long ll;

long long ModePower(ll a, ll b, ll mod) {
    ll ans=1;
    a %= mod;
    while (b>0) {
        if (1==b%2) {
            ans = (ans*a)%mod;
        }
        b/=2;
        a=(a*a)%mod;
    }
    return ans;
}

int main() {
#ifndef __LOCAL
    //这部分代码需要提交到OJ,本地调试不使用
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#endif
    ll n,m;
    cin>>n>>m;
    ll r=ModePower(10, n, m*m);
    cout<<r/m<<"\n";
#ifdef __LOCAL
    //这部分代码不需要提交到OJ,本地调试使用
    system("pause");
#endif
    return 0;
}

在这里插入图片描述

时间复杂度

O ( l o g N ) O(logN) O(logN)

空间复杂度

O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力的老周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值