Monday, May 24, 2010

Modulus Problem In C++?

This is my program:





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;


#include %26lt;math.h%26gt;


using namespace std;





int main(int argc, char *argv[])


{





double f = pow(123,17);


double c = fmod(f,3233) ;





cout%26lt;%26lt; f %26lt;%26lt; endl;


cout %26lt;%26lt; c %26lt;%26lt; endl;


system("PAUSE");


return EXIT_SUCCESS;


}





It works for smaller numbers (like if c = 8 mod 2 I will get 0), but if I have c = 123^17 mod 3233 I don't get 855 like I'm supposed to, I get 992. Any ideas why?

Modulus Problem In C++?
I think I know why it isn't working, but I don't yet know why you get 992. Doubles do not have as much precision as you need to perform that calculation . . . it's an integer calculation and the result of 123^17 is 337 587 917 446 653 715 596 592 958 817 679 803. It can depend on your system and your compiler, but according to Microsoft's interpretation of the double you have 7 or 15 digits of precision. The size of the double is something that's supposed to be standard, so that's probably the size you have to work with. Good night!
Reply:the simple reason your program is malfunctioning is due to the precision level of type double.





the number you are trying to check is some what very large for the memory to be hold so while truncating few value are omited.





if you use calculator to calculate,


123^17 mod 3233 = 885





but if you use the reverse way


i.e.


123^17/3233=Q


Q*3233+R( check once with 885, next time with 992)= both gives output "O"





if again you want to verify use the (output "O")^(1/17)=123.





hence its all due to holding of data in the memory by the computer using truncation.





Thanx BIBEK
Reply:Because you're operating on a float-type variable such as double!
Reply:The type double is not able to hold accuracy after so many precisions. This is true for all floating point numbers on computers. The reason lies in the representation of data in floats. Please read http://en.wikipedia.org/wiki/Floating_po...


No comments:

Post a Comment