Finding Prime Number java

Date Published: 02/12/2014 1:46 AM
Author: user115828

Please write a Java program to ask user for a positive input integer a within 1 to 100. With a, find next prime number that is greater than or equal to a.

To find a prime number greater than or equal to a, we should first check if a is a prime number. Then if a is not a prime number, we can proceed to check a+1, a+2 etc until a prime number is found. But how to check if a number is prime? We can use a crude but simple method – test if the number is divisible by any numbers smaller than itself. Assume we are given an integer k, we can see if k is prime with the following pseudo-code:

let boolean isPrime = true;
for i = 2 to k-1
 if k is divisible by i
 set isPrime to be false;

One can see that if isPrime remains to be true after the loop, the number k will indeed be a prime number. Some of you may see that you can improve this crude algorithm to make it run faster, but that is optional. Also note that 1 is not a prime number.

View full answer on Programmers

View Local Answers...

Can't find the answer to this question?

No answers yet.

Can you answer this question?

Finding Prime Number java

  • Your Nickname
  • Your Answer

  • Enter the code below to prove you are human