Monday, February 10, 2014

Java Program On Finding The Longest Gap Between Two Non Prime Numbers



This is a java program, user will enter the lower and upper limit and program will show the longest gap between two non prime numbers along with the starting and ending non prime numbers.

Suppose user enters 2 as lower limit and 100 as upper limit, the output will be as follows:


import java.io.*;
 class NonPrime
{
  int arr[]=new int[100];
  int lrange,urange,i,x=0,lower,upper,gap;
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 public void takeRange()throws Exception
 {
  System.out.println(" Enter the Lower Limit:");
  lrange=Integer.parseInt(br.readLine());
  System.out.println(" Enter the Upper Limit:");
  urange=Integer.parseInt(br.readLine());
 for(i=lrange; i<=urange;i++)
 {
  if(isPrime(i))
   {
    arr[x++]=i;
    }
    }
    gap=0;
    for(i=x-1;i>0;i--)
    {
    if(arr[i]-arr[i-1]>gap)
    {
     gap=arr[i]-arr[i-1];
     lower=arr[i-1]-1;
     upper=arr[i]-1;
     }
     }
   System.out.print(" Maximum Gap = "+gap+ " Lower ="+ lower + " Upper="+upper);
  }
  boolean isPrime(int n)
  {
   int i;
   for(i=2;i
   {
    if(n%i==0)
    break;
    }
    if(i==n)
    return true;
    else
    return false;
    }
  public static void main(String args[])throws Exception
  {
   NonPrime object=new NonPrime ();
   object.takeRange();
   }
   }

Related PostBlueJ Programs on Number

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner