前几天把小数点后的全部存在了一个数组里,然后用了二重循环,时间复杂度O(n^2),虽然说没超时,但是过不了,循环太多又不好改,干脆直接删了。
学了点C++,也准备开始练习C++,所以用C++又写了一次,另外改了算法,当余数出现重复时就是循环节出现的时候,唉,小学数学没学好。。。
#include<iostream>
#include<cstring>
using namespace std;
int qt[10000], re[3005];
int main() {
int a, b;
int q, r, count, last, len;
while(cin >> a >> b) {
memset(qt, 0, sizeof(qt));
memset(re, 0, sizeof(re));
count = 0;
r = a % b;
for(int i = 1; ; i++) {
if(!re[r]) {
++count;
re[r] = count;
}
else {
last = i;
break;
}
q = r * 10 / b;
r = r * 10 % b;
qt[i] = q;
}
len = last - re[r];
cout << a << "/" << b
<< " = " << a / b
<< ".";
for(int i = 1; i < re[r]; i++)
cout << qt[i];
cout << "(";
if(len <= 50)
for(int i = re[r]; i < last; i++)
cout << qt[i];
else {
for(int i = re[r]; i < re[r] + 50; i++)
cout << qt[i];
cout << "...";
}
cout << ")" << endl;
cout << " " << len << " = number of digits in repeating cycle"
<< "\n" << endl;
}
}