Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class PrimeExample {
- public static void main(String args[]) {
- final int numberToBeChecked = 3;//it is the number to be checked
- boolean isPrime = isPrime(numberToBeChecked);
- if (isPrime) {
- System.out.println(numberToBeChecked + " is prime number");
- } else {
- System.out.println(numberToBeChecked + " is not prime number");
- }
- }
- protected static boolean isPrime(final int numberToBeChecked) {
- boolean isPrime = false;
- if (numberToBeChecked == 0 || numberToBeChecked == 1) {
- isPrime = false;
- } else {
- boolean foundFactor = false;
- int largestDivisorToTry = numberToBeChecked / 2;
- for (int divisor = 2; divisor <= largestDivisorToTry; divisor++) {
- if (numberToBeChecked % divisor == 0) {
- isPrime = false;
- foundFactor = true;
- break;
- }
- }
- if (!foundFactor) {
- isPrime = true;
- }
- }//end of else
- return isPrime;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement