求循环节的长度

两个整数做除法,有时会产生循环小数,其循环部分称为:循环节

比如,11/13 = 0.846153846153...其循环节为846153共六位。

  • #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int f(int n, int m) {
        n = n % m;
        //不定长数组v
        vector<int> v;
        for(;;) {
            //将当前的余数加入到尾部
            v.push_back(n);
            //和除法运算原理相同
            n *= 10;
            n = n % m;
            if (n == 0) return 0;//已整除,没有余数
            //find()函数查找在指定范围内第一次出现目标字符的位置,如果没找到返回v.end()
            if (find(v.begin(), v.end(), n) != v.end()) {
                return (int)(v.end() - find(v.begin(), v.end(), n));
            }
        }
    }
    int main() {
        int n, m;
        cin >> n >> m;
        cout << f(n, m) << endl;
        return 0;
    }
    

猜你喜欢

转载自blog.csdn.net/weixin_41462017/article/details/86477020