Here’s a simple program in Java to check if a number is prime or not:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Scanner; public class PrimeNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.close(); boolean isPrime = true; // Check if the number is divisible by any number from 2 to half of the number for (int i = 2; i <= number / 2; i++) { if (number % i == 0) { isPrime = false; break; } } if (isPrime) { System.out.println(number + " is a prime number."); } else { System.out.println(number + " is not a prime number."); } } } |
Explanation:
- The program asks the user to enter a number using the
Scannerclass. - The
isPrimevariable is initialized totrue, assuming the number is prime. - The program checks if the number is divisible by any number from 2 to half of the number using a
forloop. - If the number is divisible by any of these numbers, the
isPrimevariable is set tofalse, and the loop breaks. - After the loop ends, the program checks the value of
isPrimeand prints the appropriate message indicating whether the number is prime or not.
Here’s a version of the prime number program in Java 8 using lambda expressions and the IntStream API:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Scanner; import java.util.stream.IntStream; public class PrimeNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.close(); boolean isPrime = number > 1 && IntStream.range(2, (int) Math.sqrt(number) + 1) .noneMatch(i -> number % i == 0); if (isPrime) { System.out.println(number + " is a prime number."); } else { System.out.println(number + " is not a prime number."); } } } |
Explanation:
- The program asks the user to enter a number using the
Scannerclass. - The
isPrimevariable is determined using theIntStreamAPI. - The
IntStream.rangemethod generates a stream of numbers from 2 to the square root of the given number. - The
noneMatchmethod checks if none of the numbers in the stream divide the given number evenly. - The
isPrimevariable is set totrueif the number is greater than 1 and no divisors are found. - Finally, the program prints the appropriate message based on the value of
isPrime.
This program uses the functional programming features introduced in Java 8, making it concise and readable. It leverages the power of streams and lambda expressions to perform the prime number check efficiently.
