A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. In simpler terms, a prime number is a number that has only two distinct natural number divisors: 1 and itself. This property makes prime numbers an interesting and widely studied topic in the world of mathematics and computer science.

Advertisement

In this article, we will learn how to write a Java program that checks whether a given number is a prime number.

Java Program to Check Prime Number

The key idea to check whether a number is prime or not is to iterate from 2 to the square root of the number and check if the number is divisible by any number in this range. If it is, then it is not a prime number. We can iterate up to the square root of the number because a larger factor of the number must be a multiple of a smaller factor that has already been checked.

Let’s see how we can implement this in Java:

In the above code:

  1. We have a main method where we initialize the number num we want to check.
  2. We call the checkPrime method, passing num as an argument.
  3. In the checkPrime method, we first check if num is less than or equal to 1. If it is, we immediately return false as 1 is not considered a prime number.
  4. Then we run a loop that goes from 2 to the square root of num. For each number in this range, we check if num is divisible by this number (num % i == 0). If it is, that means num has a divisor other than 1 and itself, so we return false.
  5. If we have checked all numbers up to the square root of num and found no divisors, we return true, indicating that num is a prime number.
  6. Back in the main method, we print out whether num is a prime number based on the result of the checkPrime method.

When you run this program with num = 29, the output will be:

If you change the value of num to 15, the output will be:

This simple Java program is an efficient way to check whether a number is prime or not, making use of the mathematical property that a number is prime if it has no divisors other than 1 and itself.

Conclusion

Writing a Java program to check whether a number is prime or not is an excellent exercise for developing problem-solving skills and understanding core programming concepts. It involves the application of simple mathematical concepts and basic control structures in Java like loops and conditional statements.

We’ve seen how to implement a prime number checking algorithm efficiently, i.e., by iterating only up to the square root of the number. This reduces the time complexity significantly, especially when working with larger numbers.

Remember that practical problem-solving exercises like these form the foundation of good programming skills. Don’t hesitate to experiment with different approaches and try to optimize your solutions even further. Keep coding and keep learning!

Share.
Leave A Reply


Exit mobile version