Wednesday, May 27, 2020

Prime Number or Next Prime Number Checking


Write a program to take a number and show if it is prime. If not prime, then show the next prime.
 If user enters 14 output will be : next prime number is 17
 If user enters 13 output will be : 13 is a prime number


 
import java.util.*;
class A
{
  int i,n;
  Scanner sc=new Scanner(System.in);
  void show()
  {
      System.out.print("\nEnter the number:");
      n=sc.nextInt();
      for(i=2;i<n;i++)
      {
           if(n%i==0)
           break;
        }
       if(i==n)
       System.out.print(n+ " is a prime number");
       else
       {
       while(true)
       {
        if(nextPrime(n))
        {
          System.out.print("next prime number is:" + n);
          break;
        }
        n++;
       }
     }
    }
         private boolean nextPrime(int n)
        {
        int i;
        for(i=2;i<n;i++)
      {
           if(n%i==0)
           break;
        }
       if(i==n)
       return true;
       else
       return false;
    }
}
        

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner