Negative numbers are tricky in such a question.
You have to take the absolute number and factor it. In your original source, you didn't do this. It meant that you got a NaN
from the Math.sqrt
method. Which also meant that you got false when you compared it to 7.
So your original method would have returned true
for all negative numbers.
But changing the sign (which, by the way can be done by num = -num
rather than multiplication), which would solve it for all negative numbers, actually introduced an overflow into the program.
The number -2147483648 is, in fact, -231. The maximum positive number allowed in an int
is 231-1. So the number - Integer.MIN_VALUE
always overflows... into itself. It remains negative after you negate it!
So you run into that NaN
again.
But note - since the number is -231, it doesn't, in fact, have any other prime factors other than 2. So the method really should return true
for it - assuming that you are not considering -1
a prime.
So I believe that your expectation that it should be false is incorrect - but it depends on the assignment's definition of the prime factors of negative numbers.
Notes:
Your program checks isPrime(num)
instead of isPrime(i)
, and therefore it will always return true. num
cannot both be divisible by i
and be prime at the same time.
Limiting your program to the square root of num
is wrong to begin with. For example, take the number 881305274. Its prime factors are 2 and 440652637. But 440652637 is much bigger than sqrt(881305274). The square root trick works for prime testing, because any factor that is bigger than the root has to be multiplied by a factor that's smaller than the root. But this doesn't apply to the "ugly" problem.
Also, prime numbers are not considered "ugly" as they are a factor of themselves. But your program, because it limits itself to the square root, will never return false for prime numbers.