A prime number must be a natural number greater than 1 and has no positive divisors except for 1 and itself.
In today's article, we shall explore various prime number manipulations using code in Java. Let's dive in!
public class Prime{
public static boolean isPrime(int n){
// number should not be less than 1
if (n <= 1) return false;
// check the number from 2 to n - 1
for (int i = 2; i < n; i++){
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args){
System.out.println("Is the number prime? " + isPrime(15));
}
}
Output:
Is the number prime? false
import java.util.Scanner;
public class Prime{
public static void main(String[] args){
// read user's input
System.out.print("Enter a number: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// output
System.out.println("Is the number prime? " + isPrime(n));
}
// checker method
public static boolean isPrime(int n){
// number should not be less than 1
if (n <= 1) return false;
// check the number from 2 to n - 1
for (int i = 2; i < n; i++){
if (n % i == 0) return false;
}
return true;
}
}
public class Prime{
public static boolean isPrime(int n){
// number should not be less than 1 or 1 itself
if (n <= 1) return false;
for (int i = 2; i < n; i++){
// number should not be divisible by any other number
// except for 1 and itself
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args){
int N = 50;
for (int i = 1; i <= N; i++){
// check for primality
if (isPrime(i)){
// if number is prime, print it
System.out.print(i + " ");
}
}
}
}
public class Prime{
public static boolean isPrime(int n){
// number should not be less than 1 or 1 itself
if (n <= 1) return false;
for (int i = 2; i < n; i++){
// number should not be divisible by any other number
// except for 1 and itself
if (n % i == 0) return false;
}
return true;
}
public static int nextPrime(int n){
int next = n + 1;
while (!isPrime(next)){
next++;
}
return next;
}
public static void main(String[] args){
System.out.println(nextPrime(37));
}
}
Output:
41
We have not yet implemented various prime number manipulation utilities, e.g. prime factors of a number, the sieve of Eratosthenes algorithm of generating prime numbers and so on. Continue exploring! ✌️