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

具体题目如下图。

 循环小数中,一个循环内相同的数是不会出现两次的,循环数的范围又在0~9,所以可以使用桶的思想。

#include <iostream>
#include <vector>
using namespace std;

int main() {
	int x;
	int y;
	cin >> x >> y;

	int rest = -1, index = 0;
	vector<int> vec(y, -1);//记录循环中出现了哪些数

	while (true) {
		rest = x % y;
		if (rest == 0) {//除断,没有循环
			cout << index << " 0" << endl;
			break;
		}
		else {//没有除断时,如果这个循环数没有出现过,则将桶中该数置为1,否则就是进入了第二个循环
			index++;
			if (vec[rest] == -1) {
				vec[rest] = index;
				x = rest * 10;
			}
			else {
				cout << vec[rest] - 1 << " " << index - vec[rest] << endl;
				break;
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_20613513/article/details/82350407