-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimeGame.java
More file actions
88 lines (72 loc) · 1.69 KB
/
PrimeGame.java
File metadata and controls
88 lines (72 loc) · 1.69 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
85
86
87
88
/***********************************
* AlgoSolutions Project
* Filename: PrimeGame.java
* Author : malay
* Date : 21-Jun-2021
*
**********************************/
package com.contest.techgig.y2021;
import java.util.Scanner;
public class PrimeGame {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
int noOfTest = s.nextInt();
s.nextLine();
if (noOfTest < 1 || noOfTest > 10) {
System.exit(0);
}
for (int i = 0; i < noOfTest; i++) {
String testStr = s.nextLine();
if (testStr == null || testStr.trim().length() == 0) {
System.exit(0);
}
String[] testStrArr = testStr.split(" ");
int left = Integer.parseInt(testStrArr[0]);
int right = Integer.parseInt(testStrArr[1]);
int result = getMaximumPrimeDiff(left, right);
System.out.println(result);
}
s.close();
}
private static int getMaximumPrimeDiff(int left, int right) {
int minPrime = -1;
int maxPrime = -1;
// Start from left, stop when minimum prime no is found
while (left <= right) {
if (isPrime(left)) {
minPrime = left;
break;
}
left++;
}
// if reached end, then return -1, no prime number retieved
if (minPrime == -1) {
return minPrime;
}
// Start from right and navigate till we explore left, stop when maximum prime no is found
while (right >= left) {
if (isPrime(right)) {
maxPrime = right;
break;
}
right--;
}
return maxPrime - minPrime;
}
private static boolean isPrime(int value) {
if (value <= 1) {
return false;
}
if (value == 2) {
return true;
}
int num = 2;
while (value % num != 0) {
if (num >= value / 2) {
return true;
}
num++;
}
return false;
}
}