Java From Beginner To Advanced

0% completed

Previous
Next
Check if a Number is Prime

Problem Statement

Write a Java program to check if a given number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, and 7 are prime numbers, whereas 4, 6, 8, and 9 are not.

Examples

Example 1:

  • Input: 7
  • Output: 7 is a prime number.
  • Justification: The number 7 has no divisors other than 1 and 7, making it a prime number.

Example 2:

  • Input: 10
  • Output: 10 is not a prime number.
  • Justification: The number 10 can be divided evenly by 1, 2, 5, and 10, indicating that it is not a prime number.

Step-by-Step Algorithm

To determine whether a number is prime, follow these steps:

  1. Initialize the Number:

    • Let num be the number to check for primality.
  2. Handle Special Cases:

    • If num is less than or equal to 1, it is not a prime number.
    • If num is 2, it is a prime number (the only even prime).
  3. Check for Even Numbers:

    • If num is even and greater than 2, it is not a prime number.
  4. Check for Divisors:

    • Iterate from 3 to the square root of num, incrementing by 2 (since even numbers have already been handled).
    • For each iteration, check if num is divisible by the current iterator value.
    • If a divisor is found, num is not a prime number.
  5. Conclusion:

    • If no divisors are found in the above steps, num is a prime number.

Code

Below is the Java code that demonstrates how to check if a number is prime using the described algorithm. This example checks whether the number 7 is prime.

Java
Java

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next