Repository navigation
Expand file tree
/
Copy pathNearestPrimeFromArray.java
More file actions
84 lines (77 loc) · 1.92 KB
/
Copy pathNearestPrimeFromArray.java
File metadata and controls
84 lines (77 loc) · 1.92 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
84
// Program to return a nearest Prime number from the array of user given number.
import java.util.Scanner;
public class NearestPrimeFromArray
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int n=scanner.nextInt();
int[] arr=new int[n];
System.out.println(" Enter the elements:");
for(int i=0;i<n;i++)
{
arr[i]=scanner.nextInt();
}
System.out.println(" Enter any number to print Nearest prime from array:");
int num=scanner.nextInt();
int x=nearestPrime(arr,num);
System.out.println("Nearest prime number:"+x);
scanner.close();
}
public static int nearestPrime(int[] arr,int num)
{
int x=num;
int y=num;
for(int i=0;i<arr.length;i++)
{
if(arr[i]==num)
return num;
}
while(true)
{
x++;
int c=0;
if(isPrime(x))
{
for(int i=0;i<arr.length;i++)
{
if(x==arr[i])
c++;
}
if(c!=0)
break;
}
}
while(true)
{
y--;
int c=0;
if(isPrime(y))
{
for(int i=0;i<arr.length;i++)
{
if(y==arr[i])
c++;
}
if(c!=0)
break;
}
}
if(x-num > num-y)
return y;
else
return x;
}
public static boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
}