Home > Java > javaTutorial > 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
Release: 2023-08-18 15:21:01
forward
1458 people have browsed it

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));
   }
}
Copy after login

Output

Enter a number ::
25
25 is not a prime number
Next prime number is: 29
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template