简体   繁体   中英

Prime Number checker is not working

This is the code for a function that is supposed to return true if the input is prime and returns false if it is not.

This is how I intended for it to work: lets say that y = 7, the loop starts with n=1. Since 1(n) is less that 7(y) the loop can iterate. The program checks if y divided by n has a remainder of 0, meaning that n is a factor of y. If it is true, then it checks to see if the factor does not equal 1 or y (7), because if they dont then that means that y has more factors other than its self and 1, meaning that it is not prime, so it should automatically end the function and return false. but since 7 has only two factors, 1 and 7, and they either equal 1 or itself (y) then after the end of the loop, it should return true.

I don't understand why it isn't working.

    public static boolean checkIfPrime(long y) {
    for ( long n =1L; n <= y; n++) {
        if(y%n == 0) {
            if( n != 1L || n != y) { 
                return false;
            }

        }
    }
    return true;
}

With a few optimizations the code will be like this

    static boolean isPrime(long n){
    long lim = (long) Math.sqrt(n);

    if(n%2 == 0 && n != 2)
        return false;

    for (int i = 3; i <= lim; i=i+2)
        if(n%i == 0)
            return false;       
    return true;
}

This code:

  • checks if the number is even and different from 2 (all even numbers except 2 are compound).
  • next iterates from 3 to sqrt(n), thats because to prove a number is prime you don't need to check all the dividers (if you don't believe me try, and if still don't believe use n/2 wich is enough but not the minimum value).
  • For loop pace start from 3 and add 2 in each iteration getting only odd numbers as divder (we first checked that it wasn't an even number).

Remove equal to operator in n <= y. Start your loop from 2. It must be like this. ( long n =2; n < y; n++)

For what you are trying to achieve, pseudo code in my opinion should look like this:

set a flag = true;

Loop from 2 to y-1{
    if(y%n==0){   
        flag = false
        break; // Very important
    }
}

check flag condition & return (if some othe computation is required) or just return flag

if( n != 1L || n != y) : is adding a check condition unnecessarily to every iteration. try to avoid it.

Why use a flag instead of direct return statement ? Just a preference, a direct return definitely would work in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM