Search code examples
c++matharithmetic-expressions

Check if 1/n has infinite number of digits after decimal point


If a user enters a number "n" (integer) not equal to 0, my program should check if the the fraction 1/n has infinite or finite number of digits after the decimal sign. For example: for n=2 we have 1/2=0.5, therefore we have 1 digit after the decimal point. My first solution to this problem was this:

int n=1;
cin>>n;
if((1.0/n)*n==1)
{
    cout<<"fixed number of digits after decimal point";
}
else cout<<"infinite number of digits after decimal point";

Since the computer can't store infinite numbers like 1/3, I expected that (1/3)*3 wouldn't be equal to 1. The first time I ran the program, the result was what I expected, but when I ran the program today, for n=3 I got the output (1/3)*3=1. I was surprised by this result and tried

double fraction = 1.0/n;
cout<< fraction*n;

which also returned 1. Why is the behaviour different and can I make my algorithm work? If I can't make it to work, I will have to check if n's divisors are only 1, 2 and 5, which, I think, would be harder to program and compute. My IDE is Visual Studio, therefore my C++ compiler is VC.


Solution

  • Your code tries to make use of the fact that 1.0/n is not done with perfect precision, which is true. Multiplying the result by n theoretically should get you something not equal to 1, true.
    Sadly the multiplication with n in your code is ALSO not done with perfect precision.
    The fact which trips your concept up is that the two imperfections can cancel each other out and you get a seemingly perfect 1 in the end.

    So, yes. Go with the divisor check.