I am writing a program that takes as input an integer, and outputs a message whether the integer entered is prime or not. The algorithm I am using is as follows... R
Your problem lies with this line:
if (isPrime = true){
You made an assignment, instead of comparing to true
, so the statement is always true
.
Use ==
to compare boolean values, or better yet, since isPrime
is already a boolean
:
if (isPrime){
In the text you say the algorithm you intend to implement checks integers up to the square root of n
but your code is going all the way up to n/2
(see the for loop).
The reason your current code isn't working is because if (isPrime = true)
is an assignment operation and should be comparison if (isPrime == true)
note the two equal signs.