-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestprime.java
More file actions
83 lines (73 loc) · 1.21 KB
/
Nearestprime.java
File metadata and controls
83 lines (73 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.*;
class Nearestprime
{
public boolean primeornot(int n)
{
int count=0;
for(int i=2;i<n;i++) //n=20
{
if(n%i==0)
count++;
}
if(count==0)
return true;
else
return false; //returns false
}
int beforeprime(int n)
{
int c=0;
while(true)
{
if(primeornot(n))
return c;
else
{
n=n-1; // n=19
c++; //c=1
}
}
}
int afterprime(int n)//=20
{
int c=0;
while(true)
{
if(primeornot(n)) //23
return c;
else
{
n=n+1;
c++; //c=3;
}
}
}
void nearest()
{
Scanner obj=new Scanner(System.in);
System.out.println("enter number");
int n=obj.nextInt(); //n=20
int m1=beforeprime(n);// m1=1
int m2=afterprime(n);//m2=3
if(m1>m2) //1>3 -f
{
System.out.println("nearest prime:");
System.out.println(n+m2);
}
else if(m1<m2) //1<3 -t
{
System.out.println("nearest prime");
System.out.println(n-m1); // 20-1=19
}
else
{
System.out.println("nearest prime");
System.out.println((n-m1)+""+(n+m2));
}
}
public static void main(String args[])
{
Nearestprime obj=new Nearestprime();
obj.nearest();
}
}