Write a function name isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Demonstrate the function in a complete program that prompts for a number and indicates whether or not it is prime.

Respuesta :

ijeggs

Answer:

public static boolean isPrime(int number)

   {

       if(number<1)

           return false;

       else if (number == 1||number ==2 ||number==3)

       {

           return true;

       }

       else

       {

           for(int i=2; i<number; i++)

           {

               if(number%i==0)

                   return false;

           }

           return true;

       }

   }

The complete program is given in the explanation section

Explanation:

import java.util.Scanner;

public class PrimeNumber {

   public static boolean isPrime(int number)

   {

       if(number<1)

           return false;

       else if (number == 1||number ==2 ||number==3)

       {

           return true;

       }

       else

       {

           for(int i=2; i<number; i++)

           {

               if(number%i==0)

                   return false;

           }

           return true;

       }

   }

   public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       System.out.println("Enter a number to check if it is Prime");

       int num = in.nextInt();

       if(isPrime(num)){

           System.out.println("The number "+num+" is a prime number");

       }

       else {

           System.out.println("The number "+num+" is NOT a prime number");

       }

   }

}

Prime numbers are numbers divisible only by themselves and 1 Examples are: (2, 3, 5, 7, 11)