Computer Science, asked by ishanavailable, 1 year ago

write bluej program to input a number and check it is a prime or not if not a prime number then print the next prime number
using Scanner​

Answers

Answered by QGP
1

Finding Next Closest Prime - Java

BlueJ is an IDE developed for beginners to use Java. We will be writing the program in Java.

We take the User Input first of all. Now, we need to check if this number is a Prime or not. For that, we create a function static boolean isPrime(int number), which would return true if the number is prime and false if it is not.

In the function, we check divisibility by each number from 2 to the square root of user number. If divisibility is found, return false. If no divisibility is found, number is prime and so return true.

If the user input number is prime, simply print it out. Else, initialize another variable with the same value, and keep incrementing it until we get a Prime.

Here's a code which works as required.

 \rule{320}{1}

import java.util.Scanner;   //Importing Scanner

public class NextPrime

{

   //Function to check if a number is Prime or not

   static boolean isPrime(int number)

   {

       //Check divisibility from 2 to sqrt(number)

       for(int i=2; i<=(int)Math.sqrt(number); i++)

       {

           if(number % i == 0)

           {

               //If divisibility is found, number is not prime

               return false;

           }

       }

       //If no divisibility is found, number is prime

       return true;

   }

   public static void main(String[] args)  //main function

   {

       Scanner sc = new Scanner(System.in);  //Create Scanner object

       //Take User Input

       System.out.print("Enter a number: ");

       int num = sc.nextInt();

       if(isPrime(num))    //Calling function

       {

           //If number is Prime, simply print it out

           System.out.println(num+" is a Prime.");

       }

       else

       {

           //If user number is not prime, we need to find the next prime

           int nextPrime = num;    //Initialising nextPrime as num

           //Run a loop until a prime is found

           while(!isPrime(nextPrime))

           {

               nextPrime++;    //Incrementing by 1

           }

           //Print out the relevant stuff

           System.out.println(num+" is not a prime. The Next Prime is: "+nextPrime);

       }

   }

}

Attachments:
Answered by Anonymous
0

Explanation:

the chicks in the story.

Who liked yellow things?

What did Lalu eat one day?

Similar questions