Check if a number is prime
Description: Write isPrime(int n). A prime number is bigger than 1 and has no divisor except 1 and itself. Print all the primes up to 30.
Hint:
- You only need to test divisors up to the square root of
n.
Solution
public class Main {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
for (int n = 1; n <= 30; n++) {
if (isPrime(n)) System.out.print(n + " ");
}
System.out.println();
}
}
Output
2 3 5 7 11 13 17 19 23 29
How it works
- If
nhas a divisor bigger than its square root, it must also have a smaller one, so testing up toi * i <= nis enough. - The method returns
falseas soon as it finds a divisor.
Read Java Methods.
Learn more about the similar topics:
| Tutorials |
|---|
| Java if, else and else if |
| Java switch Statement and Expression |
| Java for Loop |
| Java while and do while Loop |
| Java break and continue |
| Exercises & Assignments |
|---|
| Find the largest of three numbers |
| Check if a year is a leap year |
| FizzBuzz in Java |
| Sum of the digits of a number |
| Print a multiplication table |
| Check if a number is prime |
| Interview Questions & Answers |
|---|
| No Content Found. |