Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

find the next prime number using java

you are going to practice taking user input and displaying to the console, as well as solve an interesting little problem, as follows.
Prompt the user to input an integer. The user will then input an integer. The program will then find the next prime number that is strictly greater than the integer supplied by the user. The program will then report the prime number to the user and terminate. Some sample runs are shown below.
(Program) Hello John! I hope you are doing well today! Please input a number: (Ryan) 44
(Program) The next prime is: 47
(Program) Hello John! I hope you are doing well today! Please input a number:
(Ryan) 73
(Program) The next prime is: 79
(Program) Hello John! I hope you are doing well today! Please input a number:
(Ryan) 0
(Program) The next prime is: 2

Answer:

import java.util.*;

public class Prime {

	static Scanner input = new Scanner(System.in);

	public static void main(String args[]) {
		int k = 0;
		
		System.out.print("Hello John! I hope you are doing well today! please input a number: ");
		// check the next number
		k = input.nextInt();
		++k;
		k = findPrime(k);
		// print out the next largest prime number 
		System.out.println("The next prime is: " + k);
	}

/*
 * Objective: This method returns the next prime number after k 
 */
	public static int findPrime(int k) {
		int y;
		while(true){
			for (y = (k/2); y > 0; --y)
				if ((k % y == 0) && y != 1) break;
				else if((k % y == 0) && y == 1) return k;
			++k;
		}
	}
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!