Thumbnail image

Work with prime numbers in Java

2/1/2024 4-minute read

Recently in my study schedule, I added a day for week to study algorithms and data structures with Java. I only studied algorithms in my college, but many of companies use algorithms and data structures in your interview process. Also, we know, study algorithms and data structures will help any developer to be better in solving problems.

Just to clarify, this article is meant to share some parts of what I am studying, with an easy and beginner-level challenge, without the measurement of complexity, such as Big O notation, for example.

If you need a more academic explanation or more complex challenges, with a little research, you will find many free and paid web platforms and courses with thousands of challenges for practice this kind of exercises. Some famous platforms are Coursera, Hackerrank, Codewars, LeetCode and many others. If you prefer learn with books, I think the most famous book about this theme is Algorithms by Robert Sedgewick. The other book I would like to recommend is Java Challengers by Rafael Chinelato Del Nero. This book has 70 Java challenges and will help any Java developer to refine your Java skills.

Today I bring you my solution for a simple and easy challenge, it’s a beginner level, but when I was in my college this small challenge broke my mind.

The challenge is to write a program, function or method that finds out if some number is prime.

Of course there are many ways to solve this challenge, bellow I will show you my solution, I know probably is not the best solution and feel free to share your solution in the comments.

First, we need to remember what is a prime number. A prime number is natural integer number, greater than 1 and divisible only for 1 or itself. In Java, we have an operator that return the rest of division, is the "Modulus" represented by the symbol "%".

For example 10 % 2 = 0, zero is the rest of that division.
11 % 2 = 1, where 1 is the rest of the division.

Now we have all the information necessary to build a logic. Let’s take a look at this method bellow:

    private static boolean prime(int number) {
        for (int i = 2; i < number; i++) {
            if (number % i == 0)
                return false;
        }
        return true;
    }

This boolean method, we have an iteration “for” that checks all the numbers between 2 until the number with received in the parameter of method minus 1. After that, we have an condition “if” to check if the rest of the division for some number is 0. If the modulus return 0, that number can be divided by others numbers and that number is not prime, as you can see the return is “false”. In case of any division not return 0, we have a return “true” and that number is prime. Now let’s write a small program for use our method. First let’s create a Main java class. Inside our main class, let’s create a method main. Also, we will use the Class Scanner for receive a number and show some instructions in the terminal.

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a number to find out if it is prime: ");
        int numberTyped = scanner.nextInt();

    }


    private static boolean prime(int number) {
    	for (int i = 2; i < number; i++) {
        	if (number % i == 0)
            	return false;   
    	}
    	return true;
	}

Now let’s write a small condition to use our previous method and add the number scanned as a parameter. After the condition we can close the scanner. You can see the code below.

        if (prime(numberTyped)) {
            System.out.println(numberTyped + " is a prime number.");
        } else {
            System.out.println(numberTyped + " is not a prime number.");
        }


        scanner.close();

As you can see, work with prime numbers in Java is very easy. I can give you some ideas to exercise more. For example, you can write a program for print all prime numbers between 1 to 100. You also can go out of the terminal using JOptionPane. So, there are many possibilities to work with the same algorithm in Java. Below you can take a look in our code or if you prefer you can access all the code on my GitHub here.

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a number to find out if it is prime: ");
        int numberTyped = scanner.nextInt();

        if (prime(numberTyped)) {
            System.out.println(numberTyped + " is a prime number.");
        } else {
            System.out.println(numberTyped + " is not a prime number.");
        }

        scanner.close();
    }

    private static boolean prime(int number) {
        for (int i = 2; i < number; i++) {
            if (number % i == 0)
                return false;
        }
        return true;
    }
}

I hope this article helped you to keep studying and practice algorithms and data structures with Java. Any question or suggestion, please let me know in a comments sessions below. See you in next challenge.