Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 11 Online
OpenStudy (anonymous):

I just made a prime number detector--based on the assignment here. When I input a decimal or floating point, it will run it through the program, as though it were a prime number. Should it give an error?

OpenStudy (anonymous):

You've discovered the problem with floats. Later readings and lectures (I'm assuming you're still in the first few if you're on ps1) will discuss and explore exactly what a float means on a binary level. You'll see it under Lecture 5 readings. If you're curious now, read this: http://docs.python.org/tutorial/floatingpoint.html But to explain it for now, a decimal point in python will approximate the number. 4.0 is stored in the computer as 4.0000000000000000000000000000000768494985857 or some such nonsense. So if you divide that crazy decimal number by 2, you will get a remainder. Therefore it passes your prime test.

OpenStudy (anonymous):

I just experimented with the int identity and now every thing shows up as composite.

OpenStudy (anonymous):

It's hard to say what exactly is going on because you didn't post your code. But you should definitely be using only integers in this problem. If you really want your primality testing code to handle floats and 0 and 1 and negative numbers (and strings, etc.) correctly, you can put tests before the main part of the code to screen out unhandleable values and types. These are called "guardians" because they guard your delicate code from mean unexpected values. But you're the only one writing and using all the code here, so just pass integers and you won't have to check anything. Also, the guardian tests will clutter up the code, and others have found this first problem to be pretty tough as it is, so try to keep it as simple as possible.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!