Java program take a number from user and check whether it is prime or not. If it is prime then predict next 3 primes or find nearest prime?

Yogi Siddeswara 0

 Q.Write a Java program to take a number from the user and check whether it is prime or not. If it is prime then predict the next 3  primes or find the nearest prime?



package simplepro;

import java.util.Scanner;

public class PrimeValid{

	public static void main(String[] args) {
		
		Scanner in=new Scanner(System.in);
		System.out.print("Enter the Number:   ");
		int n=in.nextInt();
		if(n>1) {
			
			
			boolean isPrime=primeCheck(n);
			int limit=n+100;
		    byte count =0;
			if(isPrime) {
				System.out.println(n +" is Prime Number :");
				for(int i=n+1,j=1;i<limit;i++) {
					boolean checkPrime=primeCheck(i);
					if(checkPrime) {
						System.out.println("Next "+ j+" Prime Number: "+i);
						count++;
						j++;
						if(count>=3) {
							break;
						}
					}
					
				}
			}
			else {
				
				while(n>2) {
					n++;
					if(primeCheck(n)) {
						System.out.println(n+" is not Prime Number !!");
						System.out.println("Nearest Prime Number : "+n);
						break;
					}
				}
			}
			
			
			
		}
		else {
			System.out.println("Please Enter above 1 numbers only");
		}
		

					

				
			}
	
	public static boolean primeCheck(int n) {
	
		int count=0;
	
		for(int j=2 ; j<n; j++){
			    if(n%j==0)
		           count++;   
					}

				if(count==0)
		          return true;			       
				else
		         return false;
		       
	}
				
		
	}

Note: you can drag the code workspace to see the complete code

Post a Comment

0 Comments