Program 10:
import java.io.*;
class np //nearstprime
{
int posprime,negprime;
public void checkip(int n)
{ int i,c=0;
for(i=2;i<n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==0)
{
System.out.println("The number itself is a prime");
}
}
public static void checkpos(int n)
{
int cpos=0;
int m=n,c=0;
m=m+1;
for(int i=2;i<m;i++)
{
if(m%i==0)
c++;
}
if(c==0)
posprime=m;
else checkpos(m);//recursion
}
public static void checkneg(int n)
{ int cneg=0;
int m=n,c=0;
m=m-1;
for(int i=2;i<m;i++)
{
if(m%i==0)
c++;
}
if(c==0)
negprime=m;
else{
checkneg(m);//recursion
}}
public void printCalc(int n)
{
if((posprime-n)<(n-negprime))
{
System.out.println(posprime+" is nearest prime");
}
else if((n-negprime)<(posprime-n))
{
System.out.println(negprime+" is nearest prime");
}
else
System.out.println(negprime+" & "+ posprime+" both are nearest");
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number to check its nearest prime");
int num=Integer.parseInt(br.readLine());
np obj=new np();
obj.checkip(num);
obj.checkpos(num);
obj.checkneg(num);
obj.printCalc(num);
}
}
Nearest Prime Of A Number
For Example User inputted 100 then 101 is nearest prime
user inputs 102 then 103 and 101 are nearest primes.
user inputs 97 then 97 itself is a prime.
class np //nearstprime
{
int posprime,negprime;
public void checkip(int n)
{ int i,c=0;
for(i=2;i<n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==0)
{
System.out.println("The number itself is a prime");
}
}
public static void checkpos(int n)
{
int cpos=0;
int m=n,c=0;
m=m+1;
for(int i=2;i<m;i++)
{
if(m%i==0)
c++;
}
if(c==0)
posprime=m;
else checkpos(m);//recursion
}
public static void checkneg(int n)
{ int cneg=0;
int m=n,c=0;
m=m-1;
for(int i=2;i<m;i++)
{
if(m%i==0)
c++;
}
if(c==0)
negprime=m;
else{
checkneg(m);//recursion
}}
public void printCalc(int n)
{
if((posprime-n)<(n-negprime))
{
System.out.println(posprime+" is nearest prime");
}
else if((n-negprime)<(posprime-n))
{
System.out.println(negprime+" is nearest prime");
}
else
System.out.println(negprime+" & "+ posprime+" both are nearest");
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number to check its nearest prime");
int num=Integer.parseInt(br.readLine());
np obj=new np();
obj.checkip(num);
obj.checkpos(num);
obj.checkneg(num);
obj.printCalc(num);
}
}
posprime and negprime are global variables to store nearest prime greater then input and lesser than input
Very well use of recursion
ReplyDelete