Alice and Bob's Silly Game

  • + 0 comments

    Java

        public static String sillyGame(int n) {
    
            int player = 0;
                    Set<Integer> primes = new TreeSet<>();
    
            for (int i = 2; i <= n; i++){
                if (isPrime(i)){
                    primes.add(i);
                }
            }
    
            if (!primes.isEmpty()){
                player = primes.size() % 2;
            }
    
            return player == 0 ? "Bob" : "Alice";
    
        }
    
        private static boolean isPrime(int m) {
            // Corner case
            if (m <= 1)
                return false;
            // For m=2 or m=3 it will check
            if (m == 2 || m == 3)
                return true;
            // For multiple of 2 or 3 This will check
            if (m % 2 == 0 || m % 3 == 0)
                return false;
            // It will check all the others condition
            for (int i = 5; i <= Math.sqrt(m); i = i + 6)
                if (m % i == 0 || m % (i + 2) == 0)
                    return false;
    
            return true;
        }