Skip to content

Commit 8c60817

Browse files
add PrimeGame class
1 parent 4d34882 commit 8c60817

1 file changed

Lines changed: 98 additions & 0 deletions

File tree

CodeChef/PrimeGame.java

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import java.io.BufferedReader;
2+
import java.io.IOException;
3+
import java.io.InputStreamReader;
4+
5+
public class PrimeGame {
6+
7+
private static final int NUMBER = 1000000;
8+
private static final int[] array = new int[NUMBER + 1];
9+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
11+
public static void main(String[] args) throws IOException {
12+
13+
int t;
14+
int chefPlay;
15+
int divyamPlay;
16+
17+
boolean[] primes = getPrimesBySieveOfEratosthenes(NUMBER);
18+
setArrayWithPrimes(primes);
19+
20+
t = Integer.parseInt(br.readLine());
21+
22+
while (t-- >= 0) {
23+
24+
String line = br.readLine();
25+
String[] strings = line.split(" ");
26+
27+
chefPlay = Integer.parseInt(strings[0]);
28+
divyamPlay = Integer.parseInt(strings[1]);
29+
30+
checkWinner(chefPlay, divyamPlay);
31+
}
32+
33+
br.close();
34+
}
35+
36+
37+
/*
38+
Receives 2 plays and checks and prints the winner
39+
*/
40+
private static void checkWinner(int chefPlay, int divyamPlay) {
41+
if (array[chefPlay] <= divyamPlay) {
42+
System.out.println("Chef");
43+
}
44+
else {
45+
System.out.println("Divyam");
46+
}
47+
}
48+
49+
/*
50+
Receives a integer number and defines an boolean array with all primes smaller than or equal to
51+
the number using Sieve of Eratosthenes algorithm
52+
link: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
53+
*/
54+
private static boolean[] getPrimesBySieveOfEratosthenes(int number) {
55+
56+
/*
57+
Create a boolean array "prime[0..n]" and initialize
58+
all entries it as true. Each prime[i] will
59+
finally be false if i is Not a prime, else true.
60+
*/
61+
boolean[] prime = new boolean[number + 1];
62+
63+
for (int i = 0; i <= number; i++) {
64+
prime[i] = true;
65+
}
66+
67+
for (int p = 2; p * p <= number; p++) {
68+
69+
// If prime[p] is not changed, then it is a prime
70+
if (prime[p]) {
71+
// Update all multiples of p
72+
for (int i = p*p; i <= number; i += p) {
73+
prime[i] = false;
74+
}
75+
}
76+
}
77+
78+
return prime;
79+
}
80+
81+
/*
82+
Sets the array according to the givens primes array
83+
*/
84+
private static void setArrayWithPrimes(boolean[] primes) {
85+
86+
array[0] = 0;
87+
array[1] = 0;
88+
89+
for (int i = 2; i <= NUMBER; i++) {
90+
array[i] = array[i - 1];
91+
92+
if (primes[i]) {
93+
array[i] = array[i] + 1;
94+
}
95+
}
96+
}
97+
98+
}

0 commit comments

Comments
 (0)