Home  >  Article  >  Java  >  Java program code to check prime numbers and find next prime number

Java program code to check prime numbers and find next prime number

WBOY
WBOYforward
2023-08-18 15:21:011358browse

Any integer greater than 1 that has only two factors (i.e. 1 and the number itself) is called a prime number. Apart from these two numbers, it has no other positive divisors. For example: 7 = 1 × 7

The following is the algorithm to determine whether a number is prime:

  • Get the integer variable A.

  • Divide variable A by (A-1 to 2).

  • If A is divisible by any value in (A-1 to 2), then it is not prime.

  • Otherwise it is a prime number.

Example

The following Java program accepts an integer input by the user, determines whether the given number is a prime number, and prints the next prime number.

import java.util.Scanner;
public class NextNumberisPrime {
   public static int isPrime(int num){
      int prime = 1;
      for(int i = 2; i < num; i++) {
         if((num % i) == 0) {
            prime = 0;
         }
      }
      return num;
   }
   public static int nextPrime(int num) {
      num++;
      for (int i = 2; i < num; i++) {
         if(num%i == 0) {
            num++;
            i=2;
         } else {
            continue;
         }
      }
      return num;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number ::");
      int num = sc.nextInt();
      int result = 0;
      int prime = isPrime(num);
      if (prime == 1) {
         System.out.println(num+" is a prime number");
      } else {
         System.out.println(num+" is not a prime number");
      }
      System.out.println("Next prime number is: "+nextPrime(num));
   }
}

Output

Enter a number ::
25
25 is not a prime number
Next prime number is: 29

The above is the detailed content of Java program code to check prime numbers and find next prime number. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete