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 n has a divisor bigger than its square root, it must also have a smaller one, so testing up to i * i <= n is enough.
  • The method returns false as soon as it finds a divisor.

Read Java Methods.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.