Java – use logic in switch statements

My question relates to the following code:

public static void main(String[] args) {

    // Find Prime Numbers from 0 to 100
    int i;
    for (i=2; i <= 100; i++) {
        int j = 2;
        boolean iPrime = true;

        //The following line gives incorrect results,but should execute faster
        //  while ((iPrime = true) && (j < (i / 2 + 1))) {
        //The following line gives correct results but performs un-necessary operations
        //by continuing to calculate after the number is found to be "not prime"
        while (j < (i / 2 + 1)) {

            j++;
            if ((i % j) == 0) {
                iPrime = false;
                //System.out.println(j + " is a factor of " + i);
            }
        }
        if (iPrime) {
            System.out.println(i + " is a prime number!");
        }
    }
}

Now, as I commented in the code, what I want to achieve is to execute my program faster by executing a 'while' loop only when iprime = true 50% of the number can be divided by 2, so once determined, the calculation can stop

I'm doing this project from a book as part of a beginner's' example ', I actually want to calculate up to 1000000 as soon as possible, just because of my own "extra credit"

I read "short circuit" and "operator" & & if the first half is true, only the second half of the statement is evaluated. If false, they do not evaluate each other (save CPU)

It will also exit the loop, which will save more CPU

But for some reason, it can't work properly! I've added more system out. The println () statement lists what 'iprime' is - the output is strange... It turns iprime on and off and evaluates each number, which I can't understand

Solution

If ((iprime = true) & &...) should be if ((iprime) & &...)

By executing isprime = true, you can specify true for isprime instead of comparing its' value 'with true

You might also want to see this to better understand what's happening in your code:

So, when you use the = operator instead of = = (delete something when you compare it with true - instead of writing if (someboolean = = true) you only write if (someboolean)), you actually meet the condition, always!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>