题目相关
题目链接
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} 1≤N≤1018
- 1 ≤ M ≤ 10000 1 ≤ M ≤ 10000 1≤M≤10000
题解报告
题目翻译
给两个正整数 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
⌊M10N⌋modM,因此,我们考虑计算
⌊
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}
⌊M10N−kM2⌋≡⌊M10N−kM⌋≡⌊M10N⌋−kM≡⌊M10N⌋(modM)(k∈Z
数据范围估计
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)。