inhaler - 10 months ago 77

C++ Question

`#include<iostream>`

#include<string>

#include<cstdlib>

using namespace std;

int main()

{

double a,b,res;

while(cin>>a>>b)

{

res = a/b;

if((res*b) == a)

cout<<"Terminates"<<endl;

else

cout<<"Does not terminate"<<endl;

}

return 0;

}

So, here is my code to see if a/b results in terminating decimal or not. Some input is generating correct output, like:

1/3 : Does not terminates,

1/9 : Does not terminates,

1/7 : Does not terminates,

22/7 : Does not terminates,

1/2 : Terminates.

Except for 1/5 which should show:

`1/5 : Terminates`

`Does not terminates`

I know there are many issues for C++ floating points,tried google but it's like a puzzle.

Answer Source

There is an easy way to ask whether a ratio has an exact, terminating representation in a given radix, in your case 10.

Step 1 is to reduce it to its lowest terms. Divide top and bottom by their highest common factor.

Now only the denominator matters. If every one of its prime factors is also a prime factor of the radix, the fraction will terminate in that radix. 5 is a prime factor of 10, so 1/5 terminates in decimal. 5 is not a prime factor of 2, so 1/5 does not terminate in binary.