Question:
Input integer a and B, output a/b’s cyclic decimal representation and its loop node length. For example, the decimal number of a=5 b=43 is 0. (116279069767441860465), and the loop node length is 21.
Analysis:
The calculation process of long division
①mod = a%b;
②Decimal = (mod*10) / B;
③mod = (mod*10)%b;
Cycle, step 3, when there is a repeating residue, that is, the loop section appears.
Matters needing attention:
When the two or three steps above are looped, the remainder is zero, that is, when the result is not a cyclic decimal, the index value is output directly, and the length of the cyclic node is 0.
C++Realization:
1 #include<iostream> 2 using namespace std; 3 4 int main() { 5 int a, b, t, k; 6 cin >> a >> b; 7 int index = 0; 8 t = a%b; 9 if (t ==0) { 10 cout << index << " " << index << endl; 11 return 0; 12 } 13 int flag[10000] = {0}; 14 memset(flag,-1,1000); 15 k =0; 16 int length = 0; 17 while (true) { 18 t = (t*10)%b; 19 if (t == 0) { 20 index = ++k; 21 length = 0; 22 break; 23 } 24 25 if(flag[t] >= 0) { 26 index = flag[t]; 27 length = k - index; 28 break; 29 } 30 flag[t]=k; 31 k++; 32 } 33 34 cout << index << " " << length << endl; 35 return 0; 36 }