(algorithm) to accurately represent decimals

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.