Determining Prime Numbers Java

前端 未结 2 1024
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 03:09

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

相关标签:
2条回答
  • 2020-12-20 03:21

    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){
    
    0 讨论(0)
  • 2020-12-20 03:26

    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.

    0 讨论(0)
提交回复
热议问题