Domanda

Below is one of the first programs I made (with help from the Internet) in Java. It is a program that checks if a given integer is prime or not and prompts the user with feedback. If the user input is not an integer it outputs that it is not an integer. The latter also happens when Big Integers are entered. This is the code:

import java.util.Scanner;

class BasicPrime1 {
    public static void main(String[] args) {

        try {
            System.out.println("Enter an Integer: ");
            Scanner sc = new Scanner(System.in);

            int i; 
            int number = Integer.parseInt(sc.nextLine());

        // 1 and numbers smaller than 1 are not prime
            for (i = 1; number <= i;) {
                System.out.println("NOT a prime!");
                break;
            }

        // Number is not prime if the remainder of a division (modulus) is 0
            for (i = 2; i < number; i++) {  
                int n = number % i;         
                if (n == 0) {                 
                    System.out.println("NOT a prime!");
                    break;
                }  
            }

        // I do not understand why the if-statement below works.
            if(i == number) { 
                System.out.println("YES! PRIME!");
            }
        }

        catch(NumberFormatException nfe) {
            System.out.println("Not an integer!");
        }

    }
}

This program does his job, but I do not know why the part with the if-statement works. How is it possible that "i == number" gives a value of true (it prints out "YES! PRIME" when you enter a prime)? The local variable i gets incremented in the for-loop, but the if-statement is outside of the for-loop.

/edit the paragraph below is nonsense as Jim Lewis points out
Thinking about it now, the only reason I can think of that this is the case is because the == operator checks if the i-'object' and number-'object' belong to the same 'type' (i.e., have a reference to the same object). Since they both belong to the type of primitive integers this program catches the integers (other input throws a NumberFormatException which is caught and outputs "Not an integer"). The ones that are primes pass the first for-loop and then the magical if-statement gives "true" and it prints out "YES! PRIME!".

Am I on the right track?

I have improved this program by removing the magical if-statement and changing it for an if-else-statement like this: (/edit fixed problem with code thanks to answer of ajb)

boolean factorFound = false;            
for (i = 2; i < Math.sqrt(number) + 1; i++) {
    int n = number % i;
    if (n == 0) {
        factorFound = false;
        break;
    }  
    else {
        factorFound = true; 
    }
}
if(factorFound == false) System.out.println("NOT a prime!");
if(factorFound == true) System.out.println("YES! PRIME!");

By only going up to the square root of the input number the calculation time improves (I know it can be even more improved by only checking odd numbers or using a AKS Primality Test, but that is beside the point).

My main question is why I could not improve the efficiency of the first program (with the magical if-statement) in the same manner. When I enhance the for-loop like this "(i = 2; i < Math.sqrt(number) + 1; i++)" in the first program it does no longer print out "YES! PRIME!" when you input a prime. It gives a blank. Even if my previous explanation is correct - which it is probably not - this is not explained.

You may enlighten me.

ANSWER: int i is outside of scope of for-loop and after going through the for-loop multiple times upto number the value of i will reach the value number, when we can be sure it is a prime. Furthermore, after checking the disappearing "YES! PRIME!" statement once again it turns out it is actually possible to change number in both the if-statement and for-loop to ( Math.sqrt(number) + 1 ) and have working code. So the question was based on a false premise.

È stato utile?

Soluzione 2

// I do not understand why the if-statement below works

Explanation: Because i has been incremented until it equals number. If you stop at sqrt(number) then the if statement will always fail.

By the way I don't like using square root with integers. I like this better for a isPrime function:

        if (number < 2) return false;
        if (number > 2 && number % 2 == 0) return false;
        for (int i = 3; i * i <= number; i = i + 2)
            if (number % i == 0) return false;
        return true;

Altri suggerimenti

i is declared outside the for loops, so its value is still in scope and available after the loop finishes (nothing to do with comparing data types or anything like that!).

If no divisors were found, the i < number loop condition will eventually fail, with i == number. (If the loop finds a divisor and hits the break statement, that condition no longer holds).

When you do the sqrt optimization, the end condition of the loop is changed, so i == number no longer holds after the loop exits, even if the number is prime.

In my opinion it would be more clear to explicitly set a flag (e.g. isPrime=0 just before breaking out of the loop), then check that flag rather than looking at the loop variable to see whether the loop completed or not.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top