Topic:
Given a positive integer n, ask for a decimal representation of 1/n, such as:
1/2=0.5
1/3=0. (3)
1/6=0.1 (6)
1/7=0. (142857)
Where parentheses represent the loop portion of the decimal.
Ideas:
Consider the process of the division operation:
When the remainder is duplicated with the previous operation, then the loop has already begun, so a hash table can be used to record the position of the remainder.
Dividend divisor remainder quotient
1 7 1 0
1*10 7 3 1
3*10 7 2 4
2*10 7 6 2
6*10 7 4 8
4*10 7 5 5
5*10 7 1 7
1*10 7 3 1
3*10 7 2 4
2*10 7 6 2
6*10 7 4 8
4*10 7 5 5
5*10 7 1 7
Code:
#include <iostream>#include<map>#include<sstream>using namespacestd;stringDecimalrepresent (intN) {Map<int,int>MP; intnum=Ten; intResidue=1; stringMulti; intidx=0; while(Mp.find (residue) = =Mp.end ()) { if(residue==0) {StringStream ss; stringtmp; SS<<1.0/N; SS>>tmp; returntmp; } Mp[residue]=idx; StringStream Sstr; stringstr; Sstr<<num/N; Sstr>>str; Multi=multi+str; IDX++; Residue=num%N; Num=residue*Ten; } stringresult="0."+MULTI.SUBSTR (0, Mp[residue]) +"("+multi.substr (Mp[residue]) +")"; returnresult;}intMain () {intN; while(cin>>N) {cout<<"The result of 1/"<<n<<": "<<Endl; cout<<decimalrepresent (n) <<Endl; } return 0;}
(algorithm) to accurately represent decimals