+ 1
Have I done this code in right way? Is there another possible easy way to find a prime number?
2 Answers
+ 6
Your algorithm does not work correctly, because every odd number is identified as prime number. This is caused by two mistakes:
1. You use the decrement operator in the range:
var x = 2..inputNum--
this will modify the input-value off an odd number to an even number. Change it to:
var x =2..(inputNum-1)
(by the way: it would be sufficient to have a range from 2 to the square root of the input-number. For example, if you want to test 101 for prime, your test-range needs only to be 2..10)
2. Your if-condition is not correct. A number is prime if there is a remainder for all numbers in the given range! But in your code a division without a remainder would be a criterion for being prime. A modification could be:
if (inputNum % a ==0){
println("given number is not a prime number")
break
}
and the else-statement must be removed, because a number is only prime, if ALL remainders are greater then zero. So you have to wait until the loop is complete, before you can make a decision about being prime. This looks differently for the opposite decision: you can immediately break the loop, if a remainder of zero is found.
+ 1
Thanks Michael.. greatly appreciate your help