A prime number is a whole number greater than one with only the number one and itself as factors. A factor is a whole number that can be evenly divided by another number. Prime numbers are those that have only two factors. A prime number is a number that is only divisible by 1 and itself. So, prime numbers have only two factors, 1 and the number itself. The programme will loop through the given range of numbers and determine whether or not the number is prime. It will print if the number is a prime number. In this post, we will see how to create a java program to find prime numbers in a given range of numbers.
Prime Number
A prime number is a number that can only be divided only by 1 and itself. A number is not a prime number if the number is divisible by any another number.
Examples of prime numbers include 2, 3, 5, 7, 11, 13, 17, 19, and so on.
The numbers 0 and 1 are not prime. The only even prime number is 2 because all other even numbers can be divided by 2.
package in.yawin; public class PrimeNumbers { public static void main(String[] args) { for (int i = 1; i < 100; i++) { if (isPrime(i)) System.out.print(i + " "); } } public static boolean isPrime(int value) { if (value == 0 || value == 1) { return false; } for (int i = 2; i <= value / 2; ++i) { if (value % i == 0) { return false; } } return true; } }
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Explanations
The method isPrime determines whether or not a given number is a prime number. It returns true if it is a prime number. If not, it returns false. The for loop in the main method iterates through the given range of numbers, checking each number to see if it is prime or not.
A for loop is executed from 2 to half of the given number in the isPrime method. It returns false if the given number is divisible by any of the numbers. It returns true if it is not divisible by any of the numbers. The numberĀ is a prime number.
The programĀ in the preceding java example finds the prime number between 1 and 100.