求循环小数的开始位置和循环长度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chen134225/article/details/82228997

题目:

给出被除数和除数,求出循环小数的开始位置(小数点之后的位数)和循环长度

输入描述:

第一行包含两个数字分别是被除数a和除数b (1<= a, b <= 1000000)

输出描述:

输出一行,包含一个两个数字,分别表示循环小数的开始位置和循环体的长度(无循环则开始位置为结束位置,长度为0)

输入
1 3
输出
0 1

输入
5 4
输出
2 0

代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

class Solution{
public:
    void Func1(int a, int b)
    {
        int start, cnt = 0;
        a = a%b;
        if(a == 0){
            cout << 0 << ' ' << 0 << endl;
            return;
        }
        map<int, int> datas;
        map<int, int>::iterator item;
        datas.insert(make_pair(a, 0));
        do{
            a = 10*a%b;
            item = datas.find(a);
            if(item != datas.end()){
                start = item->second;
                break;
            }
            datas.insert(make_pair(a, ++cnt));
        }while(a);
        if(a == 0){
            cout << cnt << ' ' << 0 << endl;
            return;
        }
        cout << start << ' ' << (cnt+1-start) << endl;
    }
};

int main()
{
    int a, b;
    cin >> a >> b;
    Solution().Func1(a, b);
    return 0;
}

参考资料:

https://blog.csdn.net/qq742762377/article/details/80572811?tdsourcetag=s_pctim_aiomsg

猜你喜欢

转载自blog.csdn.net/chen134225/article/details/82228997