Prime Number
Problem
A prime number is greater than 1 and has no divisors except 1 and itself. Read an integer and print true if it is prime, otherwise false.
Constraints
- -10^12 <= n <= 10^12
Examples
Input
7
Output
true
Input
9
Output
false
Solutions
If a number has a divisor, it also has a divisor that is not larger than its square root. So we only test up to the square root. For 10^12 this is 10^6 steps instead of 10^12.
/*
* Problem : Check if a number is a prime number.
* Input : One integer.
* Output : true or false.
* Approach: Look for a divisor.
* Time : O(sqrt(n))
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and returns true if the number is a prime number.
static boolean isPrime(long number) {
// Step 1: Numbers smaller than 2 are not prime.
if (number < 2) {
return false;
}
// Step 2: If number = a * b and a is smaller than b, then a is at most the square root of the number.
// So we only test divisors while divisor * divisor <= number.
for (long divisor = 2; divisor * divisor <= number; divisor++) {
// Step 3: If a divisor divides the number without remainder, the number is not prime.
if (number % divisor == 0) {
return false;
}
}
// Step 4: No divisor was found, so the number is prime.
return true;
}
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
System.out.println(isPrime(number));
}
}
Hints (2)
- Can a divisor larger than the square root exist without a smaller partner?
- Stop when divisor * divisor is larger than the number.