Alice and Bob Problem Java
Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below.
The game begins with an integer num, used to create a unique integer from 1 to num, inclusive (i.e., ).
Set s=1, 2,... (num-1), number.
The two players alternate turns, while Alice always has the first turn.
The current player selects a prime number num from the set S for each move. After that, the player eliminates all of its multiples.
The game is won by the first person who is unable to move.
Bob and Alice had some fun. Print the name of the game's winner on a new line using the value for each game. Print Alice if she triumphs; print Bob if she loses.
Note: Each participant always plays optimally, which means they won't take a step that puts them at a disadvantage if there's a more advantageous one.
Input
The number of games Alice and Bob play is indicated by the integer G, which appears on the first line.
The next lines each include a single number, G, which describes a game, and Num describes a game.
Output
The output should display the winner of the game.
Java Program for Alice and bob
Filename: AliceBob.java
//Program for Alice and bob in Java
//importing the required packages
import java.io.*;
//package for reading the dynamic input from the user
import java. util.*;
public class AliceBob
{
static String winners(int num)
{
//the condition for the primes
boolean isPrimes[] = new boolean[num + 1];
Arrays.fill(isPrimes , true);
int counts = 0;
//the initial values are declared
isPrimes[0] = false;
isPrimes[1] = false;
//loop for iterating over all possibilities from 2 to num
for(int i = 2; i*i <= num; i++)
{
for(int j = 2*i; j <= num; j += i)
{
isPrimes[j] = false;
}
}
for(int i = 0; i <= num; i++)
{
//If the value is prime, then the count's variable value increases
if(isPrimes[i])
{
counts++;
}
}
//If the result obtained is divisible by 2;
// then it will return to "Bob". Else, “Alice."
if(counts % 2 == 0)
{
return "Bob";
}
else
{
return "Alice";
}
}
//main section of the program
public static void main(String[] args)
{
//the method for reading the dynamic values
Scanner sca = new Scanner(System.in);
int totalgames = sca.nextInt();
//loop will iterate over all games
for(int i = 0; i < totalgames; i++)
{
int num = sca.nextInt();
//display the result of the winner of the game
System.out.println("The winner of the game is: "+winners(num));
}
}
}
Output
4
23
The winner of the game is: Alice
12
The winner of the game is: Alice
1
The winner of the game is: Bob
78
The winner of the game is: Alice