题解:P15798 [GESP202603 五级] 有限不循环⼩数

· · 题解

题目大意

给定 l, r,求出 \dfrac 1 l, \dfrac 1 {l+1}, \dots, \dfrac 1 r 中有限不循环的数的个数。

解题思路

我们可以先打表观察一下:

\dfrac 1 1 = 1 \dfrac 1 2 = 0.5 \dfrac 1 3 = 0.333333\dots \dfrac 1 4 = \dfrac 1 2 \times \dfrac 1 2 = 0.25 \dfrac 1 5 = 0.2 \dfrac 1 6 = \dfrac 1 2 \times \dfrac 1 3 = 0.166666\dots

初略观察很容易发现当仅含有质因子 2, 5 时,才符合条件。

证明:

若 \dfrac{1}{a} 是有限小数,设其小数点后有 k 位,则可写成 \dfrac{m}{10^k}(m 为整数),即 \dfrac{1}{a} = \dfrac{m}{10^k},即 a = \dfrac{10^k}{m}。

所以 m 必须是 10^k 的约数,从而 a 只可能含有 2 和 5 作为质因子。

AC_Code

#include <iostream>
using namespace std;
int main()
{
    int l, r;
    cin >> l >> r;
    int res = 0;
    for (int i = l; i <= r; ++ i )
    {
        int x = i;
        while (x % 2 == 0)
            x /= 2;
        while (x % 5 == 0)
            x /= 5;
        res += x == 1;
    }
    cout << res << endl;
}